OSDN Git Service

KVM: x86: Free wbinvd_dirty_mask if vCPU creation fails
[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 = array_index_nospec(
1998                                 msr - MSR_IA32_MC0_CTL,
1999                                 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2000
2001                         /* only 0 or all 1s can be written to IA32_MCi_CTL
2002                          * some Linux kernels though clear bit 10 in bank 4 to
2003                          * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2004                          * this to avoid an uncatched #GP in the guest
2005                          */
2006                         if ((offset & 0x3) == 0 &&
2007                             data != 0 && (data | (1 << 10)) != ~(u64)0)
2008                                 return -1;
2009                         vcpu->arch.mce_banks[offset] = data;
2010                         break;
2011                 }
2012                 return 1;
2013         }
2014         return 0;
2015 }
2016
2017 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2018 {
2019         struct kvm *kvm = vcpu->kvm;
2020         int lm = is_long_mode(vcpu);
2021         u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2022                 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2023         u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2024                 : kvm->arch.xen_hvm_config.blob_size_32;
2025         u32 page_num = data & ~PAGE_MASK;
2026         u64 page_addr = data & PAGE_MASK;
2027         u8 *page;
2028         int r;
2029
2030         r = -E2BIG;
2031         if (page_num >= blob_size)
2032                 goto out;
2033         r = -ENOMEM;
2034         page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2035         if (IS_ERR(page)) {
2036                 r = PTR_ERR(page);
2037                 goto out;
2038         }
2039         if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2040                 goto out_free;
2041         r = 0;
2042 out_free:
2043         kfree(page);
2044 out:
2045         return r;
2046 }
2047
2048 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2049 {
2050         gpa_t gpa = data & ~0x3f;
2051
2052         /* Bits 2:5 are reserved, Should be zero */
2053         if (data & 0x3c)
2054                 return 1;
2055
2056         vcpu->arch.apf.msr_val = data;
2057
2058         if (!(data & KVM_ASYNC_PF_ENABLED)) {
2059                 kvm_clear_async_pf_completion_queue(vcpu);
2060                 kvm_async_pf_hash_reset(vcpu);
2061                 return 0;
2062         }
2063
2064         if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2065                                         sizeof(u32)))
2066                 return 1;
2067
2068         vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2069         kvm_async_pf_wakeup_all(vcpu);
2070         return 0;
2071 }
2072
2073 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2074 {
2075         vcpu->arch.pv_time_enabled = false;
2076 }
2077
2078 static void accumulate_steal_time(struct kvm_vcpu *vcpu)
2079 {
2080         u64 delta;
2081
2082         if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2083                 return;
2084
2085         delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
2086         vcpu->arch.st.last_steal = current->sched_info.run_delay;
2087         vcpu->arch.st.accum_steal = delta;
2088 }
2089
2090 static void record_steal_time(struct kvm_vcpu *vcpu)
2091 {
2092         accumulate_steal_time(vcpu);
2093
2094         if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2095                 return;
2096
2097         if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2098                 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
2099                 return;
2100
2101         vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
2102         vcpu->arch.st.steal.version += 2;
2103         vcpu->arch.st.accum_steal = 0;
2104
2105         kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2106                 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2107 }
2108
2109 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2110 {
2111         bool pr = false;
2112         u32 msr = msr_info->index;
2113         u64 data = msr_info->data;
2114
2115         switch (msr) {
2116         case MSR_AMD64_NB_CFG:
2117         case MSR_IA32_UCODE_REV:
2118         case MSR_IA32_UCODE_WRITE:
2119         case MSR_VM_HSAVE_PA:
2120         case MSR_AMD64_PATCH_LOADER:
2121         case MSR_AMD64_BU_CFG2:
2122                 break;
2123
2124         case MSR_IA32_ARCH_CAPABILITIES:
2125                 if (!msr_info->host_initiated)
2126                         return 1;
2127                 vcpu->arch.arch_capabilities = data;
2128                 break;
2129         case MSR_EFER:
2130                 return set_efer(vcpu, msr_info);
2131         case MSR_K7_HWCR:
2132                 data &= ~(u64)0x40;     /* ignore flush filter disable */
2133                 data &= ~(u64)0x100;    /* ignore ignne emulation enable */
2134                 data &= ~(u64)0x8;      /* ignore TLB cache disable */
2135                 data &= ~(u64)0x40000;  /* ignore Mc status write enable */
2136                 if (data != 0) {
2137                         vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2138                                     data);
2139                         return 1;
2140                 }
2141                 break;
2142         case MSR_FAM10H_MMIO_CONF_BASE:
2143                 if (data != 0) {
2144                         vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2145                                     "0x%llx\n", data);
2146                         return 1;
2147                 }
2148                 break;
2149         case MSR_IA32_DEBUGCTLMSR:
2150                 if (!data) {
2151                         /* We support the non-activated case already */
2152                         break;
2153                 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2154                         /* Values other than LBR and BTF are vendor-specific,
2155                            thus reserved and should throw a #GP */
2156                         return 1;
2157                 }
2158                 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2159                             __func__, data);
2160                 break;
2161         case 0x200 ... 0x2ff:
2162                 return kvm_mtrr_set_msr(vcpu, msr, data);
2163         case MSR_IA32_APICBASE:
2164                 return kvm_set_apic_base(vcpu, msr_info);
2165         case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2166                 return kvm_x2apic_msr_write(vcpu, msr, data);
2167         case MSR_IA32_TSCDEADLINE:
2168                 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2169                 break;
2170         case MSR_IA32_TSC_ADJUST:
2171                 if (guest_cpuid_has_tsc_adjust(vcpu)) {
2172                         if (!msr_info->host_initiated) {
2173                                 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2174                                 adjust_tsc_offset_guest(vcpu, adj);
2175                         }
2176                         vcpu->arch.ia32_tsc_adjust_msr = data;
2177                 }
2178                 break;
2179         case MSR_IA32_MISC_ENABLE:
2180                 vcpu->arch.ia32_misc_enable_msr = data;
2181                 break;
2182         case MSR_IA32_SMBASE:
2183                 if (!msr_info->host_initiated)
2184                         return 1;
2185                 vcpu->arch.smbase = data;
2186                 break;
2187         case MSR_KVM_WALL_CLOCK_NEW:
2188         case MSR_KVM_WALL_CLOCK:
2189                 vcpu->kvm->arch.wall_clock = data;
2190                 kvm_write_wall_clock(vcpu->kvm, data);
2191                 break;
2192         case MSR_KVM_SYSTEM_TIME_NEW:
2193         case MSR_KVM_SYSTEM_TIME: {
2194                 u64 gpa_offset;
2195                 struct kvm_arch *ka = &vcpu->kvm->arch;
2196
2197                 kvmclock_reset(vcpu);
2198
2199                 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2200                         bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2201
2202                         if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2203                                 set_bit(KVM_REQ_MASTERCLOCK_UPDATE,
2204                                         &vcpu->requests);
2205
2206                         ka->boot_vcpu_runs_old_kvmclock = tmp;
2207                 }
2208
2209                 vcpu->arch.time = data;
2210                 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2211
2212                 /* we verify if the enable bit is set... */
2213                 if (!(data & 1))
2214                         break;
2215
2216                 gpa_offset = data & ~(PAGE_MASK | 1);
2217
2218                 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2219                      &vcpu->arch.pv_time, data & ~1ULL,
2220                      sizeof(struct pvclock_vcpu_time_info)))
2221                         vcpu->arch.pv_time_enabled = false;
2222                 else
2223                         vcpu->arch.pv_time_enabled = true;
2224
2225                 break;
2226         }
2227         case MSR_KVM_ASYNC_PF_EN:
2228                 if (kvm_pv_enable_async_pf(vcpu, data))
2229                         return 1;
2230                 break;
2231         case MSR_KVM_STEAL_TIME:
2232
2233                 if (unlikely(!sched_info_on()))
2234                         return 1;
2235
2236                 if (data & KVM_STEAL_RESERVED_MASK)
2237                         return 1;
2238
2239                 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2240                                                 data & KVM_STEAL_VALID_BITS,
2241                                                 sizeof(struct kvm_steal_time)))
2242                         return 1;
2243
2244                 vcpu->arch.st.msr_val = data;
2245
2246                 if (!(data & KVM_MSR_ENABLED))
2247                         break;
2248
2249                 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2250
2251                 break;
2252         case MSR_KVM_PV_EOI_EN:
2253                 if (kvm_lapic_enable_pv_eoi(vcpu, data))
2254                         return 1;
2255                 break;
2256
2257         case MSR_IA32_MCG_CTL:
2258         case MSR_IA32_MCG_STATUS:
2259         case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2260                 return set_msr_mce(vcpu, msr, data);
2261
2262         case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2263         case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2264                 pr = true; /* fall through */
2265         case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2266         case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2267                 if (kvm_pmu_is_valid_msr(vcpu, msr))
2268                         return kvm_pmu_set_msr(vcpu, msr_info);
2269
2270                 if (pr || data != 0)
2271                         vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2272                                     "0x%x data 0x%llx\n", msr, data);
2273                 break;
2274         case MSR_K7_CLK_CTL:
2275                 /*
2276                  * Ignore all writes to this no longer documented MSR.
2277                  * Writes are only relevant for old K7 processors,
2278                  * all pre-dating SVM, but a recommended workaround from
2279                  * AMD for these chips. It is possible to specify the
2280                  * affected processor models on the command line, hence
2281                  * the need to ignore the workaround.
2282                  */
2283                 break;
2284         case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2285         case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2286         case HV_X64_MSR_CRASH_CTL:
2287                 return kvm_hv_set_msr_common(vcpu, msr, data,
2288                                              msr_info->host_initiated);
2289         case MSR_IA32_BBL_CR_CTL3:
2290                 /* Drop writes to this legacy MSR -- see rdmsr
2291                  * counterpart for further detail.
2292                  */
2293                 vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
2294                 break;
2295         case MSR_AMD64_OSVW_ID_LENGTH:
2296                 if (!guest_cpuid_has_osvw(vcpu))
2297                         return 1;
2298                 vcpu->arch.osvw.length = data;
2299                 break;
2300         case MSR_AMD64_OSVW_STATUS:
2301                 if (!guest_cpuid_has_osvw(vcpu))
2302                         return 1;
2303                 vcpu->arch.osvw.status = data;
2304                 break;
2305         default:
2306                 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2307                         return xen_hvm_config(vcpu, data);
2308                 if (kvm_pmu_is_valid_msr(vcpu, msr))
2309                         return kvm_pmu_set_msr(vcpu, msr_info);
2310                 if (!ignore_msrs) {
2311                         vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
2312                                     msr, data);
2313                         return 1;
2314                 } else {
2315                         vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
2316                                     msr, data);
2317                         break;
2318                 }
2319         }
2320         return 0;
2321 }
2322 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2323
2324
2325 /*
2326  * Reads an msr value (of 'msr_index') into 'pdata'.
2327  * Returns 0 on success, non-0 otherwise.
2328  * Assumes vcpu_load() was already called.
2329  */
2330 int kvm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2331 {
2332         return kvm_x86_ops->get_msr(vcpu, msr);
2333 }
2334 EXPORT_SYMBOL_GPL(kvm_get_msr);
2335
2336 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2337 {
2338         u64 data;
2339         u64 mcg_cap = vcpu->arch.mcg_cap;
2340         unsigned bank_num = mcg_cap & 0xff;
2341
2342         switch (msr) {
2343         case MSR_IA32_P5_MC_ADDR:
2344         case MSR_IA32_P5_MC_TYPE:
2345                 data = 0;
2346                 break;
2347         case MSR_IA32_MCG_CAP:
2348                 data = vcpu->arch.mcg_cap;
2349                 break;
2350         case MSR_IA32_MCG_CTL:
2351                 if (!(mcg_cap & MCG_CTL_P))
2352                         return 1;
2353                 data = vcpu->arch.mcg_ctl;
2354                 break;
2355         case MSR_IA32_MCG_STATUS:
2356                 data = vcpu->arch.mcg_status;
2357                 break;
2358         default:
2359                 if (msr >= MSR_IA32_MC0_CTL &&
2360                     msr < MSR_IA32_MCx_CTL(bank_num)) {
2361                         u32 offset = array_index_nospec(
2362                                 msr - MSR_IA32_MC0_CTL,
2363                                 MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
2364
2365                         data = vcpu->arch.mce_banks[offset];
2366                         break;
2367                 }
2368                 return 1;
2369         }
2370         *pdata = data;
2371         return 0;
2372 }
2373
2374 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2375 {
2376         switch (msr_info->index) {
2377         case MSR_IA32_PLATFORM_ID:
2378         case MSR_IA32_EBL_CR_POWERON:
2379         case MSR_IA32_DEBUGCTLMSR:
2380         case MSR_IA32_LASTBRANCHFROMIP:
2381         case MSR_IA32_LASTBRANCHTOIP:
2382         case MSR_IA32_LASTINTFROMIP:
2383         case MSR_IA32_LASTINTTOIP:
2384         case MSR_K8_SYSCFG:
2385         case MSR_K8_TSEG_ADDR:
2386         case MSR_K8_TSEG_MASK:
2387         case MSR_K7_HWCR:
2388         case MSR_VM_HSAVE_PA:
2389         case MSR_K8_INT_PENDING_MSG:
2390         case MSR_AMD64_NB_CFG:
2391         case MSR_FAM10H_MMIO_CONF_BASE:
2392         case MSR_AMD64_BU_CFG2:
2393                 msr_info->data = 0;
2394                 break;
2395         case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2396         case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2397         case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2398         case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2399                 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2400                         return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2401                 msr_info->data = 0;
2402                 break;
2403         case MSR_IA32_UCODE_REV:
2404                 msr_info->data = 0x100000000ULL;
2405                 break;
2406         case MSR_IA32_ARCH_CAPABILITIES:
2407                 if (!msr_info->host_initiated &&
2408                     !guest_cpuid_has_arch_capabilities(vcpu))
2409                         return 1;
2410                 msr_info->data = vcpu->arch.arch_capabilities;
2411                 break;
2412         case MSR_MTRRcap:
2413         case 0x200 ... 0x2ff:
2414                 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
2415         case 0xcd: /* fsb frequency */
2416                 msr_info->data = 3;
2417                 break;
2418                 /*
2419                  * MSR_EBC_FREQUENCY_ID
2420                  * Conservative value valid for even the basic CPU models.
2421                  * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2422                  * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2423                  * and 266MHz for model 3, or 4. Set Core Clock
2424                  * Frequency to System Bus Frequency Ratio to 1 (bits
2425                  * 31:24) even though these are only valid for CPU
2426                  * models > 2, however guests may end up dividing or
2427                  * multiplying by zero otherwise.
2428                  */
2429         case MSR_EBC_FREQUENCY_ID:
2430                 msr_info->data = 1 << 24;
2431                 break;
2432         case MSR_IA32_APICBASE:
2433                 msr_info->data = kvm_get_apic_base(vcpu);
2434                 break;
2435         case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2436                 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
2437                 break;
2438         case MSR_IA32_TSCDEADLINE:
2439                 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
2440                 break;
2441         case MSR_IA32_TSC_ADJUST:
2442                 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2443                 break;
2444         case MSR_IA32_MISC_ENABLE:
2445                 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
2446                 break;
2447         case MSR_IA32_SMBASE:
2448                 if (!msr_info->host_initiated)
2449                         return 1;
2450                 msr_info->data = vcpu->arch.smbase;
2451                 break;
2452         case MSR_IA32_PERF_STATUS:
2453                 /* TSC increment by tick */
2454                 msr_info->data = 1000ULL;
2455                 /* CPU multiplier */
2456                 msr_info->data |= (((uint64_t)4ULL) << 40);
2457                 break;
2458         case MSR_EFER:
2459                 msr_info->data = vcpu->arch.efer;
2460                 break;
2461         case MSR_KVM_WALL_CLOCK:
2462         case MSR_KVM_WALL_CLOCK_NEW:
2463                 msr_info->data = vcpu->kvm->arch.wall_clock;
2464                 break;
2465         case MSR_KVM_SYSTEM_TIME:
2466         case MSR_KVM_SYSTEM_TIME_NEW:
2467                 msr_info->data = vcpu->arch.time;
2468                 break;
2469         case MSR_KVM_ASYNC_PF_EN:
2470                 msr_info->data = vcpu->arch.apf.msr_val;
2471                 break;
2472         case MSR_KVM_STEAL_TIME:
2473                 msr_info->data = vcpu->arch.st.msr_val;
2474                 break;
2475         case MSR_KVM_PV_EOI_EN:
2476                 msr_info->data = vcpu->arch.pv_eoi.msr_val;
2477                 break;
2478         case MSR_IA32_P5_MC_ADDR:
2479         case MSR_IA32_P5_MC_TYPE:
2480         case MSR_IA32_MCG_CAP:
2481         case MSR_IA32_MCG_CTL:
2482         case MSR_IA32_MCG_STATUS:
2483         case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2484                 return get_msr_mce(vcpu, msr_info->index, &msr_info->data);
2485         case MSR_K7_CLK_CTL:
2486                 /*
2487                  * Provide expected ramp-up count for K7. All other
2488                  * are set to zero, indicating minimum divisors for
2489                  * every field.
2490                  *
2491                  * This prevents guest kernels on AMD host with CPU
2492                  * type 6, model 8 and higher from exploding due to
2493                  * the rdmsr failing.
2494                  */
2495                 msr_info->data = 0x20000000;
2496                 break;
2497         case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2498         case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2499         case HV_X64_MSR_CRASH_CTL:
2500                 return kvm_hv_get_msr_common(vcpu,
2501                                              msr_info->index, &msr_info->data);
2502                 break;
2503         case MSR_IA32_BBL_CR_CTL3:
2504                 /* This legacy MSR exists but isn't fully documented in current
2505                  * silicon.  It is however accessed by winxp in very narrow
2506                  * scenarios where it sets bit #19, itself documented as
2507                  * a "reserved" bit.  Best effort attempt to source coherent
2508                  * read data here should the balance of the register be
2509                  * interpreted by the guest:
2510                  *
2511                  * L2 cache control register 3: 64GB range, 256KB size,
2512                  * enabled, latency 0x1, configured
2513                  */
2514                 msr_info->data = 0xbe702111;
2515                 break;
2516         case MSR_AMD64_OSVW_ID_LENGTH:
2517                 if (!guest_cpuid_has_osvw(vcpu))
2518                         return 1;
2519                 msr_info->data = vcpu->arch.osvw.length;
2520                 break;
2521         case MSR_AMD64_OSVW_STATUS:
2522                 if (!guest_cpuid_has_osvw(vcpu))
2523                         return 1;
2524                 msr_info->data = vcpu->arch.osvw.status;
2525                 break;
2526         default:
2527                 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2528                         return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2529                 if (!ignore_msrs) {
2530                         vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr_info->index);
2531                         return 1;
2532                 } else {
2533                         vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr_info->index);
2534                         msr_info->data = 0;
2535                 }
2536                 break;
2537         }
2538         return 0;
2539 }
2540 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2541
2542 /*
2543  * Read or write a bunch of msrs. All parameters are kernel addresses.
2544  *
2545  * @return number of msrs set successfully.
2546  */
2547 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2548                     struct kvm_msr_entry *entries,
2549                     int (*do_msr)(struct kvm_vcpu *vcpu,
2550                                   unsigned index, u64 *data))
2551 {
2552         int i, idx;
2553
2554         idx = srcu_read_lock(&vcpu->kvm->srcu);
2555         for (i = 0; i < msrs->nmsrs; ++i)
2556                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2557                         break;
2558         srcu_read_unlock(&vcpu->kvm->srcu, idx);
2559
2560         return i;
2561 }
2562
2563 /*
2564  * Read or write a bunch of msrs. Parameters are user addresses.
2565  *
2566  * @return number of msrs set successfully.
2567  */
2568 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2569                   int (*do_msr)(struct kvm_vcpu *vcpu,
2570                                 unsigned index, u64 *data),
2571                   int writeback)
2572 {
2573         struct kvm_msrs msrs;
2574         struct kvm_msr_entry *entries;
2575         int r, n;
2576         unsigned size;
2577
2578         r = -EFAULT;
2579         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2580                 goto out;
2581
2582         r = -E2BIG;
2583         if (msrs.nmsrs >= MAX_IO_MSRS)
2584                 goto out;
2585
2586         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2587         entries = memdup_user(user_msrs->entries, size);
2588         if (IS_ERR(entries)) {
2589                 r = PTR_ERR(entries);
2590                 goto out;
2591         }
2592
2593         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2594         if (r < 0)
2595                 goto out_free;
2596
2597         r = -EFAULT;
2598         if (writeback && copy_to_user(user_msrs->entries, entries, size))
2599                 goto out_free;
2600
2601         r = n;
2602
2603 out_free:
2604         kfree(entries);
2605 out:
2606         return r;
2607 }
2608
2609 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2610 {
2611         int r;
2612
2613         switch (ext) {
2614         case KVM_CAP_IRQCHIP:
2615         case KVM_CAP_HLT:
2616         case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2617         case KVM_CAP_SET_TSS_ADDR:
2618         case KVM_CAP_EXT_CPUID:
2619         case KVM_CAP_EXT_EMUL_CPUID:
2620         case KVM_CAP_CLOCKSOURCE:
2621         case KVM_CAP_PIT:
2622         case KVM_CAP_NOP_IO_DELAY:
2623         case KVM_CAP_MP_STATE:
2624         case KVM_CAP_SYNC_MMU:
2625         case KVM_CAP_USER_NMI:
2626         case KVM_CAP_REINJECT_CONTROL:
2627         case KVM_CAP_IRQ_INJECT_STATUS:
2628         case KVM_CAP_IOEVENTFD:
2629         case KVM_CAP_IOEVENTFD_NO_LENGTH:
2630         case KVM_CAP_PIT2:
2631         case KVM_CAP_PIT_STATE2:
2632         case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2633         case KVM_CAP_XEN_HVM:
2634         case KVM_CAP_ADJUST_CLOCK:
2635         case KVM_CAP_VCPU_EVENTS:
2636         case KVM_CAP_HYPERV:
2637         case KVM_CAP_HYPERV_VAPIC:
2638         case KVM_CAP_HYPERV_SPIN:
2639         case KVM_CAP_PCI_SEGMENT:
2640         case KVM_CAP_DEBUGREGS:
2641         case KVM_CAP_X86_ROBUST_SINGLESTEP:
2642         case KVM_CAP_XSAVE:
2643         case KVM_CAP_ASYNC_PF:
2644         case KVM_CAP_GET_TSC_KHZ:
2645         case KVM_CAP_KVMCLOCK_CTRL:
2646         case KVM_CAP_READONLY_MEM:
2647         case KVM_CAP_HYPERV_TIME:
2648         case KVM_CAP_IOAPIC_POLARITY_IGNORED:
2649         case KVM_CAP_TSC_DEADLINE_TIMER:
2650         case KVM_CAP_ENABLE_CAP_VM:
2651         case KVM_CAP_DISABLE_QUIRKS:
2652         case KVM_CAP_SET_BOOT_CPU_ID:
2653         case KVM_CAP_SPLIT_IRQCHIP:
2654 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2655         case KVM_CAP_ASSIGN_DEV_IRQ:
2656         case KVM_CAP_PCI_2_3:
2657 #endif
2658                 r = 1;
2659                 break;
2660         case KVM_CAP_X86_SMM:
2661                 /* SMBASE is usually relocated above 1M on modern chipsets,
2662                  * and SMM handlers might indeed rely on 4G segment limits,
2663                  * so do not report SMM to be available if real mode is
2664                  * emulated via vm86 mode.  Still, do not go to great lengths
2665                  * to avoid userspace's usage of the feature, because it is a
2666                  * fringe case that is not enabled except via specific settings
2667                  * of the module parameters.
2668                  */
2669                 r = kvm_x86_ops->has_emulated_msr(MSR_IA32_SMBASE);
2670                 break;
2671         case KVM_CAP_COALESCED_MMIO:
2672                 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
2673                 break;
2674         case KVM_CAP_VAPIC:
2675                 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2676                 break;
2677         case KVM_CAP_NR_VCPUS:
2678                 r = KVM_SOFT_MAX_VCPUS;
2679                 break;
2680         case KVM_CAP_MAX_VCPUS:
2681                 r = KVM_MAX_VCPUS;
2682                 break;
2683         case KVM_CAP_NR_MEMSLOTS:
2684                 r = KVM_USER_MEM_SLOTS;
2685                 break;
2686         case KVM_CAP_PV_MMU:    /* obsolete */
2687                 r = 0;
2688                 break;
2689 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
2690         case KVM_CAP_IOMMU:
2691                 r = iommu_present(&pci_bus_type);
2692                 break;
2693 #endif
2694         case KVM_CAP_MCE:
2695                 r = KVM_MAX_MCE_BANKS;
2696                 break;
2697         case KVM_CAP_XCRS:
2698                 r = cpu_has_xsave;
2699                 break;
2700         case KVM_CAP_TSC_CONTROL:
2701                 r = kvm_has_tsc_control;
2702                 break;
2703         default:
2704                 r = 0;
2705                 break;
2706         }
2707         return r;
2708
2709 }
2710
2711 long kvm_arch_dev_ioctl(struct file *filp,
2712                         unsigned int ioctl, unsigned long arg)
2713 {
2714         void __user *argp = (void __user *)arg;
2715         long r;
2716
2717         switch (ioctl) {
2718         case KVM_GET_MSR_INDEX_LIST: {
2719                 struct kvm_msr_list __user *user_msr_list = argp;
2720                 struct kvm_msr_list msr_list;
2721                 unsigned n;
2722
2723                 r = -EFAULT;
2724                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2725                         goto out;
2726                 n = msr_list.nmsrs;
2727                 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
2728                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2729                         goto out;
2730                 r = -E2BIG;
2731                 if (n < msr_list.nmsrs)
2732                         goto out;
2733                 r = -EFAULT;
2734                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2735                                  num_msrs_to_save * sizeof(u32)))
2736                         goto out;
2737                 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2738                                  &emulated_msrs,
2739                                  num_emulated_msrs * sizeof(u32)))
2740                         goto out;
2741                 r = 0;
2742                 break;
2743         }
2744         case KVM_GET_SUPPORTED_CPUID:
2745         case KVM_GET_EMULATED_CPUID: {
2746                 struct kvm_cpuid2 __user *cpuid_arg = argp;
2747                 struct kvm_cpuid2 cpuid;
2748
2749                 r = -EFAULT;
2750                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2751                         goto out;
2752
2753                 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
2754                                             ioctl);
2755                 if (r)
2756                         goto out;
2757
2758                 r = -EFAULT;
2759                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2760                         goto out;
2761                 r = 0;
2762                 break;
2763         }
2764         case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2765                 u64 mce_cap;
2766
2767                 mce_cap = KVM_MCE_CAP_SUPPORTED;
2768                 r = -EFAULT;
2769                 if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
2770                         goto out;
2771                 r = 0;
2772                 break;
2773         }
2774         default:
2775                 r = -EINVAL;
2776         }
2777 out:
2778         return r;
2779 }
2780
2781 static void wbinvd_ipi(void *garbage)
2782 {
2783         wbinvd();
2784 }
2785
2786 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2787 {
2788         return kvm_arch_has_noncoherent_dma(vcpu->kvm);
2789 }
2790
2791 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2792 {
2793         /* Address WBINVD may be executed by guest */
2794         if (need_emulate_wbinvd(vcpu)) {
2795                 if (kvm_x86_ops->has_wbinvd_exit())
2796                         cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2797                 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2798                         smp_call_function_single(vcpu->cpu,
2799                                         wbinvd_ipi, NULL, 1);
2800         }
2801
2802         kvm_x86_ops->vcpu_load(vcpu, cpu);
2803
2804         /* Apply any externally detected TSC adjustments (due to suspend) */
2805         if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
2806                 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
2807                 vcpu->arch.tsc_offset_adjustment = 0;
2808                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2809         }
2810
2811         if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2812                 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
2813                                 rdtsc() - vcpu->arch.last_host_tsc;
2814                 if (tsc_delta < 0)
2815                         mark_tsc_unstable("KVM discovered backwards TSC");
2816                 if (check_tsc_unstable()) {
2817                         u64 offset = kvm_compute_tsc_offset(vcpu,
2818                                                 vcpu->arch.last_guest_tsc);
2819                         kvm_x86_ops->write_tsc_offset(vcpu, offset);
2820                         vcpu->arch.tsc_catchup = 1;
2821                 }
2822                 /*
2823                  * On a host with synchronized TSC, there is no need to update
2824                  * kvmclock on vcpu->cpu migration
2825                  */
2826                 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
2827                         kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2828                 if (vcpu->cpu != cpu)
2829                         kvm_migrate_timers(vcpu);
2830                 vcpu->cpu = cpu;
2831         }
2832
2833         kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2834 }
2835
2836 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2837 {
2838         kvm_x86_ops->vcpu_put(vcpu);
2839         kvm_put_guest_fpu(vcpu);
2840         vcpu->arch.last_host_tsc = rdtsc();
2841         /*
2842          * If userspace has set any breakpoints or watchpoints, dr6 is restored
2843          * on every vmexit, but if not, we might have a stale dr6 from the
2844          * guest. do_debug expects dr6 to be cleared after it runs, do the same.
2845          */
2846         set_debugreg(0, 6);
2847 }
2848
2849 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2850                                     struct kvm_lapic_state *s)
2851 {
2852         kvm_x86_ops->sync_pir_to_irr(vcpu);
2853         memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
2854
2855         return 0;
2856 }
2857
2858 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2859                                     struct kvm_lapic_state *s)
2860 {
2861         kvm_apic_post_state_restore(vcpu, s);
2862         update_cr8_intercept(vcpu);
2863
2864         return 0;
2865 }
2866
2867 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
2868 {
2869         return (!lapic_in_kernel(vcpu) ||
2870                 kvm_apic_accept_pic_intr(vcpu));
2871 }
2872
2873 /*
2874  * if userspace requested an interrupt window, check that the
2875  * interrupt window is open.
2876  *
2877  * No need to exit to userspace if we already have an interrupt queued.
2878  */
2879 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
2880 {
2881         return kvm_arch_interrupt_allowed(vcpu) &&
2882                 !kvm_cpu_has_interrupt(vcpu) &&
2883                 !kvm_event_needs_reinjection(vcpu) &&
2884                 kvm_cpu_accept_dm_intr(vcpu);
2885 }
2886
2887 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2888                                     struct kvm_interrupt *irq)
2889 {
2890         if (irq->irq >= KVM_NR_INTERRUPTS)
2891                 return -EINVAL;
2892
2893         if (!irqchip_in_kernel(vcpu->kvm)) {
2894                 kvm_queue_interrupt(vcpu, irq->irq, false);
2895                 kvm_make_request(KVM_REQ_EVENT, vcpu);
2896                 return 0;
2897         }
2898
2899         /*
2900          * With in-kernel LAPIC, we only use this to inject EXTINT, so
2901          * fail for in-kernel 8259.
2902          */
2903         if (pic_in_kernel(vcpu->kvm))
2904                 return -ENXIO;
2905
2906         if (vcpu->arch.pending_external_vector != -1)
2907                 return -EEXIST;
2908
2909         vcpu->arch.pending_external_vector = irq->irq;
2910         kvm_make_request(KVM_REQ_EVENT, vcpu);
2911         return 0;
2912 }
2913
2914 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
2915 {
2916         kvm_inject_nmi(vcpu);
2917
2918         return 0;
2919 }
2920
2921 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
2922 {
2923         kvm_make_request(KVM_REQ_SMI, vcpu);
2924
2925         return 0;
2926 }
2927
2928 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
2929                                            struct kvm_tpr_access_ctl *tac)
2930 {
2931         if (tac->flags)
2932                 return -EINVAL;
2933         vcpu->arch.tpr_access_reporting = !!tac->enabled;
2934         return 0;
2935 }
2936
2937 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
2938                                         u64 mcg_cap)
2939 {
2940         int r;
2941         unsigned bank_num = mcg_cap & 0xff, bank;
2942
2943         r = -EINVAL;
2944         if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
2945                 goto out;
2946         if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
2947                 goto out;
2948         r = 0;
2949         vcpu->arch.mcg_cap = mcg_cap;
2950         /* Init IA32_MCG_CTL to all 1s */
2951         if (mcg_cap & MCG_CTL_P)
2952                 vcpu->arch.mcg_ctl = ~(u64)0;
2953         /* Init IA32_MCi_CTL to all 1s */
2954         for (bank = 0; bank < bank_num; bank++)
2955                 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
2956 out:
2957         return r;
2958 }
2959
2960 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
2961                                       struct kvm_x86_mce *mce)
2962 {
2963         u64 mcg_cap = vcpu->arch.mcg_cap;
2964         unsigned bank_num = mcg_cap & 0xff;
2965         u64 *banks = vcpu->arch.mce_banks;
2966
2967         if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
2968                 return -EINVAL;
2969         /*
2970          * if IA32_MCG_CTL is not all 1s, the uncorrected error
2971          * reporting is disabled
2972          */
2973         if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
2974             vcpu->arch.mcg_ctl != ~(u64)0)
2975                 return 0;
2976         banks += 4 * mce->bank;
2977         /*
2978          * if IA32_MCi_CTL is not all 1s, the uncorrected error
2979          * reporting is disabled for the bank
2980          */
2981         if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
2982                 return 0;
2983         if (mce->status & MCI_STATUS_UC) {
2984                 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
2985                     !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
2986                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2987                         return 0;
2988                 }
2989                 if (banks[1] & MCI_STATUS_VAL)
2990                         mce->status |= MCI_STATUS_OVER;
2991                 banks[2] = mce->addr;
2992                 banks[3] = mce->misc;
2993                 vcpu->arch.mcg_status = mce->mcg_status;
2994                 banks[1] = mce->status;
2995                 kvm_queue_exception(vcpu, MC_VECTOR);
2996         } else if (!(banks[1] & MCI_STATUS_VAL)
2997                    || !(banks[1] & MCI_STATUS_UC)) {
2998                 if (banks[1] & MCI_STATUS_VAL)
2999                         mce->status |= MCI_STATUS_OVER;
3000                 banks[2] = mce->addr;
3001                 banks[3] = mce->misc;
3002                 banks[1] = mce->status;
3003         } else
3004                 banks[1] |= MCI_STATUS_OVER;
3005         return 0;
3006 }
3007
3008 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3009                                                struct kvm_vcpu_events *events)
3010 {
3011         process_nmi(vcpu);
3012         events->exception.injected =
3013                 vcpu->arch.exception.pending &&
3014                 !kvm_exception_is_soft(vcpu->arch.exception.nr);
3015         events->exception.nr = vcpu->arch.exception.nr;
3016         events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3017         events->exception.pad = 0;
3018         events->exception.error_code = vcpu->arch.exception.error_code;
3019
3020         events->interrupt.injected =
3021                 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
3022         events->interrupt.nr = vcpu->arch.interrupt.nr;
3023         events->interrupt.soft = 0;
3024         events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
3025
3026         events->nmi.injected = vcpu->arch.nmi_injected;
3027         events->nmi.pending = vcpu->arch.nmi_pending != 0;
3028         events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
3029         events->nmi.pad = 0;
3030
3031         events->sipi_vector = 0; /* never valid when reporting to user space */
3032
3033         events->smi.smm = is_smm(vcpu);
3034         events->smi.pending = vcpu->arch.smi_pending;
3035         events->smi.smm_inside_nmi =
3036                 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3037         events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3038
3039         events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3040                          | KVM_VCPUEVENT_VALID_SHADOW
3041                          | KVM_VCPUEVENT_VALID_SMM);
3042         memset(&events->reserved, 0, sizeof(events->reserved));
3043 }
3044
3045 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags);
3046
3047 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3048                                               struct kvm_vcpu_events *events)
3049 {
3050         if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3051                               | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3052                               | KVM_VCPUEVENT_VALID_SHADOW
3053                               | KVM_VCPUEVENT_VALID_SMM))
3054                 return -EINVAL;
3055
3056         if (events->exception.injected &&
3057             (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
3058                 return -EINVAL;
3059
3060         /* INITs are latched while in SMM */
3061         if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
3062             (events->smi.smm || events->smi.pending) &&
3063             vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
3064                 return -EINVAL;
3065
3066         process_nmi(vcpu);
3067         vcpu->arch.exception.pending = events->exception.injected;
3068         vcpu->arch.exception.nr = events->exception.nr;
3069         vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3070         vcpu->arch.exception.error_code = events->exception.error_code;
3071
3072         vcpu->arch.interrupt.pending = events->interrupt.injected;
3073         vcpu->arch.interrupt.nr = events->interrupt.nr;
3074         vcpu->arch.interrupt.soft = events->interrupt.soft;
3075         if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3076                 kvm_x86_ops->set_interrupt_shadow(vcpu,
3077                                                   events->interrupt.shadow);
3078
3079         vcpu->arch.nmi_injected = events->nmi.injected;
3080         if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3081                 vcpu->arch.nmi_pending = events->nmi.pending;
3082         kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
3083
3084         if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3085             kvm_vcpu_has_lapic(vcpu))
3086                 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3087
3088         if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
3089                 u32 hflags = vcpu->arch.hflags;
3090                 if (events->smi.smm)
3091                         hflags |= HF_SMM_MASK;
3092                 else
3093                         hflags &= ~HF_SMM_MASK;
3094                 kvm_set_hflags(vcpu, hflags);
3095
3096                 vcpu->arch.smi_pending = events->smi.pending;
3097                 if (events->smi.smm_inside_nmi)
3098                         vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
3099                 else
3100                         vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
3101                 if (kvm_vcpu_has_lapic(vcpu)) {
3102                         if (events->smi.latched_init)
3103                                 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3104                         else
3105                                 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3106                 }
3107         }
3108
3109         kvm_make_request(KVM_REQ_EVENT, vcpu);
3110
3111         return 0;
3112 }
3113
3114 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3115                                              struct kvm_debugregs *dbgregs)
3116 {
3117         unsigned long val;
3118
3119         memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3120         kvm_get_dr(vcpu, 6, &val);
3121         dbgregs->dr6 = val;
3122         dbgregs->dr7 = vcpu->arch.dr7;
3123         dbgregs->flags = 0;
3124         memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3125 }
3126
3127 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3128                                             struct kvm_debugregs *dbgregs)
3129 {
3130         if (dbgregs->flags)
3131                 return -EINVAL;
3132
3133         if (dbgregs->dr6 & ~0xffffffffull)
3134                 return -EINVAL;
3135         if (dbgregs->dr7 & ~0xffffffffull)
3136                 return -EINVAL;
3137
3138         memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3139         kvm_update_dr0123(vcpu);
3140         vcpu->arch.dr6 = dbgregs->dr6;
3141         kvm_update_dr6(vcpu);
3142         vcpu->arch.dr7 = dbgregs->dr7;
3143         kvm_update_dr7(vcpu);
3144
3145         return 0;
3146 }
3147
3148 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
3149
3150 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
3151 {
3152         struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3153         u64 xstate_bv = xsave->header.xfeatures;
3154         u64 valid;
3155
3156         /*
3157          * Copy legacy XSAVE area, to avoid complications with CPUID
3158          * leaves 0 and 1 in the loop below.
3159          */
3160         memcpy(dest, xsave, XSAVE_HDR_OFFSET);
3161
3162         /* Set XSTATE_BV */
3163         xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
3164         *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
3165
3166         /*
3167          * Copy each region from the possibly compacted offset to the
3168          * non-compacted offset.
3169          */
3170         valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3171         while (valid) {
3172                 u64 feature = valid & -valid;
3173                 int index = fls64(feature) - 1;
3174                 void *src = get_xsave_addr(xsave, feature);
3175
3176                 if (src) {
3177                         u32 size, offset, ecx, edx;
3178                         cpuid_count(XSTATE_CPUID, index,
3179                                     &size, &offset, &ecx, &edx);
3180                         memcpy(dest + offset, src, size);
3181                 }
3182
3183                 valid -= feature;
3184         }
3185 }
3186
3187 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
3188 {
3189         struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3190         u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
3191         u64 valid;
3192
3193         /*
3194          * Copy legacy XSAVE area, to avoid complications with CPUID
3195          * leaves 0 and 1 in the loop below.
3196          */
3197         memcpy(xsave, src, XSAVE_HDR_OFFSET);
3198
3199         /* Set XSTATE_BV and possibly XCOMP_BV.  */
3200         xsave->header.xfeatures = xstate_bv;
3201         if (cpu_has_xsaves)
3202                 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
3203
3204         /*
3205          * Copy each region from the non-compacted offset to the
3206          * possibly compacted offset.
3207          */
3208         valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3209         while (valid) {
3210                 u64 feature = valid & -valid;
3211                 int index = fls64(feature) - 1;
3212                 void *dest = get_xsave_addr(xsave, feature);
3213
3214                 if (dest) {
3215                         u32 size, offset, ecx, edx;
3216                         cpuid_count(XSTATE_CPUID, index,
3217                                     &size, &offset, &ecx, &edx);
3218                         memcpy(dest, src + offset, size);
3219                 }
3220
3221                 valid -= feature;
3222         }
3223 }
3224
3225 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3226                                          struct kvm_xsave *guest_xsave)
3227 {
3228         if (cpu_has_xsave) {
3229                 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
3230                 fill_xsave((u8 *) guest_xsave->region, vcpu);
3231         } else {
3232                 memcpy(guest_xsave->region,
3233                         &vcpu->arch.guest_fpu.state.fxsave,
3234                         sizeof(struct fxregs_state));
3235                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3236                         XFEATURE_MASK_FPSSE;
3237         }
3238 }
3239
3240 #define XSAVE_MXCSR_OFFSET 24
3241
3242 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3243                                         struct kvm_xsave *guest_xsave)
3244 {
3245         u64 xstate_bv =
3246                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3247         u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
3248
3249         if (cpu_has_xsave) {
3250                 /*
3251                  * Here we allow setting states that are not present in
3252                  * CPUID leaf 0xD, index 0, EDX:EAX.  This is for compatibility
3253                  * with old userspace.
3254                  */
3255                 if (xstate_bv & ~kvm_supported_xcr0() ||
3256                         mxcsr & ~mxcsr_feature_mask)
3257                         return -EINVAL;
3258                 load_xsave(vcpu, (u8 *)guest_xsave->region);
3259         } else {
3260                 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
3261                         mxcsr & ~mxcsr_feature_mask)
3262                         return -EINVAL;
3263                 memcpy(&vcpu->arch.guest_fpu.state.fxsave,
3264                         guest_xsave->region, sizeof(struct fxregs_state));
3265         }
3266         return 0;
3267 }
3268
3269 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3270                                         struct kvm_xcrs *guest_xcrs)
3271 {
3272         if (!cpu_has_xsave) {
3273                 guest_xcrs->nr_xcrs = 0;
3274                 return;
3275         }
3276
3277         guest_xcrs->nr_xcrs = 1;
3278         guest_xcrs->flags = 0;
3279         guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3280         guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3281 }
3282
3283 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3284                                        struct kvm_xcrs *guest_xcrs)
3285 {
3286         int i, r = 0;
3287
3288         if (!cpu_has_xsave)
3289                 return -EINVAL;
3290
3291         if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3292                 return -EINVAL;
3293
3294         for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3295                 /* Only support XCR0 currently */
3296                 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3297                         r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3298                                 guest_xcrs->xcrs[i].value);
3299                         break;
3300                 }
3301         if (r)
3302                 r = -EINVAL;
3303         return r;
3304 }
3305
3306 /*
3307  * kvm_set_guest_paused() indicates to the guest kernel that it has been
3308  * stopped by the hypervisor.  This function will be called from the host only.
3309  * EINVAL is returned when the host attempts to set the flag for a guest that
3310  * does not support pv clocks.
3311  */
3312 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3313 {
3314         if (!vcpu->arch.pv_time_enabled)
3315                 return -EINVAL;
3316         vcpu->arch.pvclock_set_guest_stopped_request = true;
3317         kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3318         return 0;
3319 }
3320
3321 long kvm_arch_vcpu_ioctl(struct file *filp,
3322                          unsigned int ioctl, unsigned long arg)
3323 {
3324         struct kvm_vcpu *vcpu = filp->private_data;
3325         void __user *argp = (void __user *)arg;
3326         int r;
3327         union {
3328                 struct kvm_lapic_state *lapic;
3329                 struct kvm_xsave *xsave;
3330                 struct kvm_xcrs *xcrs;
3331                 void *buffer;
3332         } u;
3333
3334         u.buffer = NULL;
3335         switch (ioctl) {
3336         case KVM_GET_LAPIC: {
3337                 r = -EINVAL;
3338                 if (!vcpu->arch.apic)
3339                         goto out;
3340                 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3341
3342                 r = -ENOMEM;
3343                 if (!u.lapic)
3344                         goto out;
3345                 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3346                 if (r)
3347                         goto out;
3348                 r = -EFAULT;
3349                 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3350                         goto out;
3351                 r = 0;
3352                 break;
3353         }
3354         case KVM_SET_LAPIC: {
3355                 r = -EINVAL;
3356                 if (!vcpu->arch.apic)
3357                         goto out;
3358                 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3359                 if (IS_ERR(u.lapic))
3360                         return PTR_ERR(u.lapic);
3361
3362                 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3363                 break;
3364         }
3365         case KVM_INTERRUPT: {
3366                 struct kvm_interrupt irq;
3367
3368                 r = -EFAULT;
3369                 if (copy_from_user(&irq, argp, sizeof irq))
3370                         goto out;
3371                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3372                 break;
3373         }
3374         case KVM_NMI: {
3375                 r = kvm_vcpu_ioctl_nmi(vcpu);
3376                 break;
3377         }
3378         case KVM_SMI: {
3379                 r = kvm_vcpu_ioctl_smi(vcpu);
3380                 break;
3381         }
3382         case KVM_SET_CPUID: {
3383                 struct kvm_cpuid __user *cpuid_arg = argp;
3384                 struct kvm_cpuid cpuid;
3385
3386                 r = -EFAULT;
3387                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3388                         goto out;
3389                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3390                 break;
3391         }
3392         case KVM_SET_CPUID2: {
3393                 struct kvm_cpuid2 __user *cpuid_arg = argp;
3394                 struct kvm_cpuid2 cpuid;
3395
3396                 r = -EFAULT;
3397                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3398                         goto out;
3399                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3400                                               cpuid_arg->entries);
3401                 break;
3402         }
3403         case KVM_GET_CPUID2: {
3404                 struct kvm_cpuid2 __user *cpuid_arg = argp;
3405                 struct kvm_cpuid2 cpuid;
3406
3407                 r = -EFAULT;
3408                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3409                         goto out;
3410                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3411                                               cpuid_arg->entries);
3412                 if (r)
3413                         goto out;
3414                 r = -EFAULT;
3415                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3416                         goto out;
3417                 r = 0;
3418                 break;
3419         }
3420         case KVM_GET_MSRS:
3421                 r = msr_io(vcpu, argp, do_get_msr, 1);
3422                 break;
3423         case KVM_SET_MSRS:
3424                 r = msr_io(vcpu, argp, do_set_msr, 0);
3425                 break;
3426         case KVM_TPR_ACCESS_REPORTING: {
3427                 struct kvm_tpr_access_ctl tac;
3428
3429                 r = -EFAULT;
3430                 if (copy_from_user(&tac, argp, sizeof tac))
3431                         goto out;
3432                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3433                 if (r)
3434                         goto out;
3435                 r = -EFAULT;
3436                 if (copy_to_user(argp, &tac, sizeof tac))
3437                         goto out;
3438                 r = 0;
3439                 break;
3440         };
3441         case KVM_SET_VAPIC_ADDR: {
3442                 struct kvm_vapic_addr va;
3443                 int idx;
3444
3445                 r = -EINVAL;
3446                 if (!lapic_in_kernel(vcpu))
3447                         goto out;
3448                 r = -EFAULT;
3449                 if (copy_from_user(&va, argp, sizeof va))
3450                         goto out;
3451                 idx = srcu_read_lock(&vcpu->kvm->srcu);
3452                 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3453                 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3454                 break;
3455         }
3456         case KVM_X86_SETUP_MCE: {
3457                 u64 mcg_cap;
3458
3459                 r = -EFAULT;
3460                 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3461                         goto out;
3462                 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3463                 break;
3464         }
3465         case KVM_X86_SET_MCE: {
3466                 struct kvm_x86_mce mce;
3467
3468                 r = -EFAULT;
3469                 if (copy_from_user(&mce, argp, sizeof mce))
3470                         goto out;
3471                 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3472                 break;
3473         }
3474         case KVM_GET_VCPU_EVENTS: {
3475                 struct kvm_vcpu_events events;
3476
3477                 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3478
3479                 r = -EFAULT;
3480                 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3481                         break;
3482                 r = 0;
3483                 break;
3484         }
3485         case KVM_SET_VCPU_EVENTS: {
3486                 struct kvm_vcpu_events events;
3487
3488                 r = -EFAULT;
3489                 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3490                         break;
3491
3492                 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3493                 break;
3494         }
3495         case KVM_GET_DEBUGREGS: {
3496                 struct kvm_debugregs dbgregs;
3497
3498                 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3499
3500                 r = -EFAULT;
3501                 if (copy_to_user(argp, &dbgregs,
3502                                  sizeof(struct kvm_debugregs)))
3503                         break;
3504                 r = 0;
3505                 break;
3506         }
3507         case KVM_SET_DEBUGREGS: {
3508                 struct kvm_debugregs dbgregs;
3509
3510                 r = -EFAULT;
3511                 if (copy_from_user(&dbgregs, argp,
3512                                    sizeof(struct kvm_debugregs)))
3513                         break;
3514
3515                 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3516                 break;
3517         }
3518         case KVM_GET_XSAVE: {
3519                 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3520                 r = -ENOMEM;
3521                 if (!u.xsave)
3522                         break;
3523
3524                 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3525
3526                 r = -EFAULT;
3527                 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3528                         break;
3529                 r = 0;
3530                 break;
3531         }
3532         case KVM_SET_XSAVE: {
3533                 u.xsave = memdup_user(argp, sizeof(*u.xsave));
3534                 if (IS_ERR(u.xsave))
3535                         return PTR_ERR(u.xsave);
3536
3537                 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3538                 break;
3539         }
3540         case KVM_GET_XCRS: {
3541                 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3542                 r = -ENOMEM;
3543                 if (!u.xcrs)
3544                         break;
3545
3546                 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3547
3548                 r = -EFAULT;
3549                 if (copy_to_user(argp, u.xcrs,
3550                                  sizeof(struct kvm_xcrs)))
3551                         break;
3552                 r = 0;
3553                 break;
3554         }
3555         case KVM_SET_XCRS: {
3556                 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
3557                 if (IS_ERR(u.xcrs))
3558                         return PTR_ERR(u.xcrs);
3559
3560                 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3561                 break;
3562         }
3563         case KVM_SET_TSC_KHZ: {
3564                 u32 user_tsc_khz;
3565
3566                 r = -EINVAL;
3567                 user_tsc_khz = (u32)arg;
3568
3569                 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3570                         goto out;
3571
3572                 if (user_tsc_khz == 0)
3573                         user_tsc_khz = tsc_khz;
3574
3575                 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
3576                         r = 0;
3577
3578                 goto out;
3579         }
3580         case KVM_GET_TSC_KHZ: {
3581                 r = vcpu->arch.virtual_tsc_khz;
3582                 goto out;
3583         }
3584         case KVM_KVMCLOCK_CTRL: {
3585                 r = kvm_set_guest_paused(vcpu);
3586                 goto out;
3587         }
3588         default:
3589                 r = -EINVAL;
3590         }
3591 out:
3592         kfree(u.buffer);
3593         return r;
3594 }
3595
3596 int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
3597 {
3598         return VM_FAULT_SIGBUS;
3599 }
3600
3601 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3602 {
3603         int ret;
3604
3605         if (addr > (unsigned int)(-3 * PAGE_SIZE))
3606                 return -EINVAL;
3607         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
3608         return ret;
3609 }
3610
3611 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3612                                               u64 ident_addr)
3613 {
3614         kvm->arch.ept_identity_map_addr = ident_addr;
3615         return 0;
3616 }
3617
3618 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3619                                           u32 kvm_nr_mmu_pages)
3620 {
3621         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3622                 return -EINVAL;
3623
3624         mutex_lock(&kvm->slots_lock);
3625
3626         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3627         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3628
3629         mutex_unlock(&kvm->slots_lock);
3630         return 0;
3631 }
3632
3633 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
3634 {
3635         return kvm->arch.n_max_mmu_pages;
3636 }
3637
3638 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3639 {
3640         int r;
3641
3642         r = 0;
3643         switch (chip->chip_id) {
3644         case KVM_IRQCHIP_PIC_MASTER:
3645                 memcpy(&chip->chip.pic,
3646                         &pic_irqchip(kvm)->pics[0],
3647                         sizeof(struct kvm_pic_state));
3648                 break;
3649         case KVM_IRQCHIP_PIC_SLAVE:
3650                 memcpy(&chip->chip.pic,
3651                         &pic_irqchip(kvm)->pics[1],
3652                         sizeof(struct kvm_pic_state));
3653                 break;
3654         case KVM_IRQCHIP_IOAPIC:
3655                 r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
3656                 break;
3657         default:
3658                 r = -EINVAL;
3659                 break;
3660         }
3661         return r;
3662 }
3663
3664 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3665 {
3666         int r;
3667
3668         r = 0;
3669         switch (chip->chip_id) {
3670         case KVM_IRQCHIP_PIC_MASTER:
3671                 spin_lock(&pic_irqchip(kvm)->lock);
3672                 memcpy(&pic_irqchip(kvm)->pics[0],
3673                         &chip->chip.pic,
3674                         sizeof(struct kvm_pic_state));
3675                 spin_unlock(&pic_irqchip(kvm)->lock);
3676                 break;
3677         case KVM_IRQCHIP_PIC_SLAVE:
3678                 spin_lock(&pic_irqchip(kvm)->lock);
3679                 memcpy(&pic_irqchip(kvm)->pics[1],
3680                         &chip->chip.pic,
3681                         sizeof(struct kvm_pic_state));
3682                 spin_unlock(&pic_irqchip(kvm)->lock);
3683                 break;
3684         case KVM_IRQCHIP_IOAPIC:
3685                 r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
3686                 break;
3687         default:
3688                 r = -EINVAL;
3689                 break;
3690         }
3691         kvm_pic_update_irq(pic_irqchip(kvm));
3692         return r;
3693 }
3694
3695 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3696 {
3697         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3698         memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
3699         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3700         return 0;
3701 }
3702
3703 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3704 {
3705         int i;
3706         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3707         memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
3708         for (i = 0; i < 3; i++)
3709                 kvm_pit_load_count(kvm, i, ps->channels[i].count, 0);
3710         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3711         return 0;
3712 }
3713
3714 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3715 {
3716         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3717         memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
3718                 sizeof(ps->channels));
3719         ps->flags = kvm->arch.vpit->pit_state.flags;
3720         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3721         memset(&ps->reserved, 0, sizeof(ps->reserved));
3722         return 0;
3723 }
3724
3725 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3726 {
3727         int start = 0;
3728         int i;
3729         u32 prev_legacy, cur_legacy;
3730         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3731         prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
3732         cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
3733         if (!prev_legacy && cur_legacy)
3734                 start = 1;
3735         memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
3736                sizeof(kvm->arch.vpit->pit_state.channels));
3737         kvm->arch.vpit->pit_state.flags = ps->flags;
3738         for (i = 0; i < 3; i++)
3739                 kvm_pit_load_count(kvm, i, kvm->arch.vpit->pit_state.channels[i].count,
3740                                    start && i == 0);
3741         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3742         return 0;
3743 }
3744
3745 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
3746                                  struct kvm_reinject_control *control)
3747 {
3748         if (!kvm->arch.vpit)
3749                 return -ENXIO;
3750         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3751         kvm->arch.vpit->pit_state.reinject = control->pit_reinject;
3752         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3753         return 0;
3754 }
3755
3756 /**
3757  * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
3758  * @kvm: kvm instance
3759  * @log: slot id and address to which we copy the log
3760  *
3761  * Steps 1-4 below provide general overview of dirty page logging. See
3762  * kvm_get_dirty_log_protect() function description for additional details.
3763  *
3764  * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
3765  * always flush the TLB (step 4) even if previous step failed  and the dirty
3766  * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
3767  * does not preclude user space subsequent dirty log read. Flushing TLB ensures
3768  * writes will be marked dirty for next log read.
3769  *
3770  *   1. Take a snapshot of the bit and clear it if needed.
3771  *   2. Write protect the corresponding page.
3772  *   3. Copy the snapshot to the userspace.
3773  *   4. Flush TLB's if needed.
3774  */
3775 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
3776 {
3777         bool is_dirty = false;
3778         int r;
3779
3780         mutex_lock(&kvm->slots_lock);
3781
3782         /*
3783          * Flush potentially hardware-cached dirty pages to dirty_bitmap.
3784          */
3785         if (kvm_x86_ops->flush_log_dirty)
3786                 kvm_x86_ops->flush_log_dirty(kvm);
3787
3788         r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
3789
3790         /*
3791          * All the TLBs can be flushed out of mmu lock, see the comments in
3792          * kvm_mmu_slot_remove_write_access().
3793          */
3794         lockdep_assert_held(&kvm->slots_lock);
3795         if (is_dirty)
3796                 kvm_flush_remote_tlbs(kvm);
3797
3798         mutex_unlock(&kvm->slots_lock);
3799         return r;
3800 }
3801
3802 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
3803                         bool line_status)
3804 {
3805         if (!irqchip_in_kernel(kvm))
3806                 return -ENXIO;
3807
3808         irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3809                                         irq_event->irq, irq_event->level,
3810                                         line_status);
3811         return 0;
3812 }
3813
3814 static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3815                                    struct kvm_enable_cap *cap)
3816 {
3817         int r;
3818
3819         if (cap->flags)
3820                 return -EINVAL;
3821
3822         switch (cap->cap) {
3823         case KVM_CAP_DISABLE_QUIRKS:
3824                 kvm->arch.disabled_quirks = cap->args[0];
3825                 r = 0;
3826                 break;
3827         case KVM_CAP_SPLIT_IRQCHIP: {
3828                 mutex_lock(&kvm->lock);
3829                 r = -EINVAL;
3830                 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
3831                         goto split_irqchip_unlock;
3832                 r = -EEXIST;
3833                 if (irqchip_in_kernel(kvm))
3834                         goto split_irqchip_unlock;
3835                 if (atomic_read(&kvm->online_vcpus))
3836                         goto split_irqchip_unlock;
3837                 r = kvm_setup_empty_irq_routing(kvm);
3838                 if (r)
3839                         goto split_irqchip_unlock;
3840                 /* Pairs with irqchip_in_kernel. */
3841                 smp_wmb();
3842                 kvm->arch.irqchip_split = true;
3843                 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
3844                 r = 0;
3845 split_irqchip_unlock:
3846                 mutex_unlock(&kvm->lock);
3847                 break;
3848         }
3849         default:
3850                 r = -EINVAL;
3851                 break;
3852         }
3853         return r;
3854 }
3855
3856 long kvm_arch_vm_ioctl(struct file *filp,
3857                        unsigned int ioctl, unsigned long arg)
3858 {
3859         struct kvm *kvm = filp->private_data;
3860         void __user *argp = (void __user *)arg;
3861         int r = -ENOTTY;
3862         /*
3863          * This union makes it completely explicit to gcc-3.x
3864          * that these two variables' stack usage should be
3865          * combined, not added together.
3866          */
3867         union {
3868                 struct kvm_pit_state ps;
3869                 struct kvm_pit_state2 ps2;
3870                 struct kvm_pit_config pit_config;
3871         } u;
3872
3873         switch (ioctl) {
3874         case KVM_SET_TSS_ADDR:
3875                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
3876                 break;
3877         case KVM_SET_IDENTITY_MAP_ADDR: {
3878                 u64 ident_addr;
3879
3880                 r = -EFAULT;
3881                 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
3882                         goto out;
3883                 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
3884                 break;
3885         }
3886         case KVM_SET_NR_MMU_PAGES:
3887                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
3888                 break;
3889         case KVM_GET_NR_MMU_PAGES:
3890                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
3891                 break;
3892         case KVM_CREATE_IRQCHIP: {
3893                 struct kvm_pic *vpic;
3894
3895                 mutex_lock(&kvm->lock);
3896                 r = -EEXIST;
3897                 if (kvm->arch.vpic)
3898                         goto create_irqchip_unlock;
3899                 r = -EINVAL;
3900                 if (atomic_read(&kvm->online_vcpus))
3901                         goto create_irqchip_unlock;
3902                 r = -ENOMEM;
3903                 vpic = kvm_create_pic(kvm);
3904                 if (vpic) {
3905                         r = kvm_ioapic_init(kvm);
3906                         if (r) {
3907                                 mutex_lock(&kvm->slots_lock);
3908                                 kvm_destroy_pic(vpic);
3909                                 mutex_unlock(&kvm->slots_lock);
3910                                 goto create_irqchip_unlock;
3911                         }
3912                 } else
3913                         goto create_irqchip_unlock;
3914                 r = kvm_setup_default_irq_routing(kvm);
3915                 if (r) {
3916                         mutex_lock(&kvm->slots_lock);
3917                         mutex_lock(&kvm->irq_lock);
3918                         kvm_ioapic_destroy(kvm);
3919                         kvm_destroy_pic(vpic);
3920                         mutex_unlock(&kvm->irq_lock);
3921                         mutex_unlock(&kvm->slots_lock);
3922                         goto create_irqchip_unlock;
3923                 }
3924                 /* Write kvm->irq_routing before kvm->arch.vpic.  */
3925                 smp_wmb();
3926                 kvm->arch.vpic = vpic;
3927         create_irqchip_unlock:
3928                 mutex_unlock(&kvm->lock);
3929                 break;
3930         }
3931         case KVM_CREATE_PIT:
3932                 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
3933                 goto create_pit;
3934         case KVM_CREATE_PIT2:
3935                 r = -EFAULT;
3936                 if (copy_from_user(&u.pit_config, argp,
3937                                    sizeof(struct kvm_pit_config)))
3938                         goto out;
3939         create_pit:
3940                 mutex_lock(&kvm->lock);
3941                 r = -EEXIST;
3942                 if (kvm->arch.vpit)
3943                         goto create_pit_unlock;
3944                 r = -ENOMEM;
3945                 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
3946                 if (kvm->arch.vpit)
3947                         r = 0;
3948         create_pit_unlock:
3949                 mutex_unlock(&kvm->lock);
3950                 break;
3951         case KVM_GET_IRQCHIP: {
3952                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3953                 struct kvm_irqchip *chip;
3954
3955                 chip = memdup_user(argp, sizeof(*chip));
3956                 if (IS_ERR(chip)) {
3957                         r = PTR_ERR(chip);
3958                         goto out;
3959                 }
3960
3961                 r = -ENXIO;
3962                 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
3963                         goto get_irqchip_out;
3964                 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
3965                 if (r)
3966                         goto get_irqchip_out;
3967                 r = -EFAULT;
3968                 if (copy_to_user(argp, chip, sizeof *chip))
3969                         goto get_irqchip_out;
3970                 r = 0;
3971         get_irqchip_out:
3972                 kfree(chip);
3973                 break;
3974         }
3975         case KVM_SET_IRQCHIP: {
3976                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
3977                 struct kvm_irqchip *chip;
3978
3979                 chip = memdup_user(argp, sizeof(*chip));
3980                 if (IS_ERR(chip)) {
3981                         r = PTR_ERR(chip);
3982                         goto out;
3983                 }
3984
3985                 r = -ENXIO;
3986                 if (!irqchip_in_kernel(kvm) || irqchip_split(kvm))
3987                         goto set_irqchip_out;
3988                 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
3989                 if (r)
3990                         goto set_irqchip_out;
3991                 r = 0;
3992         set_irqchip_out:
3993                 kfree(chip);
3994                 break;
3995         }
3996         case KVM_GET_PIT: {
3997                 r = -EFAULT;
3998                 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
3999                         goto out;
4000                 r = -ENXIO;
4001                 if (!kvm->arch.vpit)
4002                         goto out;
4003                 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
4004                 if (r)
4005                         goto out;
4006                 r = -EFAULT;
4007                 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
4008                         goto out;
4009                 r = 0;
4010                 break;
4011         }
4012         case KVM_SET_PIT: {
4013                 r = -EFAULT;
4014                 if (copy_from_user(&u.ps, argp, sizeof u.ps))
4015                         goto out;
4016                 r = -ENXIO;
4017                 if (!kvm->arch.vpit)
4018                         goto out;
4019                 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
4020                 break;
4021         }
4022         case KVM_GET_PIT2: {
4023                 r = -ENXIO;
4024                 if (!kvm->arch.vpit)
4025                         goto out;
4026                 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
4027                 if (r)
4028                         goto out;
4029                 r = -EFAULT;
4030                 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
4031                         goto out;
4032                 r = 0;
4033                 break;
4034         }
4035         case KVM_SET_PIT2: {
4036                 r = -EFAULT;
4037                 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
4038                         goto out;
4039                 r = -ENXIO;
4040                 if (!kvm->arch.vpit)
4041                         goto out;
4042                 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
4043                 break;
4044         }
4045         case KVM_REINJECT_CONTROL: {
4046                 struct kvm_reinject_control control;
4047                 r =  -EFAULT;
4048                 if (copy_from_user(&control, argp, sizeof(control)))
4049                         goto out;
4050                 r = kvm_vm_ioctl_reinject(kvm, &control);
4051                 break;
4052         }
4053         case KVM_SET_BOOT_CPU_ID:
4054                 r = 0;
4055                 mutex_lock(&kvm->lock);
4056                 if (atomic_read(&kvm->online_vcpus) != 0)
4057                         r = -EBUSY;
4058                 else
4059                         kvm->arch.bsp_vcpu_id = arg;
4060                 mutex_unlock(&kvm->lock);
4061                 break;
4062         case KVM_XEN_HVM_CONFIG: {
4063                 struct kvm_xen_hvm_config xhc;
4064                 r = -EFAULT;
4065                 if (copy_from_user(&xhc, argp, sizeof(xhc)))
4066                         goto out;
4067                 r = -EINVAL;
4068                 if (xhc.flags)
4069                         goto out;
4070                 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
4071                 r = 0;
4072                 break;
4073         }
4074         case KVM_SET_CLOCK: {
4075                 struct kvm_clock_data user_ns;
4076                 u64 now_ns;
4077                 s64 delta;
4078
4079                 r = -EFAULT;
4080                 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
4081                         goto out;
4082
4083                 r = -EINVAL;
4084                 if (user_ns.flags)
4085                         goto out;
4086
4087                 r = 0;
4088                 local_irq_disable();
4089                 now_ns = get_kernel_ns();
4090                 delta = user_ns.clock - now_ns;
4091                 local_irq_enable();
4092                 kvm->arch.kvmclock_offset = delta;
4093                 kvm_gen_update_masterclock(kvm);
4094                 break;
4095         }
4096         case KVM_GET_CLOCK: {
4097                 struct kvm_clock_data user_ns;
4098                 u64 now_ns;
4099
4100                 local_irq_disable();
4101                 now_ns = get_kernel_ns();
4102                 user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
4103                 local_irq_enable();
4104                 user_ns.flags = 0;
4105                 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
4106
4107                 r = -EFAULT;
4108                 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
4109                         goto out;
4110                 r = 0;
4111                 break;
4112         }
4113         case KVM_ENABLE_CAP: {
4114                 struct kvm_enable_cap cap;
4115
4116                 r = -EFAULT;
4117                 if (copy_from_user(&cap, argp, sizeof(cap)))
4118                         goto out;
4119                 r = kvm_vm_ioctl_enable_cap(kvm, &cap);
4120                 break;
4121         }
4122         default:
4123                 r = kvm_vm_ioctl_assigned_device(kvm, ioctl, arg);
4124         }
4125 out:
4126         return r;
4127 }
4128
4129 static void kvm_init_msr_list(void)
4130 {
4131         u32 dummy[2];
4132         unsigned i, j;
4133
4134         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
4135                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
4136                         continue;
4137
4138                 /*
4139                  * Even MSRs that are valid in the host may not be exposed
4140                  * to the guests in some cases.
4141                  */
4142                 switch (msrs_to_save[i]) {
4143                 case MSR_IA32_BNDCFGS:
4144                         if (!kvm_x86_ops->mpx_supported())
4145                                 continue;
4146                         break;
4147                 case MSR_TSC_AUX:
4148                         if (!kvm_x86_ops->rdtscp_supported())
4149                                 continue;
4150                         break;
4151                 default:
4152                         break;
4153                 }
4154
4155                 if (j < i)
4156                         msrs_to_save[j] = msrs_to_save[i];
4157                 j++;
4158         }
4159         num_msrs_to_save = j;
4160
4161         for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
4162                 if (!kvm_x86_ops->has_emulated_msr(emulated_msrs[i]))
4163                         continue;
4164
4165                 if (j < i)
4166                         emulated_msrs[j] = emulated_msrs[i];
4167                 j++;
4168         }
4169         num_emulated_msrs = j;
4170 }
4171
4172 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
4173                            const void *v)
4174 {
4175         int handled = 0;
4176         int n;
4177
4178         do {
4179                 n = min(len, 8);
4180                 if (!(vcpu->arch.apic &&
4181                       !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
4182                     && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
4183                         break;
4184                 handled += n;
4185                 addr += n;
4186                 len -= n;
4187                 v += n;
4188         } while (len);
4189
4190         return handled;
4191 }
4192
4193 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
4194 {
4195         int handled = 0;
4196         int n;
4197
4198         do {
4199                 n = min(len, 8);
4200                 if (!(vcpu->arch.apic &&
4201                       !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
4202                                          addr, n, v))
4203                     && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
4204                         break;
4205                 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
4206                 handled += n;
4207                 addr += n;
4208                 len -= n;
4209                 v += n;
4210         } while (len);
4211
4212         return handled;
4213 }
4214
4215 static void kvm_set_segment(struct kvm_vcpu *vcpu,
4216                         struct kvm_segment *var, int seg)
4217 {
4218         kvm_x86_ops->set_segment(vcpu, var, seg);
4219 }
4220
4221 void kvm_get_segment(struct kvm_vcpu *vcpu,
4222                      struct kvm_segment *var, int seg)
4223 {
4224         kvm_x86_ops->get_segment(vcpu, var, seg);
4225 }
4226
4227 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
4228                            struct x86_exception *exception)
4229 {
4230         gpa_t t_gpa;
4231
4232         BUG_ON(!mmu_is_nested(vcpu));
4233
4234         /* NPT walks are always user-walks */
4235         access |= PFERR_USER_MASK;
4236         t_gpa  = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception);
4237
4238         return t_gpa;
4239 }
4240
4241 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
4242                               struct x86_exception *exception)
4243 {
4244         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4245         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4246 }
4247
4248  gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
4249                                 struct x86_exception *exception)
4250 {
4251         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4252         access |= PFERR_FETCH_MASK;
4253         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4254 }
4255
4256 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
4257                                struct x86_exception *exception)
4258 {
4259         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4260         access |= PFERR_WRITE_MASK;
4261         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4262 }
4263
4264 /* uses this to access any guest's mapped memory without checking CPL */
4265 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
4266                                 struct x86_exception *exception)
4267 {
4268         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
4269 }
4270
4271 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4272                                       struct kvm_vcpu *vcpu, u32 access,
4273                                       struct x86_exception *exception)
4274 {
4275         void *data = val;
4276         int r = X86EMUL_CONTINUE;
4277
4278         while (bytes) {
4279                 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
4280                                                             exception);
4281                 unsigned offset = addr & (PAGE_SIZE-1);
4282                 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
4283                 int ret;
4284
4285                 if (gpa == UNMAPPED_GVA)
4286                         return X86EMUL_PROPAGATE_FAULT;
4287                 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
4288                                                offset, toread);
4289                 if (ret < 0) {
4290                         r = X86EMUL_IO_NEEDED;
4291                         goto out;
4292                 }
4293
4294                 bytes -= toread;
4295                 data += toread;
4296                 addr += toread;
4297         }
4298 out:
4299         return r;
4300 }
4301
4302 /* used for instruction fetching */
4303 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
4304                                 gva_t addr, void *val, unsigned int bytes,
4305                                 struct x86_exception *exception)
4306 {
4307         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4308         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4309         unsigned offset;
4310         int ret;
4311
4312         /* Inline kvm_read_guest_virt_helper for speed.  */
4313         gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
4314                                                     exception);
4315         if (unlikely(gpa == UNMAPPED_GVA))
4316                 return X86EMUL_PROPAGATE_FAULT;
4317
4318         offset = addr & (PAGE_SIZE-1);
4319         if (WARN_ON(offset + bytes > PAGE_SIZE))
4320                 bytes = (unsigned)PAGE_SIZE - offset;
4321         ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
4322                                        offset, bytes);
4323         if (unlikely(ret < 0))
4324                 return X86EMUL_IO_NEEDED;
4325
4326         return X86EMUL_CONTINUE;
4327 }
4328
4329 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
4330                                gva_t addr, void *val, unsigned int bytes,
4331                                struct x86_exception *exception)
4332 {
4333         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4334
4335         /*
4336          * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
4337          * is returned, but our callers are not ready for that and they blindly
4338          * call kvm_inject_page_fault.  Ensure that they at least do not leak
4339          * uninitialized kernel stack memory into cr2 and error code.
4340          */
4341         memset(exception, 0, sizeof(*exception));
4342         return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4343                                           exception);
4344 }
4345 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4346
4347 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
4348                              gva_t addr, void *val, unsigned int bytes,
4349                              struct x86_exception *exception, bool system)
4350 {
4351         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4352         u32 access = 0;
4353
4354         if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
4355                 access |= PFERR_USER_MASK;
4356
4357         return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
4358 }
4359
4360 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
4361                 unsigned long addr, void *val, unsigned int bytes)
4362 {
4363         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4364         int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
4365
4366         return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
4367 }
4368
4369 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4370                                       struct kvm_vcpu *vcpu, u32 access,
4371                                       struct x86_exception *exception)
4372 {
4373         void *data = val;
4374         int r = X86EMUL_CONTINUE;
4375
4376         while (bytes) {
4377                 gpa_t gpa =  vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4378                                                              access,
4379                                                              exception);
4380                 unsigned offset = addr & (PAGE_SIZE-1);
4381                 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4382                 int ret;
4383
4384                 if (gpa == UNMAPPED_GVA)
4385                         return X86EMUL_PROPAGATE_FAULT;
4386                 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
4387                 if (ret < 0) {
4388                         r = X86EMUL_IO_NEEDED;
4389                         goto out;
4390                 }
4391
4392                 bytes -= towrite;
4393                 data += towrite;
4394                 addr += towrite;
4395         }
4396 out:
4397         return r;
4398 }
4399
4400 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
4401                               unsigned int bytes, struct x86_exception *exception,
4402                               bool system)
4403 {
4404         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4405         u32 access = PFERR_WRITE_MASK;
4406
4407         if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
4408                 access |= PFERR_USER_MASK;
4409
4410         /*
4411          * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
4412          * is returned, but our callers are not ready for that and they blindly
4413          * call kvm_inject_page_fault.  Ensure that they at least do not leak
4414          * uninitialized kernel stack memory into cr2 and error code.
4415          */
4416         memset(exception, 0, sizeof(*exception));
4417         return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
4418                                            access, exception);
4419 }
4420
4421 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
4422                                 unsigned int bytes, struct x86_exception *exception)
4423 {
4424         return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
4425                                            PFERR_WRITE_MASK, exception);
4426 }
4427 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4428
4429 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4430                                 gpa_t *gpa, struct x86_exception *exception,
4431                                 bool write)
4432 {
4433         u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
4434                 | (write ? PFERR_WRITE_MASK : 0);
4435
4436         if (vcpu_match_mmio_gva(vcpu, gva)
4437             && !permission_fault(vcpu, vcpu->arch.walk_mmu,
4438                                  vcpu->arch.access, access)) {
4439                 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
4440                                         (gva & (PAGE_SIZE - 1));
4441                 trace_vcpu_match_mmio(gva, *gpa, write, false);
4442                 return 1;
4443         }
4444
4445         *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4446
4447         if (*gpa == UNMAPPED_GVA)
4448                 return -1;
4449
4450         /* For APIC access vmexit */
4451         if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4452                 return 1;
4453
4454         if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
4455                 trace_vcpu_match_mmio(gva, *gpa, write, true);
4456                 return 1;
4457         }
4458
4459         return 0;
4460 }
4461
4462 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
4463                         const void *val, int bytes)
4464 {
4465         int ret;
4466
4467         ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
4468         if (ret < 0)
4469                 return 0;
4470         kvm_mmu_pte_write(vcpu, gpa, val, bytes);
4471         return 1;
4472 }
4473
4474 struct read_write_emulator_ops {
4475         int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
4476                                   int bytes);
4477         int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
4478                                   void *val, int bytes);
4479         int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4480                                int bytes, void *val);
4481         int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4482                                     void *val, int bytes);
4483         bool write;
4484 };
4485
4486 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
4487 {
4488         if (vcpu->mmio_read_completed) {
4489                 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
4490                                vcpu->mmio_fragments[0].gpa, val);
4491                 vcpu->mmio_read_completed = 0;
4492                 return 1;
4493         }
4494
4495         return 0;
4496 }
4497
4498 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4499                         void *val, int bytes)
4500 {
4501         return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
4502 }
4503
4504 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4505                          void *val, int bytes)
4506 {
4507         return emulator_write_phys(vcpu, gpa, val, bytes);
4508 }
4509
4510 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
4511 {
4512         trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
4513         return vcpu_mmio_write(vcpu, gpa, bytes, val);
4514 }
4515
4516 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4517                           void *val, int bytes)
4518 {
4519         trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
4520         return X86EMUL_IO_NEEDED;
4521 }
4522
4523 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4524                            void *val, int bytes)
4525 {
4526         struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
4527
4528         memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
4529         return X86EMUL_CONTINUE;
4530 }
4531
4532 static const struct read_write_emulator_ops read_emultor = {
4533         .read_write_prepare = read_prepare,
4534         .read_write_emulate = read_emulate,
4535         .read_write_mmio = vcpu_mmio_read,
4536         .read_write_exit_mmio = read_exit_mmio,
4537 };
4538
4539 static const struct read_write_emulator_ops write_emultor = {
4540         .read_write_emulate = write_emulate,
4541         .read_write_mmio = write_mmio,
4542         .read_write_exit_mmio = write_exit_mmio,
4543         .write = true,
4544 };
4545
4546 static int emulator_read_write_onepage(unsigned long addr, void *val,
4547                                        unsigned int bytes,
4548                                        struct x86_exception *exception,
4549                                        struct kvm_vcpu *vcpu,
4550                                        const struct read_write_emulator_ops *ops)
4551 {
4552         gpa_t gpa;
4553         int handled, ret;
4554         bool write = ops->write;
4555         struct kvm_mmio_fragment *frag;
4556
4557         ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
4558
4559         if (ret < 0)
4560                 return X86EMUL_PROPAGATE_FAULT;
4561
4562         /* For APIC access vmexit */
4563         if (ret)
4564                 goto mmio;
4565
4566         if (ops->read_write_emulate(vcpu, gpa, val, bytes))
4567                 return X86EMUL_CONTINUE;
4568
4569 mmio:
4570         /*
4571          * Is this MMIO handled locally?
4572          */
4573         handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
4574         if (handled == bytes)
4575                 return X86EMUL_CONTINUE;
4576
4577         gpa += handled;
4578         bytes -= handled;
4579         val += handled;
4580
4581         WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
4582         frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
4583         frag->gpa = gpa;
4584         frag->data = val;
4585         frag->len = bytes;
4586         return X86EMUL_CONTINUE;
4587 }
4588
4589 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
4590                         unsigned long addr,
4591                         void *val, unsigned int bytes,
4592                         struct x86_exception *exception,
4593                         const struct read_write_emulator_ops *ops)
4594 {
4595         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4596         gpa_t gpa;
4597         int rc;
4598
4599         if (ops->read_write_prepare &&
4600                   ops->read_write_prepare(vcpu, val, bytes))
4601                 return X86EMUL_CONTINUE;
4602
4603         vcpu->mmio_nr_fragments = 0;
4604
4605         /* Crossing a page boundary? */
4606         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
4607                 int now;
4608
4609                 now = -addr & ~PAGE_MASK;
4610                 rc = emulator_read_write_onepage(addr, val, now, exception,
4611                                                  vcpu, ops);
4612
4613                 if (rc != X86EMUL_CONTINUE)
4614                         return rc;
4615                 addr += now;
4616                 if (ctxt->mode != X86EMUL_MODE_PROT64)
4617                         addr = (u32)addr;
4618                 val += now;
4619                 bytes -= now;
4620         }
4621
4622         rc = emulator_read_write_onepage(addr, val, bytes, exception,
4623                                          vcpu, ops);
4624         if (rc != X86EMUL_CONTINUE)
4625                 return rc;
4626
4627         if (!vcpu->mmio_nr_fragments)
4628                 return rc;
4629
4630         gpa = vcpu->mmio_fragments[0].gpa;
4631
4632         vcpu->mmio_needed = 1;
4633         vcpu->mmio_cur_fragment = 0;
4634
4635         vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
4636         vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
4637         vcpu->run->exit_reason = KVM_EXIT_MMIO;
4638         vcpu->run->mmio.phys_addr = gpa;
4639
4640         return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
4641 }
4642
4643 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
4644                                   unsigned long addr,
4645                                   void *val,
4646                                   unsigned int bytes,
4647                                   struct x86_exception *exception)
4648 {
4649         return emulator_read_write(ctxt, addr, val, bytes,
4650                                    exception, &read_emultor);
4651 }
4652
4653 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
4654                             unsigned long addr,
4655                             const void *val,
4656                             unsigned int bytes,
4657                             struct x86_exception *exception)
4658 {
4659         return emulator_read_write(ctxt, addr, (void *)val, bytes,
4660                                    exception, &write_emultor);
4661 }
4662
4663 #define CMPXCHG_TYPE(t, ptr, old, new) \
4664         (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
4665
4666 #ifdef CONFIG_X86_64
4667 #  define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
4668 #else
4669 #  define CMPXCHG64(ptr, old, new) \
4670         (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
4671 #endif
4672
4673 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
4674                                      unsigned long addr,
4675                                      const void *old,
4676                                      const void *new,
4677                                      unsigned int bytes,
4678                                      struct x86_exception *exception)
4679 {
4680         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4681         gpa_t gpa;
4682         struct page *page;
4683         char *kaddr;
4684         bool exchanged;
4685
4686         /* guests cmpxchg8b have to be emulated atomically */
4687         if (bytes > 8 || (bytes & (bytes - 1)))
4688                 goto emul_write;
4689
4690         gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
4691
4692         if (gpa == UNMAPPED_GVA ||
4693             (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4694                 goto emul_write;
4695
4696         if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
4697                 goto emul_write;
4698
4699         page = kvm_vcpu_gfn_to_page(vcpu, gpa >> PAGE_SHIFT);
4700         if (is_error_page(page))
4701                 goto emul_write;
4702
4703         kaddr = kmap_atomic(page);
4704         kaddr += offset_in_page(gpa);
4705         switch (bytes) {
4706         case 1:
4707                 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
4708                 break;
4709         case 2:
4710                 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
4711                 break;
4712         case 4:
4713                 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
4714                 break;
4715         case 8:
4716                 exchanged = CMPXCHG64(kaddr, old, new);
4717                 break;
4718         default:
4719                 BUG();
4720         }
4721         kunmap_atomic(kaddr);
4722         kvm_release_page_dirty(page);
4723
4724         if (!exchanged)
4725                 return X86EMUL_CMPXCHG_FAILED;
4726
4727         kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
4728         kvm_mmu_pte_write(vcpu, gpa, new, bytes);
4729
4730         return X86EMUL_CONTINUE;
4731
4732 emul_write:
4733         printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
4734
4735         return emulator_write_emulated(ctxt, addr, new, bytes, exception);
4736 }
4737
4738 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
4739 {
4740         int r = 0, i;
4741
4742         for (i = 0; i < vcpu->arch.pio.count; i++) {
4743                 if (vcpu->arch.pio.in)
4744                         r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
4745                                             vcpu->arch.pio.size, pd);
4746                 else
4747                         r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
4748                                              vcpu->arch.pio.port, vcpu->arch.pio.size,
4749                                              pd);
4750                 if (r)
4751                         break;
4752                 pd += vcpu->arch.pio.size;
4753         }
4754         return r;
4755 }
4756
4757 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
4758                                unsigned short port, void *val,
4759                                unsigned int count, bool in)
4760 {
4761         vcpu->arch.pio.port = port;
4762         vcpu->arch.pio.in = in;
4763         vcpu->arch.pio.count  = count;
4764         vcpu->arch.pio.size = size;
4765
4766         if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
4767                 vcpu->arch.pio.count = 0;
4768                 return 1;
4769         }
4770
4771         vcpu->run->exit_reason = KVM_EXIT_IO;
4772         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
4773         vcpu->run->io.size = size;
4774         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
4775         vcpu->run->io.count = count;
4776         vcpu->run->io.port = port;
4777
4778         return 0;
4779 }
4780
4781 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
4782                                     int size, unsigned short port, void *val,
4783                                     unsigned int count)
4784 {
4785         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4786         int ret;
4787
4788         if (vcpu->arch.pio.count)
4789                 goto data_avail;
4790
4791         memset(vcpu->arch.pio_data, 0, size * count);
4792
4793         ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
4794         if (ret) {
4795 data_avail:
4796                 memcpy(val, vcpu->arch.pio_data, size * count);
4797                 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
4798                 vcpu->arch.pio.count = 0;
4799                 return 1;
4800         }
4801
4802         return 0;
4803 }
4804
4805 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
4806                                      int size, unsigned short port,
4807                                      const void *val, unsigned int count)
4808 {
4809         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4810
4811         memcpy(vcpu->arch.pio_data, val, size * count);
4812         trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
4813         return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
4814 }
4815
4816 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
4817 {
4818         return kvm_x86_ops->get_segment_base(vcpu, seg);
4819 }
4820
4821 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
4822 {
4823         kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
4824 }
4825
4826 int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
4827 {
4828         if (!need_emulate_wbinvd(vcpu))
4829                 return X86EMUL_CONTINUE;
4830
4831         if (kvm_x86_ops->has_wbinvd_exit()) {
4832                 int cpu = get_cpu();
4833
4834                 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
4835                 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
4836                                 wbinvd_ipi, NULL, 1);
4837                 put_cpu();
4838                 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
4839         } else
4840                 wbinvd();
4841         return X86EMUL_CONTINUE;
4842 }
4843
4844 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
4845 {
4846         kvm_x86_ops->skip_emulated_instruction(vcpu);
4847         return kvm_emulate_wbinvd_noskip(vcpu);
4848 }
4849 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
4850
4851
4852
4853 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
4854 {
4855         kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
4856 }
4857
4858 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
4859                            unsigned long *dest)
4860 {
4861         return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
4862 }
4863
4864 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
4865                            unsigned long value)
4866 {
4867
4868         return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
4869 }
4870
4871 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
4872 {
4873         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
4874 }
4875
4876 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
4877 {
4878         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4879         unsigned long value;
4880
4881         switch (cr) {
4882         case 0:
4883                 value = kvm_read_cr0(vcpu);
4884                 break;
4885         case 2:
4886                 value = vcpu->arch.cr2;
4887                 break;
4888         case 3:
4889                 value = kvm_read_cr3(vcpu);
4890                 break;
4891         case 4:
4892                 value = kvm_read_cr4(vcpu);
4893                 break;
4894         case 8:
4895                 value = kvm_get_cr8(vcpu);
4896                 break;
4897         default:
4898                 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4899                 return 0;
4900         }
4901
4902         return value;
4903 }
4904
4905 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
4906 {
4907         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4908         int res = 0;
4909
4910         switch (cr) {
4911         case 0:
4912                 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
4913                 break;
4914         case 2:
4915                 vcpu->arch.cr2 = val;
4916                 break;
4917         case 3:
4918                 res = kvm_set_cr3(vcpu, val);
4919                 break;
4920         case 4:
4921                 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
4922                 break;
4923         case 8:
4924                 res = kvm_set_cr8(vcpu, val);
4925                 break;
4926         default:
4927                 kvm_err("%s: unexpected cr %u\n", __func__, cr);
4928                 res = -1;
4929         }
4930
4931         return res;
4932 }
4933
4934 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
4935 {
4936         return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
4937 }
4938
4939 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4940 {
4941         kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
4942 }
4943
4944 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4945 {
4946         kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
4947 }
4948
4949 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4950 {
4951         kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
4952 }
4953
4954 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
4955 {
4956         kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
4957 }
4958
4959 static unsigned long emulator_get_cached_segment_base(
4960         struct x86_emulate_ctxt *ctxt, int seg)
4961 {
4962         return get_segment_base(emul_to_vcpu(ctxt), seg);
4963 }
4964
4965 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
4966                                  struct desc_struct *desc, u32 *base3,
4967                                  int seg)
4968 {
4969         struct kvm_segment var;
4970
4971         kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
4972         *selector = var.selector;
4973
4974         if (var.unusable) {
4975                 memset(desc, 0, sizeof(*desc));
4976                 if (base3)
4977                         *base3 = 0;
4978                 return false;
4979         }
4980
4981         if (var.g)
4982                 var.limit >>= 12;
4983         set_desc_limit(desc, var.limit);
4984         set_desc_base(desc, (unsigned long)var.base);
4985 #ifdef CONFIG_X86_64
4986         if (base3)
4987                 *base3 = var.base >> 32;
4988 #endif
4989         desc->type = var.type;
4990         desc->s = var.s;
4991         desc->dpl = var.dpl;
4992         desc->p = var.present;
4993         desc->avl = var.avl;
4994         desc->l = var.l;
4995         desc->d = var.db;
4996         desc->g = var.g;
4997
4998         return true;
4999 }
5000
5001 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
5002                                  struct desc_struct *desc, u32 base3,
5003                                  int seg)
5004 {
5005         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5006         struct kvm_segment var;
5007
5008         var.selector = selector;
5009         var.base = get_desc_base(desc);
5010 #ifdef CONFIG_X86_64
5011         var.base |= ((u64)base3) << 32;
5012 #endif
5013         var.limit = get_desc_limit(desc);
5014         if (desc->g)
5015                 var.limit = (var.limit << 12) | 0xfff;
5016         var.type = desc->type;
5017         var.dpl = desc->dpl;
5018         var.db = desc->d;
5019         var.s = desc->s;
5020         var.l = desc->l;
5021         var.g = desc->g;
5022         var.avl = desc->avl;
5023         var.present = desc->p;
5024         var.unusable = !var.present;
5025         var.padding = 0;
5026
5027         kvm_set_segment(vcpu, &var, seg);
5028         return;
5029 }
5030
5031 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
5032                             u32 msr_index, u64 *pdata)
5033 {
5034         struct msr_data msr;
5035         int r;
5036
5037         msr.index = msr_index;
5038         msr.host_initiated = false;
5039         r = kvm_get_msr(emul_to_vcpu(ctxt), &msr);
5040         if (r)
5041                 return r;
5042
5043         *pdata = msr.data;
5044         return 0;
5045 }
5046
5047 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
5048                             u32 msr_index, u64 data)
5049 {
5050         struct msr_data msr;
5051
5052         msr.data = data;
5053         msr.index = msr_index;
5054         msr.host_initiated = false;
5055         return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
5056 }
5057
5058 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
5059 {
5060         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5061
5062         return vcpu->arch.smbase;
5063 }
5064
5065 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
5066 {
5067         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5068
5069         vcpu->arch.smbase = smbase;
5070 }
5071
5072 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
5073                               u32 pmc)
5074 {
5075         return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
5076 }
5077
5078 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
5079                              u32 pmc, u64 *pdata)
5080 {
5081         return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
5082 }
5083
5084 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
5085 {
5086         emul_to_vcpu(ctxt)->arch.halt_request = 1;
5087 }
5088
5089 static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
5090 {
5091         preempt_disable();
5092         kvm_load_guest_fpu(emul_to_vcpu(ctxt));
5093         /*
5094          * CR0.TS may reference the host fpu state, not the guest fpu state,
5095          * so it may be clear at this point.
5096          */
5097         clts();
5098 }
5099
5100 static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
5101 {
5102         preempt_enable();
5103 }
5104
5105 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
5106                               struct x86_instruction_info *info,
5107                               enum x86_intercept_stage stage)
5108 {
5109         return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
5110 }
5111
5112 static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
5113                                u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
5114 {
5115         kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
5116 }
5117
5118 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
5119 {
5120         return kvm_register_read(emul_to_vcpu(ctxt), reg);
5121 }
5122
5123 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
5124 {
5125         kvm_register_write(emul_to_vcpu(ctxt), reg, val);
5126 }
5127
5128 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
5129 {
5130         kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
5131 }
5132
5133 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
5134 {
5135         return emul_to_vcpu(ctxt)->arch.hflags;
5136 }
5137
5138 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
5139 {
5140         kvm_set_hflags(emul_to_vcpu(ctxt), emul_flags);
5141 }
5142
5143 static const struct x86_emulate_ops emulate_ops = {
5144         .read_gpr            = emulator_read_gpr,
5145         .write_gpr           = emulator_write_gpr,
5146         .read_std            = emulator_read_std,
5147         .write_std           = emulator_write_std,
5148         .read_phys           = kvm_read_guest_phys_system,
5149         .fetch               = kvm_fetch_guest_virt,
5150         .read_emulated       = emulator_read_emulated,
5151         .write_emulated      = emulator_write_emulated,
5152         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
5153         .invlpg              = emulator_invlpg,
5154         .pio_in_emulated     = emulator_pio_in_emulated,
5155         .pio_out_emulated    = emulator_pio_out_emulated,
5156         .get_segment         = emulator_get_segment,
5157         .set_segment         = emulator_set_segment,
5158         .get_cached_segment_base = emulator_get_cached_segment_base,
5159         .get_gdt             = emulator_get_gdt,
5160         .get_idt             = emulator_get_idt,
5161         .set_gdt             = emulator_set_gdt,
5162         .set_idt             = emulator_set_idt,
5163         .get_cr              = emulator_get_cr,
5164         .set_cr              = emulator_set_cr,
5165         .cpl                 = emulator_get_cpl,
5166         .get_dr              = emulator_get_dr,
5167         .set_dr              = emulator_set_dr,
5168         .get_smbase          = emulator_get_smbase,
5169         .set_smbase          = emulator_set_smbase,
5170         .set_msr             = emulator_set_msr,
5171         .get_msr             = emulator_get_msr,
5172         .check_pmc           = emulator_check_pmc,
5173         .read_pmc            = emulator_read_pmc,
5174         .halt                = emulator_halt,
5175         .wbinvd              = emulator_wbinvd,
5176         .fix_hypercall       = emulator_fix_hypercall,
5177         .get_fpu             = emulator_get_fpu,
5178         .put_fpu             = emulator_put_fpu,
5179         .intercept           = emulator_intercept,
5180         .get_cpuid           = emulator_get_cpuid,
5181         .set_nmi_mask        = emulator_set_nmi_mask,
5182         .get_hflags          = emulator_get_hflags,
5183         .set_hflags          = emulator_set_hflags,
5184 };
5185
5186 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
5187 {
5188         u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
5189         /*
5190          * an sti; sti; sequence only disable interrupts for the first
5191          * instruction. So, if the last instruction, be it emulated or
5192          * not, left the system with the INT_STI flag enabled, it
5193          * means that the last instruction is an sti. We should not
5194          * leave the flag on in this case. The same goes for mov ss
5195          */
5196         if (int_shadow & mask)
5197                 mask = 0;
5198         if (unlikely(int_shadow || mask)) {
5199                 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
5200                 if (!mask)
5201                         kvm_make_request(KVM_REQ_EVENT, vcpu);
5202         }
5203 }
5204
5205 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
5206 {
5207         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5208         if (ctxt->exception.vector == PF_VECTOR)
5209                 return kvm_propagate_fault(vcpu, &ctxt->exception);
5210
5211         if (ctxt->exception.error_code_valid)
5212                 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
5213                                       ctxt->exception.error_code);
5214         else
5215                 kvm_queue_exception(vcpu, ctxt->exception.vector);
5216         return false;
5217 }
5218
5219 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
5220 {
5221         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5222         int cs_db, cs_l;
5223
5224         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5225
5226         ctxt->eflags = kvm_get_rflags(vcpu);
5227         ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
5228
5229         ctxt->eip = kvm_rip_read(vcpu);
5230         ctxt->mode = (!is_protmode(vcpu))               ? X86EMUL_MODE_REAL :
5231                      (ctxt->eflags & X86_EFLAGS_VM)     ? X86EMUL_MODE_VM86 :
5232                      (cs_l && is_long_mode(vcpu))       ? X86EMUL_MODE_PROT64 :
5233                      cs_db                              ? X86EMUL_MODE_PROT32 :
5234                                                           X86EMUL_MODE_PROT16;
5235         BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
5236         BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
5237         BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
5238
5239         init_decode_cache(ctxt);
5240         vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5241 }
5242
5243 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
5244 {
5245         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5246         int ret;
5247
5248         init_emulate_ctxt(vcpu);
5249
5250         ctxt->op_bytes = 2;
5251         ctxt->ad_bytes = 2;
5252         ctxt->_eip = ctxt->eip + inc_eip;
5253         ret = emulate_int_real(ctxt, irq);
5254
5255         if (ret != X86EMUL_CONTINUE)
5256                 return EMULATE_FAIL;
5257
5258         ctxt->eip = ctxt->_eip;
5259         kvm_rip_write(vcpu, ctxt->eip);
5260         kvm_set_rflags(vcpu, ctxt->eflags);
5261
5262         if (irq == NMI_VECTOR)
5263                 vcpu->arch.nmi_pending = 0;
5264         else
5265                 vcpu->arch.interrupt.pending = false;
5266
5267         return EMULATE_DONE;
5268 }
5269 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
5270
5271 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
5272 {
5273         int r = EMULATE_DONE;
5274
5275         ++vcpu->stat.insn_emulation_fail;
5276         trace_kvm_emulate_insn_failed(vcpu);
5277         if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
5278                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5279                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5280                 vcpu->run->internal.ndata = 0;
5281                 r = EMULATE_USER_EXIT;
5282         }
5283         kvm_queue_exception(vcpu, UD_VECTOR);
5284
5285         return r;
5286 }
5287
5288 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
5289                                   bool write_fault_to_shadow_pgtable,
5290                                   int emulation_type)
5291 {
5292         gpa_t gpa = cr2;
5293         pfn_t pfn;
5294
5295         if (emulation_type & EMULTYPE_NO_REEXECUTE)
5296                 return false;
5297
5298         if (!vcpu->arch.mmu.direct_map) {
5299                 /*
5300                  * Write permission should be allowed since only
5301                  * write access need to be emulated.
5302                  */
5303                 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5304
5305                 /*
5306                  * If the mapping is invalid in guest, let cpu retry
5307                  * it to generate fault.
5308                  */
5309                 if (gpa == UNMAPPED_GVA)
5310                         return true;
5311         }
5312
5313         /*
5314          * Do not retry the unhandleable instruction if it faults on the
5315          * readonly host memory, otherwise it will goto a infinite loop:
5316          * retry instruction -> write #PF -> emulation fail -> retry
5317          * instruction -> ...
5318          */
5319         pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
5320
5321         /*
5322          * If the instruction failed on the error pfn, it can not be fixed,
5323          * report the error to userspace.
5324          */
5325         if (is_error_noslot_pfn(pfn))
5326                 return false;
5327
5328         kvm_release_pfn_clean(pfn);
5329
5330         /* The instructions are well-emulated on direct mmu. */
5331         if (vcpu->arch.mmu.direct_map) {
5332                 unsigned int indirect_shadow_pages;
5333
5334                 spin_lock(&vcpu->kvm->mmu_lock);
5335                 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
5336                 spin_unlock(&vcpu->kvm->mmu_lock);
5337
5338                 if (indirect_shadow_pages)
5339                         kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5340
5341                 return true;
5342         }
5343
5344         /*
5345          * if emulation was due to access to shadowed page table
5346          * and it failed try to unshadow page and re-enter the
5347          * guest to let CPU execute the instruction.
5348          */
5349         kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5350
5351         /*
5352          * If the access faults on its page table, it can not
5353          * be fixed by unprotecting shadow page and it should
5354          * be reported to userspace.
5355          */
5356         return !write_fault_to_shadow_pgtable;
5357 }
5358
5359 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
5360                               unsigned long cr2,  int emulation_type)
5361 {
5362         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5363         unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
5364
5365         last_retry_eip = vcpu->arch.last_retry_eip;
5366         last_retry_addr = vcpu->arch.last_retry_addr;
5367
5368         /*
5369          * If the emulation is caused by #PF and it is non-page_table
5370          * writing instruction, it means the VM-EXIT is caused by shadow
5371          * page protected, we can zap the shadow page and retry this
5372          * instruction directly.
5373          *
5374          * Note: if the guest uses a non-page-table modifying instruction
5375          * on the PDE that points to the instruction, then we will unmap
5376          * the instruction and go to an infinite loop. So, we cache the
5377          * last retried eip and the last fault address, if we meet the eip
5378          * and the address again, we can break out of the potential infinite
5379          * loop.
5380          */
5381         vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
5382
5383         if (!(emulation_type & EMULTYPE_RETRY))
5384                 return false;
5385
5386         if (x86_page_table_writing_insn(ctxt))
5387                 return false;
5388
5389         if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
5390                 return false;
5391
5392         vcpu->arch.last_retry_eip = ctxt->eip;
5393         vcpu->arch.last_retry_addr = cr2;
5394
5395         if (!vcpu->arch.mmu.direct_map)
5396                 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5397
5398         kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5399
5400         return true;
5401 }
5402
5403 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
5404 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
5405
5406 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
5407 {
5408         if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
5409                 /* This is a good place to trace that we are exiting SMM.  */
5410                 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
5411
5412                 if (unlikely(vcpu->arch.smi_pending)) {
5413                         kvm_make_request(KVM_REQ_SMI, vcpu);
5414                         vcpu->arch.smi_pending = 0;
5415                 } else {
5416                         /* Process a latched INIT, if any.  */
5417                         kvm_make_request(KVM_REQ_EVENT, vcpu);
5418                 }
5419         }
5420
5421         kvm_mmu_reset_context(vcpu);
5422 }
5423
5424 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags)
5425 {
5426         unsigned changed = vcpu->arch.hflags ^ emul_flags;
5427
5428         vcpu->arch.hflags = emul_flags;
5429
5430         if (changed & HF_SMM_MASK)
5431                 kvm_smm_changed(vcpu);
5432 }
5433
5434 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
5435                                 unsigned long *db)
5436 {
5437         u32 dr6 = 0;
5438         int i;
5439         u32 enable, rwlen;
5440
5441         enable = dr7;
5442         rwlen = dr7 >> 16;
5443         for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
5444                 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
5445                         dr6 |= (1 << i);
5446         return dr6;
5447 }
5448
5449 static void kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu, int *r)
5450 {
5451         struct kvm_run *kvm_run = vcpu->run;
5452
5453         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
5454                 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
5455                 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
5456                 kvm_run->debug.arch.exception = DB_VECTOR;
5457                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5458                 *r = EMULATE_USER_EXIT;
5459         } else {
5460                 vcpu->arch.emulate_ctxt.eflags &= ~X86_EFLAGS_TF;
5461                 /*
5462                  * "Certain debug exceptions may clear bit 0-3.  The
5463                  * remaining contents of the DR6 register are never
5464                  * cleared by the processor".
5465                  */
5466                 vcpu->arch.dr6 &= ~15;
5467                 vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
5468                 kvm_queue_exception(vcpu, DB_VECTOR);
5469         }
5470 }
5471
5472 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
5473 {
5474         if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
5475             (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
5476                 struct kvm_run *kvm_run = vcpu->run;
5477                 unsigned long eip = kvm_get_linear_rip(vcpu);
5478                 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5479                                            vcpu->arch.guest_debug_dr7,
5480                                            vcpu->arch.eff_db);
5481
5482                 if (dr6 != 0) {
5483                         kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
5484                         kvm_run->debug.arch.pc = eip;
5485                         kvm_run->debug.arch.exception = DB_VECTOR;
5486                         kvm_run->exit_reason = KVM_EXIT_DEBUG;
5487                         *r = EMULATE_USER_EXIT;
5488                         return true;
5489                 }
5490         }
5491
5492         if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
5493             !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
5494                 unsigned long eip = kvm_get_linear_rip(vcpu);
5495                 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5496                                            vcpu->arch.dr7,
5497                                            vcpu->arch.db);
5498
5499                 if (dr6 != 0) {
5500                         vcpu->arch.dr6 &= ~15;
5501                         vcpu->arch.dr6 |= dr6 | DR6_RTM;
5502                         kvm_queue_exception(vcpu, DB_VECTOR);
5503                         *r = EMULATE_DONE;
5504                         return true;
5505                 }
5506         }
5507
5508         return false;
5509 }
5510
5511 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
5512                             unsigned long cr2,
5513                             int emulation_type,
5514                             void *insn,
5515                             int insn_len)
5516 {
5517         int r;
5518         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5519         bool writeback = true;
5520         bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
5521
5522         /*
5523          * Clear write_fault_to_shadow_pgtable here to ensure it is
5524          * never reused.
5525          */
5526         vcpu->arch.write_fault_to_shadow_pgtable = false;
5527         kvm_clear_exception_queue(vcpu);
5528
5529         if (!(emulation_type & EMULTYPE_NO_DECODE)) {
5530                 init_emulate_ctxt(vcpu);
5531
5532                 /*
5533                  * We will reenter on the same instruction since
5534                  * we do not set complete_userspace_io.  This does not
5535                  * handle watchpoints yet, those would be handled in
5536                  * the emulate_ops.
5537                  */
5538                 if (!(emulation_type & EMULTYPE_SKIP) &&
5539                     kvm_vcpu_check_breakpoint(vcpu, &r))
5540                         return r;
5541
5542                 ctxt->interruptibility = 0;
5543                 ctxt->have_exception = false;
5544                 ctxt->exception.vector = -1;
5545                 ctxt->perm_ok = false;
5546
5547                 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
5548
5549                 r = x86_decode_insn(ctxt, insn, insn_len);
5550
5551                 trace_kvm_emulate_insn_start(vcpu);
5552                 ++vcpu->stat.insn_emulation;
5553                 if (r != EMULATION_OK)  {
5554                         if (emulation_type & EMULTYPE_TRAP_UD)
5555                                 return EMULATE_FAIL;
5556                         if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5557                                                 emulation_type))
5558                                 return EMULATE_DONE;
5559                         if (ctxt->have_exception) {
5560                                 /*
5561                                  * #UD should result in just EMULATION_FAILED, and trap-like
5562                                  * exception should not be encountered during decode.
5563                                  */
5564                                 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
5565                                              exception_type(ctxt->exception.vector) == EXCPT_TRAP);
5566                                 inject_emulated_exception(vcpu);
5567                                 return EMULATE_DONE;
5568                         }
5569                         if (emulation_type & EMULTYPE_SKIP)
5570                                 return EMULATE_FAIL;
5571                         return handle_emulation_failure(vcpu);
5572                 }
5573         }
5574
5575         if (emulation_type & EMULTYPE_SKIP) {
5576                 kvm_rip_write(vcpu, ctxt->_eip);
5577                 if (ctxt->eflags & X86_EFLAGS_RF)
5578                         kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
5579                 return EMULATE_DONE;
5580         }
5581
5582         if (retry_instruction(ctxt, cr2, emulation_type))
5583                 return EMULATE_DONE;
5584
5585         /* this is needed for vmware backdoor interface to work since it
5586            changes registers values  during IO operation */
5587         if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
5588                 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5589                 emulator_invalidate_register_cache(ctxt);
5590         }
5591
5592 restart:
5593         r = x86_emulate_insn(ctxt);
5594
5595         if (r == EMULATION_INTERCEPTED)
5596                 return EMULATE_DONE;
5597
5598         if (r == EMULATION_FAILED) {
5599                 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5600                                         emulation_type))
5601                         return EMULATE_DONE;
5602
5603                 return handle_emulation_failure(vcpu);
5604         }
5605
5606         if (ctxt->have_exception) {
5607                 r = EMULATE_DONE;
5608                 if (inject_emulated_exception(vcpu))
5609                         return r;
5610         } else if (vcpu->arch.pio.count) {
5611                 if (!vcpu->arch.pio.in) {
5612                         /* FIXME: return into emulator if single-stepping.  */
5613                         vcpu->arch.pio.count = 0;
5614                 } else {
5615                         writeback = false;
5616                         vcpu->arch.complete_userspace_io = complete_emulated_pio;
5617                 }
5618                 r = EMULATE_USER_EXIT;
5619         } else if (vcpu->mmio_needed) {
5620                 if (!vcpu->mmio_is_write)
5621                         writeback = false;
5622                 r = EMULATE_USER_EXIT;
5623                 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
5624         } else if (r == EMULATION_RESTART)
5625                 goto restart;
5626         else
5627                 r = EMULATE_DONE;
5628
5629         if (writeback) {
5630                 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
5631                 toggle_interruptibility(vcpu, ctxt->interruptibility);
5632                 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5633                 if (!ctxt->have_exception ||
5634                     exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
5635                         kvm_rip_write(vcpu, ctxt->eip);
5636                         if (r == EMULATE_DONE && ctxt->tf)
5637                                 kvm_vcpu_do_singlestep(vcpu, &r);
5638                         __kvm_set_rflags(vcpu, ctxt->eflags);
5639                 }
5640
5641                 /*
5642                  * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
5643                  * do nothing, and it will be requested again as soon as
5644                  * the shadow expires.  But we still need to check here,
5645                  * because POPF has no interrupt shadow.
5646                  */
5647                 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
5648                         kvm_make_request(KVM_REQ_EVENT, vcpu);
5649         } else
5650                 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
5651
5652         return r;
5653 }
5654 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
5655
5656 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
5657 {
5658         unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
5659         int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
5660                                             size, port, &val, 1);
5661         /* do not return to emulator after return from userspace */
5662         vcpu->arch.pio.count = 0;
5663         return ret;
5664 }
5665 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
5666
5667 static void tsc_bad(void *info)
5668 {
5669         __this_cpu_write(cpu_tsc_khz, 0);
5670 }
5671
5672 static void tsc_khz_changed(void *data)
5673 {
5674         struct cpufreq_freqs *freq = data;
5675         unsigned long khz = 0;
5676
5677         if (data)
5678                 khz = freq->new;
5679         else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5680                 khz = cpufreq_quick_get(raw_smp_processor_id());
5681         if (!khz)
5682                 khz = tsc_khz;
5683         __this_cpu_write(cpu_tsc_khz, khz);
5684 }
5685
5686 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
5687                                      void *data)
5688 {
5689         struct cpufreq_freqs *freq = data;
5690         struct kvm *kvm;
5691         struct kvm_vcpu *vcpu;
5692         int i, send_ipi = 0;
5693
5694         /*
5695          * We allow guests to temporarily run on slowing clocks,
5696          * provided we notify them after, or to run on accelerating
5697          * clocks, provided we notify them before.  Thus time never
5698          * goes backwards.
5699          *
5700          * However, we have a problem.  We can't atomically update
5701          * the frequency of a given CPU from this function; it is
5702          * merely a notifier, which can be called from any CPU.
5703          * Changing the TSC frequency at arbitrary points in time
5704          * requires a recomputation of local variables related to
5705          * the TSC for each VCPU.  We must flag these local variables
5706          * to be updated and be sure the update takes place with the
5707          * new frequency before any guests proceed.
5708          *
5709          * Unfortunately, the combination of hotplug CPU and frequency
5710          * change creates an intractable locking scenario; the order
5711          * of when these callouts happen is undefined with respect to
5712          * CPU hotplug, and they can race with each other.  As such,
5713          * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
5714          * undefined; you can actually have a CPU frequency change take
5715          * place in between the computation of X and the setting of the
5716          * variable.  To protect against this problem, all updates of
5717          * the per_cpu tsc_khz variable are done in an interrupt
5718          * protected IPI, and all callers wishing to update the value
5719          * must wait for a synchronous IPI to complete (which is trivial
5720          * if the caller is on the CPU already).  This establishes the
5721          * necessary total order on variable updates.
5722          *
5723          * Note that because a guest time update may take place
5724          * anytime after the setting of the VCPU's request bit, the
5725          * correct TSC value must be set before the request.  However,
5726          * to ensure the update actually makes it to any guest which
5727          * starts running in hardware virtualization between the set
5728          * and the acquisition of the spinlock, we must also ping the
5729          * CPU after setting the request bit.
5730          *
5731          */
5732
5733         if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
5734                 return 0;
5735         if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
5736                 return 0;
5737
5738         smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5739
5740         spin_lock(&kvm_lock);
5741         list_for_each_entry(kvm, &vm_list, vm_list) {
5742                 kvm_for_each_vcpu(i, vcpu, kvm) {
5743                         if (vcpu->cpu != freq->cpu)
5744                                 continue;
5745                         kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5746                         if (vcpu->cpu != smp_processor_id())
5747                                 send_ipi = 1;
5748                 }
5749         }
5750         spin_unlock(&kvm_lock);
5751
5752         if (freq->old < freq->new && send_ipi) {
5753                 /*
5754                  * We upscale the frequency.  Must make the guest
5755                  * doesn't see old kvmclock values while running with
5756                  * the new frequency, otherwise we risk the guest sees
5757                  * time go backwards.
5758                  *
5759                  * In case we update the frequency for another cpu
5760                  * (which might be in guest context) send an interrupt
5761                  * to kick the cpu out of guest context.  Next time
5762                  * guest context is entered kvmclock will be updated,
5763                  * so the guest will not see stale values.
5764                  */
5765                 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5766         }
5767         return 0;
5768 }
5769
5770 static struct notifier_block kvmclock_cpufreq_notifier_block = {
5771         .notifier_call  = kvmclock_cpufreq_notifier
5772 };
5773
5774 static int kvmclock_cpu_notifier(struct notifier_block *nfb,
5775                                         unsigned long action, void *hcpu)
5776 {
5777         unsigned int cpu = (unsigned long)hcpu;
5778
5779         switch (action) {
5780                 case CPU_ONLINE:
5781                 case CPU_DOWN_FAILED:
5782                         smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5783                         break;
5784                 case CPU_DOWN_PREPARE:
5785                         smp_call_function_single(cpu, tsc_bad, NULL, 1);
5786                         break;
5787         }
5788         return NOTIFY_OK;
5789 }
5790
5791 static struct notifier_block kvmclock_cpu_notifier_block = {
5792         .notifier_call  = kvmclock_cpu_notifier,
5793         .priority = -INT_MAX
5794 };
5795
5796 static void kvm_timer_init(void)
5797 {
5798         int cpu;
5799
5800         max_tsc_khz = tsc_khz;
5801
5802         cpu_notifier_register_begin();
5803         if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5804 #ifdef CONFIG_CPU_FREQ
5805                 struct cpufreq_policy policy;
5806                 memset(&policy, 0, sizeof(policy));
5807                 cpu = get_cpu();
5808                 cpufreq_get_policy(&policy, cpu);
5809                 if (policy.cpuinfo.max_freq)
5810                         max_tsc_khz = policy.cpuinfo.max_freq;
5811                 put_cpu();
5812 #endif
5813                 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
5814                                           CPUFREQ_TRANSITION_NOTIFIER);
5815         }
5816         pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
5817         for_each_online_cpu(cpu)
5818                 smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
5819
5820         __register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
5821         cpu_notifier_register_done();
5822
5823 }
5824
5825 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
5826
5827 int kvm_is_in_guest(void)
5828 {
5829         return __this_cpu_read(current_vcpu) != NULL;
5830 }
5831
5832 static int kvm_is_user_mode(void)
5833 {
5834         int user_mode = 3;
5835
5836         if (__this_cpu_read(current_vcpu))
5837                 user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
5838
5839         return user_mode != 0;
5840 }
5841
5842 static unsigned long kvm_get_guest_ip(void)
5843 {
5844         unsigned long ip = 0;
5845
5846         if (__this_cpu_read(current_vcpu))
5847                 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
5848
5849         return ip;
5850 }
5851
5852 static struct perf_guest_info_callbacks kvm_guest_cbs = {
5853         .is_in_guest            = kvm_is_in_guest,
5854         .is_user_mode           = kvm_is_user_mode,
5855         .get_guest_ip           = kvm_get_guest_ip,
5856 };
5857
5858 void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
5859 {
5860         __this_cpu_write(current_vcpu, vcpu);
5861 }
5862 EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
5863
5864 void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
5865 {
5866         __this_cpu_write(current_vcpu, NULL);
5867 }
5868 EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
5869
5870 static void kvm_set_mmio_spte_mask(void)
5871 {
5872         u64 mask;
5873         int maxphyaddr = boot_cpu_data.x86_phys_bits;
5874
5875         /*
5876          * Set the reserved bits and the present bit of an paging-structure
5877          * entry to generate page fault with PFER.RSV = 1.
5878          */
5879          /* Mask the reserved physical address bits. */
5880         mask = rsvd_bits(maxphyaddr, 51);
5881
5882         /* Bit 62 is always reserved for 32bit host. */
5883         mask |= 0x3ull << 62;
5884
5885         /* Set the present bit. */
5886         mask |= 1ull;
5887
5888 #ifdef CONFIG_X86_64
5889         /*
5890          * If reserved bit is not supported, clear the present bit to disable
5891          * mmio page fault.
5892          */
5893         if (maxphyaddr == 52)
5894                 mask &= ~1ull;
5895 #endif
5896
5897         kvm_mmu_set_mmio_spte_mask(mask);
5898 }
5899
5900 #ifdef CONFIG_X86_64
5901 static void pvclock_gtod_update_fn(struct work_struct *work)
5902 {
5903         struct kvm *kvm;
5904
5905         struct kvm_vcpu *vcpu;
5906         int i;
5907
5908         spin_lock(&kvm_lock);
5909         list_for_each_entry(kvm, &vm_list, vm_list)
5910                 kvm_for_each_vcpu(i, vcpu, kvm)
5911                         kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
5912         atomic_set(&kvm_guest_has_master_clock, 0);
5913         spin_unlock(&kvm_lock);
5914 }
5915
5916 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
5917
5918 /*
5919  * Notification about pvclock gtod data update.
5920  */
5921 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
5922                                void *priv)
5923 {
5924         struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
5925         struct timekeeper *tk = priv;
5926
5927         update_pvclock_gtod(tk);
5928
5929         /* disable master clock if host does not trust, or does not
5930          * use, TSC clocksource
5931          */
5932         if (gtod->clock.vclock_mode != VCLOCK_TSC &&
5933             atomic_read(&kvm_guest_has_master_clock) != 0)
5934                 queue_work(system_long_wq, &pvclock_gtod_work);
5935
5936         return 0;
5937 }
5938
5939 static struct notifier_block pvclock_gtod_notifier = {
5940         .notifier_call = pvclock_gtod_notify,
5941 };
5942 #endif
5943
5944 int kvm_arch_init(void *opaque)
5945 {
5946         int r;
5947         struct kvm_x86_ops *ops = opaque;
5948
5949         if (kvm_x86_ops) {
5950                 printk(KERN_ERR "kvm: already loaded the other module\n");
5951                 r = -EEXIST;
5952                 goto out;
5953         }
5954
5955         if (!ops->cpu_has_kvm_support()) {
5956                 printk(KERN_ERR "kvm: no hardware support\n");
5957                 r = -EOPNOTSUPP;
5958                 goto out;
5959         }
5960         if (ops->disabled_by_bios()) {
5961                 printk(KERN_ERR "kvm: disabled by bios\n");
5962                 r = -EOPNOTSUPP;
5963                 goto out;
5964         }
5965
5966         r = -ENOMEM;
5967         shared_msrs = alloc_percpu(struct kvm_shared_msrs);
5968         if (!shared_msrs) {
5969                 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
5970                 goto out;
5971         }
5972
5973         r = kvm_mmu_module_init();
5974         if (r)
5975                 goto out_free_percpu;
5976
5977         kvm_set_mmio_spte_mask();
5978
5979         kvm_x86_ops = ops;
5980
5981         kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
5982                         PT_DIRTY_MASK, PT64_NX_MASK, 0);
5983
5984         kvm_timer_init();
5985
5986         perf_register_guest_info_callbacks(&kvm_guest_cbs);
5987
5988         if (cpu_has_xsave)
5989                 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
5990
5991         kvm_lapic_init();
5992 #ifdef CONFIG_X86_64
5993         pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
5994 #endif
5995
5996         return 0;
5997
5998 out_free_percpu:
5999         free_percpu(shared_msrs);
6000 out:
6001         return r;
6002 }
6003
6004 void kvm_arch_exit(void)
6005 {
6006         kvm_lapic_exit();
6007         perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
6008
6009         if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
6010                 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
6011                                             CPUFREQ_TRANSITION_NOTIFIER);
6012         unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
6013 #ifdef CONFIG_X86_64
6014         pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
6015 #endif
6016         kvm_x86_ops = NULL;
6017         kvm_mmu_module_exit();
6018         free_percpu(shared_msrs);
6019 }
6020
6021 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
6022 {
6023         ++vcpu->stat.halt_exits;
6024         if (lapic_in_kernel(vcpu)) {
6025                 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
6026                 return 1;
6027         } else {
6028                 vcpu->run->exit_reason = KVM_EXIT_HLT;
6029                 return 0;
6030         }
6031 }
6032 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
6033
6034 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
6035 {
6036         kvm_x86_ops->skip_emulated_instruction(vcpu);
6037         return kvm_vcpu_halt(vcpu);
6038 }
6039 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
6040
6041 /*
6042  * kvm_pv_kick_cpu_op:  Kick a vcpu.
6043  *
6044  * @apicid - apicid of vcpu to be kicked.
6045  */
6046 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
6047 {
6048         struct kvm_lapic_irq lapic_irq;
6049
6050         lapic_irq.shorthand = 0;
6051         lapic_irq.dest_mode = 0;
6052         lapic_irq.dest_id = apicid;
6053         lapic_irq.msi_redir_hint = false;
6054
6055         lapic_irq.delivery_mode = APIC_DM_REMRD;
6056         kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
6057 }
6058
6059 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
6060 {
6061         unsigned long nr, a0, a1, a2, a3, ret;
6062         int op_64_bit, r = 1;
6063
6064         kvm_x86_ops->skip_emulated_instruction(vcpu);
6065
6066         if (kvm_hv_hypercall_enabled(vcpu->kvm))
6067                 return kvm_hv_hypercall(vcpu);
6068
6069         nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
6070         a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
6071         a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
6072         a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
6073         a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
6074
6075         trace_kvm_hypercall(nr, a0, a1, a2, a3);
6076
6077         op_64_bit = is_64_bit_mode(vcpu);
6078         if (!op_64_bit) {
6079                 nr &= 0xFFFFFFFF;
6080                 a0 &= 0xFFFFFFFF;
6081                 a1 &= 0xFFFFFFFF;
6082                 a2 &= 0xFFFFFFFF;
6083                 a3 &= 0xFFFFFFFF;
6084         }
6085
6086         if (kvm_x86_ops->get_cpl(vcpu) != 0) {
6087                 ret = -KVM_EPERM;
6088                 goto out;
6089         }
6090
6091         switch (nr) {
6092         case KVM_HC_VAPIC_POLL_IRQ:
6093                 ret = 0;
6094                 break;
6095         case KVM_HC_KICK_CPU:
6096                 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
6097                 ret = 0;
6098                 break;
6099         default:
6100                 ret = -KVM_ENOSYS;
6101                 break;
6102         }
6103 out:
6104         if (!op_64_bit)
6105                 ret = (u32)ret;
6106         kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
6107         ++vcpu->stat.hypercalls;
6108         return r;
6109 }
6110 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
6111
6112 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
6113 {
6114         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6115         char instruction[3];
6116         unsigned long rip = kvm_rip_read(vcpu);
6117
6118         kvm_x86_ops->patch_hypercall(vcpu, instruction);
6119
6120         return emulator_write_emulated(ctxt, rip, instruction, 3,
6121                 &ctxt->exception);
6122 }
6123
6124 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
6125 {
6126         return vcpu->run->request_interrupt_window &&
6127                 likely(!pic_in_kernel(vcpu->kvm));
6128 }
6129
6130 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
6131 {
6132         struct kvm_run *kvm_run = vcpu->run;
6133
6134         kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
6135         kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
6136         kvm_run->cr8 = kvm_get_cr8(vcpu);
6137         kvm_run->apic_base = kvm_get_apic_base(vcpu);
6138         kvm_run->ready_for_interrupt_injection =
6139                 pic_in_kernel(vcpu->kvm) ||
6140                 kvm_vcpu_ready_for_interrupt_injection(vcpu);
6141 }
6142
6143 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
6144 {
6145         int max_irr, tpr;
6146
6147         if (!kvm_x86_ops->update_cr8_intercept)
6148                 return;
6149
6150         if (!vcpu->arch.apic)
6151                 return;
6152
6153         if (!vcpu->arch.apic->vapic_addr)
6154                 max_irr = kvm_lapic_find_highest_irr(vcpu);
6155         else
6156                 max_irr = -1;
6157
6158         if (max_irr != -1)
6159                 max_irr >>= 4;
6160
6161         tpr = kvm_lapic_get_cr8(vcpu);
6162
6163         kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
6164 }
6165
6166 static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
6167 {
6168         int r;
6169
6170         /* try to reinject previous events if any */
6171         if (vcpu->arch.exception.pending) {
6172                 trace_kvm_inj_exception(vcpu->arch.exception.nr,
6173                                         vcpu->arch.exception.has_error_code,
6174                                         vcpu->arch.exception.error_code);
6175
6176                 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
6177                         __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
6178                                              X86_EFLAGS_RF);
6179
6180                 if (vcpu->arch.exception.nr == DB_VECTOR &&
6181                     (vcpu->arch.dr7 & DR7_GD)) {
6182                         vcpu->arch.dr7 &= ~DR7_GD;
6183                         kvm_update_dr7(vcpu);
6184                 }
6185
6186                 kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
6187                                           vcpu->arch.exception.has_error_code,
6188                                           vcpu->arch.exception.error_code,
6189                                           vcpu->arch.exception.reinject);
6190                 return 0;
6191         }
6192
6193         if (vcpu->arch.nmi_injected) {
6194                 kvm_x86_ops->set_nmi(vcpu);
6195                 return 0;
6196         }
6197
6198         if (vcpu->arch.interrupt.pending) {
6199                 kvm_x86_ops->set_irq(vcpu);
6200                 return 0;
6201         }
6202
6203         if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6204                 r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6205                 if (r != 0)
6206                         return r;
6207         }
6208
6209         /* try to inject new event if pending */
6210         if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
6211                 --vcpu->arch.nmi_pending;
6212                 vcpu->arch.nmi_injected = true;
6213                 kvm_x86_ops->set_nmi(vcpu);
6214         } else if (kvm_cpu_has_injectable_intr(vcpu)) {
6215                 /*
6216                  * Because interrupts can be injected asynchronously, we are
6217                  * calling check_nested_events again here to avoid a race condition.
6218                  * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
6219                  * proposal and current concerns.  Perhaps we should be setting
6220                  * KVM_REQ_EVENT only on certain events and not unconditionally?
6221                  */
6222                 if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
6223                         r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
6224                         if (r != 0)
6225                                 return r;
6226                 }
6227                 if (kvm_x86_ops->interrupt_allowed(vcpu)) {
6228                         kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
6229                                             false);
6230                         kvm_x86_ops->set_irq(vcpu);
6231                 }
6232         }
6233         return 0;
6234 }
6235
6236 static void process_nmi(struct kvm_vcpu *vcpu)
6237 {
6238         unsigned limit = 2;
6239
6240         /*
6241          * x86 is limited to one NMI running, and one NMI pending after it.
6242          * If an NMI is already in progress, limit further NMIs to just one.
6243          * Otherwise, allow two (and we'll inject the first one immediately).
6244          */
6245         if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
6246                 limit = 1;
6247
6248         vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
6249         vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
6250         kvm_make_request(KVM_REQ_EVENT, vcpu);
6251 }
6252
6253 #define put_smstate(type, buf, offset, val)                       \
6254         *(type *)((buf) + (offset) - 0x7e00) = val
6255
6256 static u32 process_smi_get_segment_flags(struct kvm_segment *seg)
6257 {
6258         u32 flags = 0;
6259         flags |= seg->g       << 23;
6260         flags |= seg->db      << 22;
6261         flags |= seg->l       << 21;
6262         flags |= seg->avl     << 20;
6263         flags |= seg->present << 15;
6264         flags |= seg->dpl     << 13;
6265         flags |= seg->s       << 12;
6266         flags |= seg->type    << 8;
6267         return flags;
6268 }
6269
6270 static void process_smi_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
6271 {
6272         struct kvm_segment seg;
6273         int offset;
6274
6275         kvm_get_segment(vcpu, &seg, n);
6276         put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
6277
6278         if (n < 3)
6279                 offset = 0x7f84 + n * 12;
6280         else
6281                 offset = 0x7f2c + (n - 3) * 12;
6282
6283         put_smstate(u32, buf, offset + 8, seg.base);
6284         put_smstate(u32, buf, offset + 4, seg.limit);
6285         put_smstate(u32, buf, offset, process_smi_get_segment_flags(&seg));
6286 }
6287
6288 #ifdef CONFIG_X86_64
6289 static void process_smi_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
6290 {
6291         struct kvm_segment seg;
6292         int offset;
6293         u16 flags;
6294
6295         kvm_get_segment(vcpu, &seg, n);
6296         offset = 0x7e00 + n * 16;
6297
6298         flags = process_smi_get_segment_flags(&seg) >> 8;
6299         put_smstate(u16, buf, offset, seg.selector);
6300         put_smstate(u16, buf, offset + 2, flags);
6301         put_smstate(u32, buf, offset + 4, seg.limit);
6302         put_smstate(u64, buf, offset + 8, seg.base);
6303 }
6304 #endif
6305
6306 static void process_smi_save_state_32(struct kvm_vcpu *vcpu, char *buf)
6307 {
6308         struct desc_ptr dt;
6309         struct kvm_segment seg;
6310         unsigned long val;
6311         int i;
6312
6313         put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
6314         put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
6315         put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
6316         put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
6317
6318         for (i = 0; i < 8; i++)
6319                 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
6320
6321         kvm_get_dr(vcpu, 6, &val);
6322         put_smstate(u32, buf, 0x7fcc, (u32)val);
6323         kvm_get_dr(vcpu, 7, &val);
6324         put_smstate(u32, buf, 0x7fc8, (u32)val);
6325
6326         kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6327         put_smstate(u32, buf, 0x7fc4, seg.selector);
6328         put_smstate(u32, buf, 0x7f64, seg.base);
6329         put_smstate(u32, buf, 0x7f60, seg.limit);
6330         put_smstate(u32, buf, 0x7f5c, process_smi_get_segment_flags(&seg));
6331
6332         kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6333         put_smstate(u32, buf, 0x7fc0, seg.selector);
6334         put_smstate(u32, buf, 0x7f80, seg.base);
6335         put_smstate(u32, buf, 0x7f7c, seg.limit);
6336         put_smstate(u32, buf, 0x7f78, process_smi_get_segment_flags(&seg));
6337
6338         kvm_x86_ops->get_gdt(vcpu, &dt);
6339         put_smstate(u32, buf, 0x7f74, dt.address);
6340         put_smstate(u32, buf, 0x7f70, dt.size);
6341
6342         kvm_x86_ops->get_idt(vcpu, &dt);
6343         put_smstate(u32, buf, 0x7f58, dt.address);
6344         put_smstate(u32, buf, 0x7f54, dt.size);
6345
6346         for (i = 0; i < 6; i++)
6347                 process_smi_save_seg_32(vcpu, buf, i);
6348
6349         put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
6350
6351         /* revision id */
6352         put_smstate(u32, buf, 0x7efc, 0x00020000);
6353         put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
6354 }
6355
6356 static void process_smi_save_state_64(struct kvm_vcpu *vcpu, char *buf)
6357 {
6358 #ifdef CONFIG_X86_64
6359         struct desc_ptr dt;
6360         struct kvm_segment seg;
6361         unsigned long val;
6362         int i;
6363
6364         for (i = 0; i < 16; i++)
6365                 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
6366
6367         put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
6368         put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
6369
6370         kvm_get_dr(vcpu, 6, &val);
6371         put_smstate(u64, buf, 0x7f68, val);
6372         kvm_get_dr(vcpu, 7, &val);
6373         put_smstate(u64, buf, 0x7f60, val);
6374
6375         put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
6376         put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
6377         put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
6378
6379         put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
6380
6381         /* revision id */
6382         put_smstate(u32, buf, 0x7efc, 0x00020064);
6383
6384         put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
6385
6386         kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
6387         put_smstate(u16, buf, 0x7e90, seg.selector);
6388         put_smstate(u16, buf, 0x7e92, process_smi_get_segment_flags(&seg) >> 8);
6389         put_smstate(u32, buf, 0x7e94, seg.limit);
6390         put_smstate(u64, buf, 0x7e98, seg.base);
6391
6392         kvm_x86_ops->get_idt(vcpu, &dt);
6393         put_smstate(u32, buf, 0x7e84, dt.size);
6394         put_smstate(u64, buf, 0x7e88, dt.address);
6395
6396         kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
6397         put_smstate(u16, buf, 0x7e70, seg.selector);
6398         put_smstate(u16, buf, 0x7e72, process_smi_get_segment_flags(&seg) >> 8);
6399         put_smstate(u32, buf, 0x7e74, seg.limit);
6400         put_smstate(u64, buf, 0x7e78, seg.base);
6401
6402         kvm_x86_ops->get_gdt(vcpu, &dt);
6403         put_smstate(u32, buf, 0x7e64, dt.size);
6404         put_smstate(u64, buf, 0x7e68, dt.address);
6405
6406         for (i = 0; i < 6; i++)
6407                 process_smi_save_seg_64(vcpu, buf, i);
6408 #else
6409         WARN_ON_ONCE(1);
6410 #endif
6411 }
6412
6413 static void process_smi(struct kvm_vcpu *vcpu)
6414 {
6415         struct kvm_segment cs, ds;
6416         struct desc_ptr dt;
6417         char buf[512];
6418         u32 cr0;
6419
6420         if (is_smm(vcpu)) {
6421                 vcpu->arch.smi_pending = true;
6422                 return;
6423         }
6424
6425         trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
6426         vcpu->arch.hflags |= HF_SMM_MASK;
6427         memset(buf, 0, 512);
6428         if (guest_cpuid_has_longmode(vcpu))
6429                 process_smi_save_state_64(vcpu, buf);
6430         else
6431                 process_smi_save_state_32(vcpu, buf);
6432
6433         kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
6434
6435         if (kvm_x86_ops->get_nmi_mask(vcpu))
6436                 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
6437         else
6438                 kvm_x86_ops->set_nmi_mask(vcpu, true);
6439
6440         kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
6441         kvm_rip_write(vcpu, 0x8000);
6442
6443         cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
6444         kvm_x86_ops->set_cr0(vcpu, cr0);
6445         vcpu->arch.cr0 = cr0;
6446
6447         kvm_x86_ops->set_cr4(vcpu, 0);
6448
6449         /* Undocumented: IDT limit is set to zero on entry to SMM.  */
6450         dt.address = dt.size = 0;
6451         kvm_x86_ops->set_idt(vcpu, &dt);
6452
6453         __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
6454
6455         cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
6456         cs.base = vcpu->arch.smbase;
6457
6458         ds.selector = 0;
6459         ds.base = 0;
6460
6461         cs.limit    = ds.limit = 0xffffffff;
6462         cs.type     = ds.type = 0x3;
6463         cs.dpl      = ds.dpl = 0;
6464         cs.db       = ds.db = 0;
6465         cs.s        = ds.s = 1;
6466         cs.l        = ds.l = 0;
6467         cs.g        = ds.g = 1;
6468         cs.avl      = ds.avl = 0;
6469         cs.present  = ds.present = 1;
6470         cs.unusable = ds.unusable = 0;
6471         cs.padding  = ds.padding = 0;
6472
6473         kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
6474         kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
6475         kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
6476         kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
6477         kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
6478         kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
6479
6480         if (guest_cpuid_has_longmode(vcpu))
6481                 kvm_x86_ops->set_efer(vcpu, 0);
6482
6483         kvm_update_cpuid(vcpu);
6484         kvm_mmu_reset_context(vcpu);
6485 }
6486
6487 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
6488 {
6489         if (!kvm_apic_hw_enabled(vcpu->arch.apic))
6490                 return;
6491
6492         memset(vcpu->arch.eoi_exit_bitmap, 0, 256 / 8);
6493
6494         if (irqchip_split(vcpu->kvm))
6495                 kvm_scan_ioapic_routes(vcpu, vcpu->arch.eoi_exit_bitmap);
6496         else {
6497                 kvm_x86_ops->sync_pir_to_irr(vcpu);
6498                 if (ioapic_in_kernel(vcpu->kvm))
6499                         kvm_ioapic_scan_entry(vcpu, vcpu->arch.eoi_exit_bitmap);
6500         }
6501         kvm_x86_ops->load_eoi_exitmap(vcpu);
6502 }
6503
6504 static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu)
6505 {
6506         ++vcpu->stat.tlb_flush;
6507         kvm_x86_ops->tlb_flush(vcpu);
6508 }
6509
6510 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
6511 {
6512         struct page *page = NULL;
6513
6514         if (!lapic_in_kernel(vcpu))
6515                 return;
6516
6517         if (!kvm_x86_ops->set_apic_access_page_addr)
6518                 return;
6519
6520         page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6521         if (is_error_page(page))
6522                 return;
6523         kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
6524
6525         /*
6526          * Do not pin apic access page in memory, the MMU notifier
6527          * will call us again if it is migrated or swapped out.
6528          */
6529         put_page(page);
6530 }
6531 EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
6532
6533 void kvm_arch_mmu_notifier_invalidate_page(struct kvm *kvm,
6534                                            unsigned long address)
6535 {
6536         /*
6537          * The physical address of apic access page is stored in the VMCS.
6538          * Update it when it becomes invalid.
6539          */
6540         if (address == gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT))
6541                 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
6542 }
6543
6544 /*
6545  * Returns 1 to let vcpu_run() continue the guest execution loop without
6546  * exiting to the userspace.  Otherwise, the value will be returned to the
6547  * userspace.
6548  */
6549 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
6550 {
6551         int r;
6552         bool req_int_win =
6553                 dm_request_for_irq_injection(vcpu) &&
6554                 kvm_cpu_accept_dm_intr(vcpu);
6555
6556         bool req_immediate_exit = false;
6557
6558         if (vcpu->requests) {
6559                 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
6560                         kvm_mmu_unload(vcpu);
6561                 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
6562                         __kvm_migrate_timers(vcpu);
6563                 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
6564                         kvm_gen_update_masterclock(vcpu->kvm);
6565                 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
6566                         kvm_gen_kvmclock_update(vcpu);
6567                 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
6568                         r = kvm_guest_time_update(vcpu);
6569                         if (unlikely(r))
6570                                 goto out;
6571                 }
6572                 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
6573                         kvm_mmu_sync_roots(vcpu);
6574                 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
6575                         kvm_vcpu_flush_tlb(vcpu);
6576                 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
6577                         vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
6578                         r = 0;
6579                         goto out;
6580                 }
6581                 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
6582                         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6583                         vcpu->mmio_needed = 0;
6584                         r = 0;
6585                         goto out;
6586                 }
6587                 if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
6588                         vcpu->fpu_active = 0;
6589                         kvm_x86_ops->fpu_deactivate(vcpu);
6590                 }
6591                 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
6592                         /* Page is swapped out. Do synthetic halt */
6593                         vcpu->arch.apf.halted = true;
6594                         r = 1;
6595                         goto out;
6596                 }
6597                 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
6598                         record_steal_time(vcpu);
6599                 if (kvm_check_request(KVM_REQ_SMI, vcpu))
6600                         process_smi(vcpu);
6601                 if (kvm_check_request(KVM_REQ_NMI, vcpu))
6602                         process_nmi(vcpu);
6603                 if (kvm_check_request(KVM_REQ_PMU, vcpu))
6604                         kvm_pmu_handle_event(vcpu);
6605                 if (kvm_check_request(KVM_REQ_PMI, vcpu))
6606                         kvm_pmu_deliver_pmi(vcpu);
6607                 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
6608                         BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
6609                         if (test_bit(vcpu->arch.pending_ioapic_eoi,
6610                                      (void *) vcpu->arch.eoi_exit_bitmap)) {
6611                                 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
6612                                 vcpu->run->eoi.vector =
6613                                                 vcpu->arch.pending_ioapic_eoi;
6614                                 r = 0;
6615                                 goto out;
6616                         }
6617                 }
6618                 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
6619                         vcpu_scan_ioapic(vcpu);
6620                 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
6621                         kvm_vcpu_reload_apic_access_page(vcpu);
6622                 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
6623                         vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6624                         vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
6625                         r = 0;
6626                         goto out;
6627                 }
6628                 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
6629                         vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
6630                         vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
6631                         r = 0;
6632                         goto out;
6633                 }
6634         }
6635
6636         /*
6637          * KVM_REQ_EVENT is not set when posted interrupts are set by
6638          * VT-d hardware, so we have to update RVI unconditionally.
6639          */
6640         if (kvm_lapic_enabled(vcpu)) {
6641                 /*
6642                  * Update architecture specific hints for APIC
6643                  * virtual interrupt delivery.
6644                  */
6645                 if (kvm_x86_ops->hwapic_irr_update)
6646                         kvm_x86_ops->hwapic_irr_update(vcpu,
6647                                 kvm_lapic_find_highest_irr(vcpu));
6648         }
6649
6650         if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
6651                 kvm_apic_accept_events(vcpu);
6652                 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
6653                         r = 1;
6654                         goto out;
6655                 }
6656
6657                 if (inject_pending_event(vcpu, req_int_win) != 0)
6658                         req_immediate_exit = true;
6659                 /* enable NMI/IRQ window open exits if needed */
6660                 else {
6661                         if (vcpu->arch.nmi_pending)
6662                                 kvm_x86_ops->enable_nmi_window(vcpu);
6663                         if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
6664                                 kvm_x86_ops->enable_irq_window(vcpu);
6665                 }
6666
6667                 if (kvm_lapic_enabled(vcpu)) {
6668                         update_cr8_intercept(vcpu);
6669                         kvm_lapic_sync_to_vapic(vcpu);
6670                 }
6671         }
6672
6673         r = kvm_mmu_reload(vcpu);
6674         if (unlikely(r)) {
6675                 goto cancel_injection;
6676         }
6677
6678         preempt_disable();
6679
6680         kvm_x86_ops->prepare_guest_switch(vcpu);
6681         if (vcpu->fpu_active)
6682                 kvm_load_guest_fpu(vcpu);
6683         vcpu->mode = IN_GUEST_MODE;
6684
6685         srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6686
6687         /* We should set ->mode before check ->requests,
6688          * see the comment in make_all_cpus_request.
6689          */
6690         smp_mb__after_srcu_read_unlock();
6691
6692         local_irq_disable();
6693
6694         if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
6695             || need_resched() || signal_pending(current)) {
6696                 vcpu->mode = OUTSIDE_GUEST_MODE;
6697                 smp_wmb();
6698                 local_irq_enable();
6699                 preempt_enable();
6700                 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6701                 r = 1;
6702                 goto cancel_injection;
6703         }
6704
6705         kvm_load_guest_xcr0(vcpu);
6706
6707         if (req_immediate_exit)
6708                 smp_send_reschedule(vcpu->cpu);
6709
6710         trace_kvm_entry(vcpu->vcpu_id);
6711         wait_lapic_expire(vcpu);
6712         __kvm_guest_enter();
6713
6714         if (unlikely(vcpu->arch.switch_db_regs)) {
6715                 set_debugreg(0, 7);
6716                 set_debugreg(vcpu->arch.eff_db[0], 0);
6717                 set_debugreg(vcpu->arch.eff_db[1], 1);
6718                 set_debugreg(vcpu->arch.eff_db[2], 2);
6719                 set_debugreg(vcpu->arch.eff_db[3], 3);
6720                 set_debugreg(vcpu->arch.dr6, 6);
6721                 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
6722         }
6723
6724         kvm_x86_ops->run(vcpu);
6725
6726         /*
6727          * Do this here before restoring debug registers on the host.  And
6728          * since we do this before handling the vmexit, a DR access vmexit
6729          * can (a) read the correct value of the debug registers, (b) set
6730          * KVM_DEBUGREG_WONT_EXIT again.
6731          */
6732         if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
6733                 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
6734                 kvm_x86_ops->sync_dirty_debug_regs(vcpu);
6735                 kvm_update_dr0123(vcpu);
6736                 kvm_update_dr6(vcpu);
6737                 kvm_update_dr7(vcpu);
6738                 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
6739         }
6740
6741         /*
6742          * If the guest has used debug registers, at least dr7
6743          * will be disabled while returning to the host.
6744          * If we don't have active breakpoints in the host, we don't
6745          * care about the messed up debug address registers. But if
6746          * we have some of them active, restore the old state.
6747          */
6748         if (hw_breakpoint_active())
6749                 hw_breakpoint_restore();
6750
6751         vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
6752
6753         vcpu->mode = OUTSIDE_GUEST_MODE;
6754         smp_wmb();
6755
6756         kvm_put_guest_xcr0(vcpu);
6757
6758         /* Interrupt is enabled by handle_external_intr() */
6759         kvm_x86_ops->handle_external_intr(vcpu);
6760
6761         ++vcpu->stat.exits;
6762
6763         /*
6764          * We must have an instruction between local_irq_enable() and
6765          * kvm_guest_exit(), so the timer interrupt isn't delayed by
6766          * the interrupt shadow.  The stat.exits increment will do nicely.
6767          * But we need to prevent reordering, hence this barrier():
6768          */
6769         barrier();
6770
6771         kvm_guest_exit();
6772
6773         preempt_enable();
6774
6775         vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6776
6777         /*
6778          * Profile KVM exit RIPs:
6779          */
6780         if (unlikely(prof_on == KVM_PROFILING)) {
6781                 unsigned long rip = kvm_rip_read(vcpu);
6782                 profile_hit(KVM_PROFILING, (void *)rip);
6783         }
6784
6785         if (unlikely(vcpu->arch.tsc_always_catchup))
6786                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
6787
6788         if (vcpu->arch.apic_attention)
6789                 kvm_lapic_sync_from_vapic(vcpu);
6790
6791         r = kvm_x86_ops->handle_exit(vcpu);
6792         return r;
6793
6794 cancel_injection:
6795         kvm_x86_ops->cancel_injection(vcpu);
6796         if (unlikely(vcpu->arch.apic_attention))
6797                 kvm_lapic_sync_from_vapic(vcpu);
6798 out:
6799         return r;
6800 }
6801
6802 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
6803 {
6804         if (!kvm_arch_vcpu_runnable(vcpu) &&
6805             (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
6806                 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6807                 kvm_vcpu_block(vcpu);
6808                 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6809
6810                 if (kvm_x86_ops->post_block)
6811                         kvm_x86_ops->post_block(vcpu);
6812
6813                 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
6814                         return 1;
6815         }
6816
6817         kvm_apic_accept_events(vcpu);
6818         switch(vcpu->arch.mp_state) {
6819         case KVM_MP_STATE_HALTED:
6820                 vcpu->arch.pv.pv_unhalted = false;
6821                 vcpu->arch.mp_state =
6822                         KVM_MP_STATE_RUNNABLE;
6823         case KVM_MP_STATE_RUNNABLE:
6824                 vcpu->arch.apf.halted = false;
6825                 break;
6826         case KVM_MP_STATE_INIT_RECEIVED:
6827                 break;
6828         default:
6829                 return -EINTR;
6830                 break;
6831         }
6832         return 1;
6833 }
6834
6835 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
6836 {
6837         return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
6838                 !vcpu->arch.apf.halted);
6839 }
6840
6841 static int vcpu_run(struct kvm_vcpu *vcpu)
6842 {
6843         int r;
6844         struct kvm *kvm = vcpu->kvm;
6845
6846         vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6847
6848         for (;;) {
6849                 if (kvm_vcpu_running(vcpu)) {
6850                         r = vcpu_enter_guest(vcpu);
6851                 } else {
6852                         r = vcpu_block(kvm, vcpu);
6853                 }
6854
6855                 if (r <= 0)
6856                         break;
6857
6858                 clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
6859                 if (kvm_cpu_has_pending_timer(vcpu))
6860                         kvm_inject_pending_timer_irqs(vcpu);
6861
6862                 if (dm_request_for_irq_injection(vcpu) &&
6863                         kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
6864                         r = 0;
6865                         vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
6866                         ++vcpu->stat.request_irq_exits;
6867                         break;
6868                 }
6869
6870                 kvm_check_async_pf_completion(vcpu);
6871
6872                 if (signal_pending(current)) {
6873                         r = -EINTR;
6874                         vcpu->run->exit_reason = KVM_EXIT_INTR;
6875                         ++vcpu->stat.signal_exits;
6876                         break;
6877                 }
6878                 if (need_resched()) {
6879                         srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6880                         cond_resched();
6881                         vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
6882                 }
6883         }
6884
6885         srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
6886
6887         return r;
6888 }
6889
6890 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
6891 {
6892         int r;
6893         vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
6894         r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
6895         srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
6896         if (r != EMULATE_DONE)
6897                 return 0;
6898         return 1;
6899 }
6900
6901 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
6902 {
6903         BUG_ON(!vcpu->arch.pio.count);
6904
6905         return complete_emulated_io(vcpu);
6906 }
6907
6908 /*
6909  * Implements the following, as a state machine:
6910  *
6911  * read:
6912  *   for each fragment
6913  *     for each mmio piece in the fragment
6914  *       write gpa, len
6915  *       exit
6916  *       copy data
6917  *   execute insn
6918  *
6919  * write:
6920  *   for each fragment
6921  *     for each mmio piece in the fragment
6922  *       write gpa, len
6923  *       copy data
6924  *       exit
6925  */
6926 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
6927 {
6928         struct kvm_run *run = vcpu->run;
6929         struct kvm_mmio_fragment *frag;
6930         unsigned len;
6931
6932         BUG_ON(!vcpu->mmio_needed);
6933
6934         /* Complete previous fragment */
6935         frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
6936         len = min(8u, frag->len);
6937         if (!vcpu->mmio_is_write)
6938                 memcpy(frag->data, run->mmio.data, len);
6939
6940         if (frag->len <= 8) {
6941                 /* Switch to the next fragment. */
6942                 frag++;
6943                 vcpu->mmio_cur_fragment++;
6944         } else {
6945                 /* Go forward to the next mmio piece. */
6946                 frag->data += len;
6947                 frag->gpa += len;
6948                 frag->len -= len;
6949         }
6950
6951         if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
6952                 vcpu->mmio_needed = 0;
6953
6954                 /* FIXME: return into emulator if single-stepping.  */
6955                 if (vcpu->mmio_is_write)
6956                         return 1;
6957                 vcpu->mmio_read_completed = 1;
6958                 return complete_emulated_io(vcpu);
6959         }
6960
6961         run->exit_reason = KVM_EXIT_MMIO;
6962         run->mmio.phys_addr = frag->gpa;
6963         if (vcpu->mmio_is_write)
6964                 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
6965         run->mmio.len = min(8u, frag->len);
6966         run->mmio.is_write = vcpu->mmio_is_write;
6967         vcpu->arch.complete_userspace_io = complete_emulated_mmio;
6968         return 0;
6969 }
6970
6971
6972 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
6973 {
6974         struct fpu *fpu = &current->thread.fpu;
6975         int r;
6976         sigset_t sigsaved;
6977
6978         fpu__activate_curr(fpu);
6979
6980         if (vcpu->sigset_active)
6981                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
6982
6983         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
6984                 kvm_vcpu_block(vcpu);
6985                 kvm_apic_accept_events(vcpu);
6986                 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
6987                 r = -EAGAIN;
6988                 goto out;
6989         }
6990
6991         /* re-sync apic's tpr */
6992         if (!lapic_in_kernel(vcpu)) {
6993                 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
6994                         r = -EINVAL;
6995                         goto out;
6996                 }
6997         }
6998
6999         if (unlikely(vcpu->arch.complete_userspace_io)) {
7000                 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
7001                 vcpu->arch.complete_userspace_io = NULL;
7002                 r = cui(vcpu);
7003                 if (r <= 0)
7004                         goto out;
7005         } else
7006                 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
7007
7008         r = vcpu_run(vcpu);
7009
7010 out:
7011         post_kvm_run_save(vcpu);
7012         if (vcpu->sigset_active)
7013                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
7014
7015         return r;
7016 }
7017
7018 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7019 {
7020         if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
7021                 /*
7022                  * We are here if userspace calls get_regs() in the middle of
7023                  * instruction emulation. Registers state needs to be copied
7024                  * back from emulation context to vcpu. Userspace shouldn't do
7025                  * that usually, but some bad designed PV devices (vmware
7026                  * backdoor interface) need this to work
7027                  */
7028                 emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
7029                 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7030         }
7031         regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
7032         regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
7033         regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
7034         regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
7035         regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
7036         regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
7037         regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
7038         regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
7039 #ifdef CONFIG_X86_64
7040         regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
7041         regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
7042         regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
7043         regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
7044         regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
7045         regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
7046         regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
7047         regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
7048 #endif
7049
7050         regs->rip = kvm_rip_read(vcpu);
7051         regs->rflags = kvm_get_rflags(vcpu);
7052
7053         return 0;
7054 }
7055
7056 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
7057 {
7058         vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
7059         vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7060
7061         kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
7062         kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
7063         kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
7064         kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
7065         kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
7066         kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
7067         kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
7068         kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
7069 #ifdef CONFIG_X86_64
7070         kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
7071         kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
7072         kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
7073         kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
7074         kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
7075         kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
7076         kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
7077         kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
7078 #endif
7079
7080         kvm_rip_write(vcpu, regs->rip);
7081         kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
7082
7083         vcpu->arch.exception.pending = false;
7084
7085         kvm_make_request(KVM_REQ_EVENT, vcpu);
7086
7087         return 0;
7088 }
7089
7090 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
7091 {
7092         struct kvm_segment cs;
7093
7094         kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7095         *db = cs.db;
7096         *l = cs.l;
7097 }
7098 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
7099
7100 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
7101                                   struct kvm_sregs *sregs)
7102 {
7103         struct desc_ptr dt;
7104
7105         kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7106         kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7107         kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7108         kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7109         kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7110         kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7111
7112         kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7113         kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7114
7115         kvm_x86_ops->get_idt(vcpu, &dt);
7116         sregs->idt.limit = dt.size;
7117         sregs->idt.base = dt.address;
7118         kvm_x86_ops->get_gdt(vcpu, &dt);
7119         sregs->gdt.limit = dt.size;
7120         sregs->gdt.base = dt.address;
7121
7122         sregs->cr0 = kvm_read_cr0(vcpu);
7123         sregs->cr2 = vcpu->arch.cr2;
7124         sregs->cr3 = kvm_read_cr3(vcpu);
7125         sregs->cr4 = kvm_read_cr4(vcpu);
7126         sregs->cr8 = kvm_get_cr8(vcpu);
7127         sregs->efer = vcpu->arch.efer;
7128         sregs->apic_base = kvm_get_apic_base(vcpu);
7129
7130         memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
7131
7132         if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
7133                 set_bit(vcpu->arch.interrupt.nr,
7134                         (unsigned long *)sregs->interrupt_bitmap);
7135
7136         return 0;
7137 }
7138
7139 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
7140                                     struct kvm_mp_state *mp_state)
7141 {
7142         kvm_apic_accept_events(vcpu);
7143         if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
7144                                         vcpu->arch.pv.pv_unhalted)
7145                 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
7146         else
7147                 mp_state->mp_state = vcpu->arch.mp_state;
7148
7149         return 0;
7150 }
7151
7152 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
7153                                     struct kvm_mp_state *mp_state)
7154 {
7155         if (!kvm_vcpu_has_lapic(vcpu) &&
7156             mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
7157                 return -EINVAL;
7158
7159         /* INITs are latched while in SMM */
7160         if ((is_smm(vcpu) || vcpu->arch.smi_pending) &&
7161             (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
7162              mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
7163                 return -EINVAL;
7164
7165         if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
7166                 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
7167                 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
7168         } else
7169                 vcpu->arch.mp_state = mp_state->mp_state;
7170         kvm_make_request(KVM_REQ_EVENT, vcpu);
7171         return 0;
7172 }
7173
7174 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
7175                     int reason, bool has_error_code, u32 error_code)
7176 {
7177         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
7178         int ret;
7179
7180         init_emulate_ctxt(vcpu);
7181
7182         ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
7183                                    has_error_code, error_code);
7184
7185         if (ret)
7186                 return EMULATE_FAIL;
7187
7188         kvm_rip_write(vcpu, ctxt->eip);
7189         kvm_set_rflags(vcpu, ctxt->eflags);
7190         kvm_make_request(KVM_REQ_EVENT, vcpu);
7191         return EMULATE_DONE;
7192 }
7193 EXPORT_SYMBOL_GPL(kvm_task_switch);
7194
7195 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
7196                                   struct kvm_sregs *sregs)
7197 {
7198         struct msr_data apic_base_msr;
7199         int mmu_reset_needed = 0;
7200         int pending_vec, max_bits, idx;
7201         struct desc_ptr dt;
7202
7203         if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
7204                 return -EINVAL;
7205
7206         dt.size = sregs->idt.limit;
7207         dt.address = sregs->idt.base;
7208         kvm_x86_ops->set_idt(vcpu, &dt);
7209         dt.size = sregs->gdt.limit;
7210         dt.address = sregs->gdt.base;
7211         kvm_x86_ops->set_gdt(vcpu, &dt);
7212
7213         vcpu->arch.cr2 = sregs->cr2;
7214         mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
7215         vcpu->arch.cr3 = sregs->cr3;
7216         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
7217
7218         kvm_set_cr8(vcpu, sregs->cr8);
7219
7220         mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
7221         kvm_x86_ops->set_efer(vcpu, sregs->efer);
7222         apic_base_msr.data = sregs->apic_base;
7223         apic_base_msr.host_initiated = true;
7224         kvm_set_apic_base(vcpu, &apic_base_msr);
7225
7226         mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
7227         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
7228         vcpu->arch.cr0 = sregs->cr0;
7229
7230         mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
7231         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
7232         if (sregs->cr4 & X86_CR4_OSXSAVE)
7233                 kvm_update_cpuid(vcpu);
7234
7235         idx = srcu_read_lock(&vcpu->kvm->srcu);
7236         if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu)) {
7237                 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
7238                 mmu_reset_needed = 1;
7239         }
7240         srcu_read_unlock(&vcpu->kvm->srcu, idx);
7241
7242         if (mmu_reset_needed)
7243                 kvm_mmu_reset_context(vcpu);
7244
7245         max_bits = KVM_NR_INTERRUPTS;
7246         pending_vec = find_first_bit(
7247                 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
7248         if (pending_vec < max_bits) {
7249                 kvm_queue_interrupt(vcpu, pending_vec, false);
7250                 pr_debug("Set back pending irq %d\n", pending_vec);
7251         }
7252
7253         kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
7254         kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
7255         kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
7256         kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
7257         kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
7258         kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
7259
7260         kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
7261         kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
7262
7263         update_cr8_intercept(vcpu);
7264
7265         /* Older userspace won't unhalt the vcpu on reset. */
7266         if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
7267             sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
7268             !is_protmode(vcpu))
7269                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7270
7271         kvm_make_request(KVM_REQ_EVENT, vcpu);
7272
7273         return 0;
7274 }
7275
7276 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
7277                                         struct kvm_guest_debug *dbg)
7278 {
7279         unsigned long rflags;
7280         int i, r;
7281
7282         if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
7283                 r = -EBUSY;
7284                 if (vcpu->arch.exception.pending)
7285                         goto out;
7286                 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
7287                         kvm_queue_exception(vcpu, DB_VECTOR);
7288                 else
7289                         kvm_queue_exception(vcpu, BP_VECTOR);
7290         }
7291
7292         /*
7293          * Read rflags as long as potentially injected trace flags are still
7294          * filtered out.
7295          */
7296         rflags = kvm_get_rflags(vcpu);
7297
7298         vcpu->guest_debug = dbg->control;
7299         if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
7300                 vcpu->guest_debug = 0;
7301
7302         if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
7303                 for (i = 0; i < KVM_NR_DB_REGS; ++i)
7304                         vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
7305                 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
7306         } else {
7307                 for (i = 0; i < KVM_NR_DB_REGS; i++)
7308                         vcpu->arch.eff_db[i] = vcpu->arch.db[i];
7309         }
7310         kvm_update_dr7(vcpu);
7311
7312         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7313                 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
7314                         get_segment_base(vcpu, VCPU_SREG_CS);
7315
7316         /*
7317          * Trigger an rflags update that will inject or remove the trace
7318          * flags.
7319          */
7320         kvm_set_rflags(vcpu, rflags);
7321
7322         kvm_x86_ops->update_bp_intercept(vcpu);
7323
7324         r = 0;
7325
7326 out:
7327
7328         return r;
7329 }
7330
7331 /*
7332  * Translate a guest virtual address to a guest physical address.
7333  */
7334 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
7335                                     struct kvm_translation *tr)
7336 {
7337         unsigned long vaddr = tr->linear_address;
7338         gpa_t gpa;
7339         int idx;
7340
7341         idx = srcu_read_lock(&vcpu->kvm->srcu);
7342         gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
7343         srcu_read_unlock(&vcpu->kvm->srcu, idx);
7344         tr->physical_address = gpa;
7345         tr->valid = gpa != UNMAPPED_GVA;
7346         tr->writeable = 1;
7347         tr->usermode = 0;
7348
7349         return 0;
7350 }
7351
7352 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7353 {
7354         struct fxregs_state *fxsave =
7355                         &vcpu->arch.guest_fpu.state.fxsave;
7356
7357         memcpy(fpu->fpr, fxsave->st_space, 128);
7358         fpu->fcw = fxsave->cwd;
7359         fpu->fsw = fxsave->swd;
7360         fpu->ftwx = fxsave->twd;
7361         fpu->last_opcode = fxsave->fop;
7362         fpu->last_ip = fxsave->rip;
7363         fpu->last_dp = fxsave->rdp;
7364         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
7365
7366         return 0;
7367 }
7368
7369 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
7370 {
7371         struct fxregs_state *fxsave =
7372                         &vcpu->arch.guest_fpu.state.fxsave;
7373
7374         memcpy(fxsave->st_space, fpu->fpr, 128);
7375         fxsave->cwd = fpu->fcw;
7376         fxsave->swd = fpu->fsw;
7377         fxsave->twd = fpu->ftwx;
7378         fxsave->fop = fpu->last_opcode;
7379         fxsave->rip = fpu->last_ip;
7380         fxsave->rdp = fpu->last_dp;
7381         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
7382
7383         return 0;
7384 }
7385
7386 static void fx_init(struct kvm_vcpu *vcpu)
7387 {
7388         fpstate_init(&vcpu->arch.guest_fpu.state);
7389         if (cpu_has_xsaves)
7390                 vcpu->arch.guest_fpu.state.xsave.header.xcomp_bv =
7391                         host_xcr0 | XSTATE_COMPACTION_ENABLED;
7392
7393         /*
7394          * Ensure guest xcr0 is valid for loading
7395          */
7396         vcpu->arch.xcr0 = XFEATURE_MASK_FP;
7397
7398         vcpu->arch.cr0 |= X86_CR0_ET;
7399 }
7400
7401 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
7402 {
7403         if (vcpu->guest_fpu_loaded)
7404                 return;
7405
7406         /*
7407          * Restore all possible states in the guest,
7408          * and assume host would use all available bits.
7409          * Guest xcr0 would be loaded later.
7410          */
7411         vcpu->guest_fpu_loaded = 1;
7412         __kernel_fpu_begin();
7413         __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu.state);
7414         trace_kvm_fpu(1);
7415 }
7416
7417 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
7418 {
7419         if (!vcpu->guest_fpu_loaded) {
7420                 vcpu->fpu_counter = 0;
7421                 return;
7422         }
7423
7424         vcpu->guest_fpu_loaded = 0;
7425         copy_fpregs_to_fpstate(&vcpu->arch.guest_fpu);
7426         __kernel_fpu_end();
7427         ++vcpu->stat.fpu_reload;
7428         trace_kvm_fpu(0);
7429 }
7430
7431 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
7432 {
7433         void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
7434
7435         kvmclock_reset(vcpu);
7436
7437         kvm_x86_ops->vcpu_free(vcpu);
7438         free_cpumask_var(wbinvd_dirty_mask);
7439 }
7440
7441 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
7442                                                 unsigned int id)
7443 {
7444         struct kvm_vcpu *vcpu;
7445
7446         if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
7447                 printk_once(KERN_WARNING
7448                 "kvm: SMP vm created on host with unstable TSC; "
7449                 "guest TSC will not be reliable\n");
7450
7451         vcpu = kvm_x86_ops->vcpu_create(kvm, id);
7452
7453         return vcpu;
7454 }
7455
7456 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
7457 {
7458         int r;
7459
7460         vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
7461         kvm_vcpu_mtrr_init(vcpu);
7462         r = vcpu_load(vcpu);
7463         if (r)
7464                 return r;
7465         kvm_vcpu_reset(vcpu, false);
7466         kvm_mmu_setup(vcpu);
7467         vcpu_put(vcpu);
7468         return r;
7469 }
7470
7471 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
7472 {
7473         struct msr_data msr;
7474         struct kvm *kvm = vcpu->kvm;
7475
7476         if (vcpu_load(vcpu))
7477                 return;
7478         msr.data = 0x0;
7479         msr.index = MSR_IA32_TSC;
7480         msr.host_initiated = true;
7481         kvm_write_tsc(vcpu, &msr);
7482         vcpu_put(vcpu);
7483
7484         if (!kvmclock_periodic_sync)
7485                 return;
7486
7487         schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
7488                                         KVMCLOCK_SYNC_PERIOD);
7489 }
7490
7491 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
7492 {
7493         int r;
7494         vcpu->arch.apf.msr_val = 0;
7495
7496         r = vcpu_load(vcpu);
7497         BUG_ON(r);
7498         kvm_mmu_unload(vcpu);
7499         vcpu_put(vcpu);
7500
7501         kvm_arch_vcpu_free(vcpu);
7502 }
7503
7504 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
7505 {
7506         vcpu->arch.hflags = 0;
7507
7508         atomic_set(&vcpu->arch.nmi_queued, 0);
7509         vcpu->arch.nmi_pending = 0;
7510         vcpu->arch.nmi_injected = false;
7511         kvm_clear_interrupt_queue(vcpu);
7512         kvm_clear_exception_queue(vcpu);
7513
7514         memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
7515         kvm_update_dr0123(vcpu);
7516         vcpu->arch.dr6 = DR6_INIT;
7517         kvm_update_dr6(vcpu);
7518         vcpu->arch.dr7 = DR7_FIXED_1;
7519         kvm_update_dr7(vcpu);
7520
7521         vcpu->arch.cr2 = 0;
7522
7523         kvm_make_request(KVM_REQ_EVENT, vcpu);
7524         vcpu->arch.apf.msr_val = 0;
7525         vcpu->arch.st.msr_val = 0;
7526
7527         kvmclock_reset(vcpu);
7528
7529         kvm_clear_async_pf_completion_queue(vcpu);
7530         kvm_async_pf_hash_reset(vcpu);
7531         vcpu->arch.apf.halted = false;
7532
7533         if (!init_event) {
7534                 kvm_pmu_reset(vcpu);
7535                 vcpu->arch.smbase = 0x30000;
7536         }
7537
7538         memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
7539         vcpu->arch.regs_avail = ~0;
7540         vcpu->arch.regs_dirty = ~0;
7541
7542         kvm_x86_ops->vcpu_reset(vcpu, init_event);
7543 }
7544
7545 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
7546 {
7547         struct kvm_segment cs;
7548
7549         kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
7550         cs.selector = vector << 8;
7551         cs.base = vector << 12;
7552         kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
7553         kvm_rip_write(vcpu, 0);
7554 }
7555
7556 int kvm_arch_hardware_enable(void)
7557 {
7558         struct kvm *kvm;
7559         struct kvm_vcpu *vcpu;
7560         int i;
7561         int ret;
7562         u64 local_tsc;
7563         u64 max_tsc = 0;
7564         bool stable, backwards_tsc = false;
7565
7566         kvm_shared_msr_cpu_online();
7567         ret = kvm_x86_ops->hardware_enable();
7568         if (ret != 0)
7569                 return ret;
7570
7571         local_tsc = rdtsc();
7572         stable = !check_tsc_unstable();
7573         list_for_each_entry(kvm, &vm_list, vm_list) {
7574                 kvm_for_each_vcpu(i, vcpu, kvm) {
7575                         if (!stable && vcpu->cpu == smp_processor_id())
7576                                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7577                         if (stable && vcpu->arch.last_host_tsc > local_tsc) {
7578                                 backwards_tsc = true;
7579                                 if (vcpu->arch.last_host_tsc > max_tsc)
7580                                         max_tsc = vcpu->arch.last_host_tsc;
7581                         }
7582                 }
7583         }
7584
7585         /*
7586          * Sometimes, even reliable TSCs go backwards.  This happens on
7587          * platforms that reset TSC during suspend or hibernate actions, but
7588          * maintain synchronization.  We must compensate.  Fortunately, we can
7589          * detect that condition here, which happens early in CPU bringup,
7590          * before any KVM threads can be running.  Unfortunately, we can't
7591          * bring the TSCs fully up to date with real time, as we aren't yet far
7592          * enough into CPU bringup that we know how much real time has actually
7593          * elapsed; our helper function, get_kernel_ns() will be using boot
7594          * variables that haven't been updated yet.
7595          *
7596          * So we simply find the maximum observed TSC above, then record the
7597          * adjustment to TSC in each VCPU.  When the VCPU later gets loaded,
7598          * the adjustment will be applied.  Note that we accumulate
7599          * adjustments, in case multiple suspend cycles happen before some VCPU
7600          * gets a chance to run again.  In the event that no KVM threads get a
7601          * chance to run, we will miss the entire elapsed period, as we'll have
7602          * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
7603          * loose cycle time.  This isn't too big a deal, since the loss will be
7604          * uniform across all VCPUs (not to mention the scenario is extremely
7605          * unlikely). It is possible that a second hibernate recovery happens
7606          * much faster than a first, causing the observed TSC here to be
7607          * smaller; this would require additional padding adjustment, which is
7608          * why we set last_host_tsc to the local tsc observed here.
7609          *
7610          * N.B. - this code below runs only on platforms with reliable TSC,
7611          * as that is the only way backwards_tsc is set above.  Also note
7612          * that this runs for ALL vcpus, which is not a bug; all VCPUs should
7613          * have the same delta_cyc adjustment applied if backwards_tsc
7614          * is detected.  Note further, this adjustment is only done once,
7615          * as we reset last_host_tsc on all VCPUs to stop this from being
7616          * called multiple times (one for each physical CPU bringup).
7617          *
7618          * Platforms with unreliable TSCs don't have to deal with this, they
7619          * will be compensated by the logic in vcpu_load, which sets the TSC to
7620          * catchup mode.  This will catchup all VCPUs to real time, but cannot
7621          * guarantee that they stay in perfect synchronization.
7622          */
7623         if (backwards_tsc) {
7624                 u64 delta_cyc = max_tsc - local_tsc;
7625                 backwards_tsc_observed = true;
7626                 list_for_each_entry(kvm, &vm_list, vm_list) {
7627                         kvm_for_each_vcpu(i, vcpu, kvm) {
7628                                 vcpu->arch.tsc_offset_adjustment += delta_cyc;
7629                                 vcpu->arch.last_host_tsc = local_tsc;
7630                                 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7631                         }
7632
7633                         /*
7634                          * We have to disable TSC offset matching.. if you were
7635                          * booting a VM while issuing an S4 host suspend....
7636                          * you may have some problem.  Solving this issue is
7637                          * left as an exercise to the reader.
7638                          */
7639                         kvm->arch.last_tsc_nsec = 0;
7640                         kvm->arch.last_tsc_write = 0;
7641                 }
7642
7643         }
7644         return 0;
7645 }
7646
7647 void kvm_arch_hardware_disable(void)
7648 {
7649         kvm_x86_ops->hardware_disable();
7650         drop_user_return_notifiers();
7651 }
7652
7653 int kvm_arch_hardware_setup(void)
7654 {
7655         int r;
7656
7657         r = kvm_x86_ops->hardware_setup();
7658         if (r != 0)
7659                 return r;
7660
7661         if (kvm_has_tsc_control) {
7662                 /*
7663                  * Make sure the user can only configure tsc_khz values that
7664                  * fit into a signed integer.
7665                  * A min value is not calculated needed because it will always
7666                  * be 1 on all machines.
7667                  */
7668                 u64 max = min(0x7fffffffULL,
7669                               __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
7670                 kvm_max_guest_tsc_khz = max;
7671
7672                 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
7673         }
7674
7675         kvm_init_msr_list();
7676         return 0;
7677 }
7678
7679 void kvm_arch_hardware_unsetup(void)
7680 {
7681         kvm_x86_ops->hardware_unsetup();
7682 }
7683
7684 void kvm_arch_check_processor_compat(void *rtn)
7685 {
7686         kvm_x86_ops->check_processor_compatibility(rtn);
7687 }
7688
7689 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
7690 {
7691         return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
7692 }
7693 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
7694
7695 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
7696 {
7697         return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
7698 }
7699
7700 bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu)
7701 {
7702         return irqchip_in_kernel(vcpu->kvm) == lapic_in_kernel(vcpu);
7703 }
7704
7705 struct static_key kvm_no_apic_vcpu __read_mostly;
7706
7707 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
7708 {
7709         struct page *page;
7710         struct kvm *kvm;
7711         int r;
7712
7713         BUG_ON(vcpu->kvm == NULL);
7714         kvm = vcpu->kvm;
7715
7716         vcpu->arch.pv.pv_unhalted = false;
7717         vcpu->arch.emulate_ctxt.ops = &emulate_ops;
7718         if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_reset_bsp(vcpu))
7719                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
7720         else
7721                 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
7722
7723         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
7724         if (!page) {
7725                 r = -ENOMEM;
7726                 goto fail;
7727         }
7728         vcpu->arch.pio_data = page_address(page);
7729
7730         kvm_set_tsc_khz(vcpu, max_tsc_khz);
7731
7732         r = kvm_mmu_create(vcpu);
7733         if (r < 0)
7734                 goto fail_free_pio_data;
7735
7736         if (irqchip_in_kernel(kvm)) {
7737                 r = kvm_create_lapic(vcpu);
7738                 if (r < 0)
7739                         goto fail_mmu_destroy;
7740         } else
7741                 static_key_slow_inc(&kvm_no_apic_vcpu);
7742
7743         vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
7744                                        GFP_KERNEL);
7745         if (!vcpu->arch.mce_banks) {
7746                 r = -ENOMEM;
7747                 goto fail_free_lapic;
7748         }
7749         vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
7750
7751         if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
7752                 r = -ENOMEM;
7753                 goto fail_free_mce_banks;
7754         }
7755
7756         fx_init(vcpu);
7757
7758         vcpu->arch.ia32_tsc_adjust_msr = 0x0;
7759         vcpu->arch.pv_time_enabled = false;
7760
7761         vcpu->arch.guest_supported_xcr0 = 0;
7762         vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
7763
7764         vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
7765
7766         vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
7767
7768         kvm_async_pf_hash_reset(vcpu);
7769         kvm_pmu_init(vcpu);
7770
7771         vcpu->arch.pending_external_vector = -1;
7772
7773         return 0;
7774
7775 fail_free_mce_banks:
7776         kfree(vcpu->arch.mce_banks);
7777 fail_free_lapic:
7778         kvm_free_lapic(vcpu);
7779 fail_mmu_destroy:
7780         kvm_mmu_destroy(vcpu);
7781 fail_free_pio_data:
7782         free_page((unsigned long)vcpu->arch.pio_data);
7783 fail:
7784         return r;
7785 }
7786
7787 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
7788 {
7789         int idx;
7790
7791         kvm_pmu_destroy(vcpu);
7792         kfree(vcpu->arch.mce_banks);
7793         kvm_free_lapic(vcpu);
7794         idx = srcu_read_lock(&vcpu->kvm->srcu);
7795         kvm_mmu_destroy(vcpu);
7796         srcu_read_unlock(&vcpu->kvm->srcu, idx);
7797         free_page((unsigned long)vcpu->arch.pio_data);
7798         if (!lapic_in_kernel(vcpu))
7799                 static_key_slow_dec(&kvm_no_apic_vcpu);
7800 }
7801
7802 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
7803 {
7804         kvm_x86_ops->sched_in(vcpu, cpu);
7805 }
7806
7807 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
7808 {
7809         if (type)
7810                 return -EINVAL;
7811
7812         INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
7813         INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
7814         INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
7815         INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
7816         atomic_set(&kvm->arch.noncoherent_dma_count, 0);
7817
7818         /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
7819         set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
7820         /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
7821         set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
7822                 &kvm->arch.irq_sources_bitmap);
7823
7824         raw_spin_lock_init(&kvm->arch.tsc_write_lock);
7825         mutex_init(&kvm->arch.apic_map_lock);
7826         spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
7827
7828         pvclock_update_vm_gtod_copy(kvm);
7829
7830         INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
7831         INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
7832
7833         return 0;
7834 }
7835
7836 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
7837 {
7838         int r;
7839         r = vcpu_load(vcpu);
7840         BUG_ON(r);
7841         kvm_mmu_unload(vcpu);
7842         vcpu_put(vcpu);
7843 }
7844
7845 static void kvm_free_vcpus(struct kvm *kvm)
7846 {
7847         unsigned int i;
7848         struct kvm_vcpu *vcpu;
7849
7850         /*
7851          * Unpin any mmu pages first.
7852          */
7853         kvm_for_each_vcpu(i, vcpu, kvm) {
7854                 kvm_clear_async_pf_completion_queue(vcpu);
7855                 kvm_unload_vcpu_mmu(vcpu);
7856         }
7857         kvm_for_each_vcpu(i, vcpu, kvm)
7858                 kvm_arch_vcpu_free(vcpu);
7859
7860         mutex_lock(&kvm->lock);
7861         for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
7862                 kvm->vcpus[i] = NULL;
7863
7864         atomic_set(&kvm->online_vcpus, 0);
7865         mutex_unlock(&kvm->lock);
7866 }
7867
7868 void kvm_arch_sync_events(struct kvm *kvm)
7869 {
7870         cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
7871         cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
7872         kvm_free_all_assigned_devices(kvm);
7873         kvm_free_pit(kvm);
7874 }
7875
7876 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
7877 {
7878         int i, r;
7879         unsigned long hva;
7880         struct kvm_memslots *slots = kvm_memslots(kvm);
7881         struct kvm_memory_slot *slot, old;
7882
7883         /* Called with kvm->slots_lock held.  */
7884         if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
7885                 return -EINVAL;
7886
7887         slot = id_to_memslot(slots, id);
7888         if (size) {
7889                 if (slot->npages)
7890                         return -EEXIST;
7891
7892                 /*
7893                  * MAP_SHARED to prevent internal slot pages from being moved
7894                  * by fork()/COW.
7895                  */
7896                 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
7897                               MAP_SHARED | MAP_ANONYMOUS, 0);
7898                 if (IS_ERR((void *)hva))
7899                         return PTR_ERR((void *)hva);
7900         } else {
7901                 if (!slot->npages)
7902                         return 0;
7903
7904                 hva = 0;
7905         }
7906
7907         old = *slot;
7908         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
7909                 struct kvm_userspace_memory_region m;
7910
7911                 m.slot = id | (i << 16);
7912                 m.flags = 0;
7913                 m.guest_phys_addr = gpa;
7914                 m.userspace_addr = hva;
7915                 m.memory_size = size;
7916                 r = __kvm_set_memory_region(kvm, &m);
7917                 if (r < 0)
7918                         return r;
7919         }
7920
7921         if (!size) {
7922                 r = vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
7923                 WARN_ON(r < 0);
7924         }
7925
7926         return 0;
7927 }
7928 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
7929
7930 int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
7931 {
7932         int r;
7933
7934         mutex_lock(&kvm->slots_lock);
7935         r = __x86_set_memory_region(kvm, id, gpa, size);
7936         mutex_unlock(&kvm->slots_lock);
7937
7938         return r;
7939 }
7940 EXPORT_SYMBOL_GPL(x86_set_memory_region);
7941
7942 void kvm_arch_destroy_vm(struct kvm *kvm)
7943 {
7944         if (current->mm == kvm->mm) {
7945                 /*
7946                  * Free memory regions allocated on behalf of userspace,
7947                  * unless the the memory map has changed due to process exit
7948                  * or fd copying.
7949                  */
7950                 x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
7951                 x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
7952                 x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
7953         }
7954         kvm_iommu_unmap_guest(kvm);
7955         kfree(kvm->arch.vpic);
7956         kfree(kvm->arch.vioapic);
7957         kvm_free_vcpus(kvm);
7958         kfree(rcu_dereference_check(kvm->arch.apic_map, 1));
7959 }
7960
7961 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
7962                            struct kvm_memory_slot *dont)
7963 {
7964         int i;
7965
7966         for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7967                 if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
7968                         kvfree(free->arch.rmap[i]);
7969                         free->arch.rmap[i] = NULL;
7970                 }
7971                 if (i == 0)
7972                         continue;
7973
7974                 if (!dont || free->arch.lpage_info[i - 1] !=
7975                              dont->arch.lpage_info[i - 1]) {
7976                         kvfree(free->arch.lpage_info[i - 1]);
7977                         free->arch.lpage_info[i - 1] = NULL;
7978                 }
7979         }
7980 }
7981
7982 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
7983                             unsigned long npages)
7984 {
7985         int i;
7986
7987         for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
7988                 unsigned long ugfn;
7989                 int lpages;
7990                 int level = i + 1;
7991
7992                 lpages = gfn_to_index(slot->base_gfn + npages - 1,
7993                                       slot->base_gfn, level) + 1;
7994
7995                 slot->arch.rmap[i] =
7996                         kvm_kvzalloc(lpages * sizeof(*slot->arch.rmap[i]));
7997                 if (!slot->arch.rmap[i])
7998                         goto out_free;
7999                 if (i == 0)
8000                         continue;
8001
8002                 slot->arch.lpage_info[i - 1] = kvm_kvzalloc(lpages *
8003                                         sizeof(*slot->arch.lpage_info[i - 1]));
8004                 if (!slot->arch.lpage_info[i - 1])
8005                         goto out_free;
8006
8007                 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
8008                         slot->arch.lpage_info[i - 1][0].write_count = 1;
8009                 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
8010                         slot->arch.lpage_info[i - 1][lpages - 1].write_count = 1;
8011                 ugfn = slot->userspace_addr >> PAGE_SHIFT;
8012                 /*
8013                  * If the gfn and userspace address are not aligned wrt each
8014                  * other, or if explicitly asked to, disable large page
8015                  * support for this slot
8016                  */
8017                 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
8018                     !kvm_largepages_enabled()) {
8019                         unsigned long j;
8020
8021                         for (j = 0; j < lpages; ++j)
8022                                 slot->arch.lpage_info[i - 1][j].write_count = 1;
8023                 }
8024         }
8025
8026         return 0;
8027
8028 out_free:
8029         for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
8030                 kvfree(slot->arch.rmap[i]);
8031                 slot->arch.rmap[i] = NULL;
8032                 if (i == 0)
8033                         continue;
8034
8035                 kvfree(slot->arch.lpage_info[i - 1]);
8036                 slot->arch.lpage_info[i - 1] = NULL;
8037         }
8038         return -ENOMEM;
8039 }
8040
8041 void kvm_arch_memslots_updated(struct kvm *kvm, struct kvm_memslots *slots)
8042 {
8043         /*
8044          * memslots->generation has been incremented.
8045          * mmio generation may have reached its maximum value.
8046          */
8047         kvm_mmu_invalidate_mmio_sptes(kvm, slots);
8048 }
8049
8050 int kvm_arch_prepare_memory_region(struct kvm *kvm,
8051                                 struct kvm_memory_slot *memslot,
8052                                 const struct kvm_userspace_memory_region *mem,
8053                                 enum kvm_mr_change change)
8054 {
8055         return 0;
8056 }
8057
8058 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
8059                                      struct kvm_memory_slot *new)
8060 {
8061         /* Still write protect RO slot */
8062         if (new->flags & KVM_MEM_READONLY) {
8063                 kvm_mmu_slot_remove_write_access(kvm, new);
8064                 return;
8065         }
8066
8067         /*
8068          * Call kvm_x86_ops dirty logging hooks when they are valid.
8069          *
8070          * kvm_x86_ops->slot_disable_log_dirty is called when:
8071          *
8072          *  - KVM_MR_CREATE with dirty logging is disabled
8073          *  - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
8074          *
8075          * The reason is, in case of PML, we need to set D-bit for any slots
8076          * with dirty logging disabled in order to eliminate unnecessary GPA
8077          * logging in PML buffer (and potential PML buffer full VMEXT). This
8078          * guarantees leaving PML enabled during guest's lifetime won't have
8079          * any additonal overhead from PML when guest is running with dirty
8080          * logging disabled for memory slots.
8081          *
8082          * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
8083          * to dirty logging mode.
8084          *
8085          * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
8086          *
8087          * In case of write protect:
8088          *
8089          * Write protect all pages for dirty logging.
8090          *
8091          * All the sptes including the large sptes which point to this
8092          * slot are set to readonly. We can not create any new large
8093          * spte on this slot until the end of the logging.
8094          *
8095          * See the comments in fast_page_fault().
8096          */
8097         if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
8098                 if (kvm_x86_ops->slot_enable_log_dirty)
8099                         kvm_x86_ops->slot_enable_log_dirty(kvm, new);
8100                 else
8101                         kvm_mmu_slot_remove_write_access(kvm, new);
8102         } else {
8103                 if (kvm_x86_ops->slot_disable_log_dirty)
8104                         kvm_x86_ops->slot_disable_log_dirty(kvm, new);
8105         }
8106 }
8107
8108 void kvm_arch_commit_memory_region(struct kvm *kvm,
8109                                 const struct kvm_userspace_memory_region *mem,
8110                                 const struct kvm_memory_slot *old,
8111                                 const struct kvm_memory_slot *new,
8112                                 enum kvm_mr_change change)
8113 {
8114         int nr_mmu_pages = 0;
8115
8116         if (!kvm->arch.n_requested_mmu_pages)
8117                 nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
8118
8119         if (nr_mmu_pages)
8120                 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
8121
8122         /*
8123          * Dirty logging tracks sptes in 4k granularity, meaning that large
8124          * sptes have to be split.  If live migration is successful, the guest
8125          * in the source machine will be destroyed and large sptes will be
8126          * created in the destination. However, if the guest continues to run
8127          * in the source machine (for example if live migration fails), small
8128          * sptes will remain around and cause bad performance.
8129          *
8130          * Scan sptes if dirty logging has been stopped, dropping those
8131          * which can be collapsed into a single large-page spte.  Later
8132          * page faults will create the large-page sptes.
8133          */
8134         if ((change != KVM_MR_DELETE) &&
8135                 (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
8136                 !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
8137                 kvm_mmu_zap_collapsible_sptes(kvm, new);
8138
8139         /*
8140          * Set up write protection and/or dirty logging for the new slot.
8141          *
8142          * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
8143          * been zapped so no dirty logging staff is needed for old slot. For
8144          * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
8145          * new and it's also covered when dealing with the new slot.
8146          *
8147          * FIXME: const-ify all uses of struct kvm_memory_slot.
8148          */
8149         if (change != KVM_MR_DELETE)
8150                 kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
8151 }
8152
8153 void kvm_arch_flush_shadow_all(struct kvm *kvm)
8154 {
8155         kvm_mmu_invalidate_zap_all_pages(kvm);
8156 }
8157
8158 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
8159                                    struct kvm_memory_slot *slot)
8160 {
8161         kvm_mmu_invalidate_zap_all_pages(kvm);
8162 }
8163
8164 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
8165 {
8166         if (!list_empty_careful(&vcpu->async_pf.done))
8167                 return true;
8168
8169         if (kvm_apic_has_events(vcpu))
8170                 return true;
8171
8172         if (vcpu->arch.pv.pv_unhalted)
8173                 return true;
8174
8175         if (atomic_read(&vcpu->arch.nmi_queued))
8176                 return true;
8177
8178         if (test_bit(KVM_REQ_SMI, &vcpu->requests))
8179                 return true;
8180
8181         if (kvm_arch_interrupt_allowed(vcpu) &&
8182             kvm_cpu_has_interrupt(vcpu))
8183                 return true;
8184
8185         return false;
8186 }
8187
8188 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
8189 {
8190         if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
8191                 kvm_x86_ops->check_nested_events(vcpu, false);
8192
8193         return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
8194 }
8195
8196 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
8197 {
8198         return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
8199 }
8200
8201 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
8202 {
8203         return kvm_x86_ops->interrupt_allowed(vcpu);
8204 }
8205
8206 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
8207 {
8208         if (is_64_bit_mode(vcpu))
8209                 return kvm_rip_read(vcpu);
8210         return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
8211                      kvm_rip_read(vcpu));
8212 }
8213 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
8214
8215 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
8216 {
8217         return kvm_get_linear_rip(vcpu) == linear_rip;
8218 }
8219 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
8220
8221 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
8222 {
8223         unsigned long rflags;
8224
8225         rflags = kvm_x86_ops->get_rflags(vcpu);
8226         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
8227                 rflags &= ~X86_EFLAGS_TF;
8228         return rflags;
8229 }
8230 EXPORT_SYMBOL_GPL(kvm_get_rflags);
8231
8232 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8233 {
8234         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
8235             kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
8236                 rflags |= X86_EFLAGS_TF;
8237         kvm_x86_ops->set_rflags(vcpu, rflags);
8238 }
8239
8240 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
8241 {
8242         __kvm_set_rflags(vcpu, rflags);
8243         kvm_make_request(KVM_REQ_EVENT, vcpu);
8244 }
8245 EXPORT_SYMBOL_GPL(kvm_set_rflags);
8246
8247 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
8248 {
8249         int r;
8250
8251         if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
8252               work->wakeup_all)
8253                 return;
8254
8255         r = kvm_mmu_reload(vcpu);
8256         if (unlikely(r))
8257                 return;
8258
8259         if (!vcpu->arch.mmu.direct_map &&
8260               work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
8261                 return;
8262
8263         vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
8264 }
8265
8266 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
8267 {
8268         return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
8269 }
8270
8271 static inline u32 kvm_async_pf_next_probe(u32 key)
8272 {
8273         return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
8274 }
8275
8276 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8277 {
8278         u32 key = kvm_async_pf_hash_fn(gfn);
8279
8280         while (vcpu->arch.apf.gfns[key] != ~0)
8281                 key = kvm_async_pf_next_probe(key);
8282
8283         vcpu->arch.apf.gfns[key] = gfn;
8284 }
8285
8286 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
8287 {
8288         int i;
8289         u32 key = kvm_async_pf_hash_fn(gfn);
8290
8291         for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
8292                      (vcpu->arch.apf.gfns[key] != gfn &&
8293                       vcpu->arch.apf.gfns[key] != ~0); i++)
8294                 key = kvm_async_pf_next_probe(key);
8295
8296         return key;
8297 }
8298
8299 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8300 {
8301         return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
8302 }
8303
8304 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
8305 {
8306         u32 i, j, k;
8307
8308         i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
8309         while (true) {
8310                 vcpu->arch.apf.gfns[i] = ~0;
8311                 do {
8312                         j = kvm_async_pf_next_probe(j);
8313                         if (vcpu->arch.apf.gfns[j] == ~0)
8314                                 return;
8315                         k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
8316                         /*
8317                          * k lies cyclically in ]i,j]
8318                          * |    i.k.j |
8319                          * |....j i.k.| or  |.k..j i...|
8320                          */
8321                 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
8322                 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
8323                 i = j;
8324         }
8325 }
8326
8327 static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
8328 {
8329
8330         return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
8331                                       sizeof(val));
8332 }
8333
8334 static int apf_get_user(struct kvm_vcpu *vcpu, u32 *val)
8335 {
8336
8337         return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, val,
8338                                       sizeof(u32));
8339 }
8340
8341 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
8342                                      struct kvm_async_pf *work)
8343 {
8344         struct x86_exception fault;
8345
8346         trace_kvm_async_pf_not_present(work->arch.token, work->gva);
8347         kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
8348
8349         if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
8350             (vcpu->arch.apf.send_user_only &&
8351              kvm_x86_ops->get_cpl(vcpu) == 0))
8352                 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
8353         else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
8354                 fault.vector = PF_VECTOR;
8355                 fault.error_code_valid = true;
8356                 fault.error_code = 0;
8357                 fault.nested_page_fault = false;
8358                 fault.address = work->arch.token;
8359                 kvm_inject_page_fault(vcpu, &fault);
8360         }
8361 }
8362
8363 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
8364                                  struct kvm_async_pf *work)
8365 {
8366         struct x86_exception fault;
8367         u32 val;
8368
8369         if (work->wakeup_all)
8370                 work->arch.token = ~0; /* broadcast wakeup */
8371         else
8372                 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
8373         trace_kvm_async_pf_ready(work->arch.token, work->gva);
8374
8375         if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
8376             !apf_get_user(vcpu, &val)) {
8377                 if (val == KVM_PV_REASON_PAGE_NOT_PRESENT &&
8378                     vcpu->arch.exception.pending &&
8379                     vcpu->arch.exception.nr == PF_VECTOR &&
8380                     !apf_put_user(vcpu, 0)) {
8381                         vcpu->arch.exception.pending = false;
8382                         vcpu->arch.exception.nr = 0;
8383                         vcpu->arch.exception.has_error_code = false;
8384                         vcpu->arch.exception.error_code = 0;
8385                 } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
8386                         fault.vector = PF_VECTOR;
8387                         fault.error_code_valid = true;
8388                         fault.error_code = 0;
8389                         fault.nested_page_fault = false;
8390                         fault.address = work->arch.token;
8391                         kvm_inject_page_fault(vcpu, &fault);
8392                 }
8393         }
8394         vcpu->arch.apf.halted = false;
8395         vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8396 }
8397
8398 bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
8399 {
8400         if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
8401                 return true;
8402         else
8403                 return kvm_can_do_async_pf(vcpu);
8404 }
8405
8406 void kvm_arch_start_assignment(struct kvm *kvm)
8407 {
8408         atomic_inc(&kvm->arch.assigned_device_count);
8409 }
8410 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
8411
8412 void kvm_arch_end_assignment(struct kvm *kvm)
8413 {
8414         atomic_dec(&kvm->arch.assigned_device_count);
8415 }
8416 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
8417
8418 bool kvm_arch_has_assigned_device(struct kvm *kvm)
8419 {
8420         return atomic_read(&kvm->arch.assigned_device_count);
8421 }
8422 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
8423
8424 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
8425 {
8426         atomic_inc(&kvm->arch.noncoherent_dma_count);
8427 }
8428 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
8429
8430 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
8431 {
8432         atomic_dec(&kvm->arch.noncoherent_dma_count);
8433 }
8434 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
8435
8436 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
8437 {
8438         return atomic_read(&kvm->arch.noncoherent_dma_count);
8439 }
8440 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
8441
8442 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
8443                                       struct irq_bypass_producer *prod)
8444 {
8445         struct kvm_kernel_irqfd *irqfd =
8446                 container_of(cons, struct kvm_kernel_irqfd, consumer);
8447
8448         if (kvm_x86_ops->update_pi_irte) {
8449                 irqfd->producer = prod;
8450                 return kvm_x86_ops->update_pi_irte(irqfd->kvm,
8451                                 prod->irq, irqfd->gsi, 1);
8452         }
8453
8454         return -EINVAL;
8455 }
8456
8457 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
8458                                       struct irq_bypass_producer *prod)
8459 {
8460         int ret;
8461         struct kvm_kernel_irqfd *irqfd =
8462                 container_of(cons, struct kvm_kernel_irqfd, consumer);
8463
8464         if (!kvm_x86_ops->update_pi_irte) {
8465                 WARN_ON(irqfd->producer != NULL);
8466                 return;
8467         }
8468
8469         WARN_ON(irqfd->producer != prod);
8470         irqfd->producer = NULL;
8471
8472         /*
8473          * When producer of consumer is unregistered, we change back to
8474          * remapped mode, so we can re-use the current implementation
8475          * when the irq is masked/disabed or the consumer side (KVM
8476          * int this case doesn't want to receive the interrupts.
8477         */
8478         ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
8479         if (ret)
8480                 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
8481                        " fails: %d\n", irqfd->consumer.token, ret);
8482 }
8483
8484 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
8485                                    uint32_t guest_irq, bool set)
8486 {
8487         if (!kvm_x86_ops->update_pi_irte)
8488                 return -EINVAL;
8489
8490         return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
8491 }
8492
8493 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
8494 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
8495 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
8496 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
8497 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
8498 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
8499 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
8500 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
8501 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
8502 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
8503 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
8504 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
8505 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
8506 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
8507 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);
8508 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
8509 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);