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