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