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