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