KVM: X86: Move handling of INVPCID types to x86
[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                 msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + vcpu->arch.tsc_offset;
3221                 break;
3222         case MSR_MTRRcap:
3223         case 0x200 ... 0x2ff:
3224                 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
3225         case 0xcd: /* fsb frequency */
3226                 msr_info->data = 3;
3227                 break;
3228                 /*
3229                  * MSR_EBC_FREQUENCY_ID
3230                  * Conservative value valid for even the basic CPU models.
3231                  * Models 0,1: 000 in bits 23:21 indicating a bus speed of
3232                  * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
3233                  * and 266MHz for model 3, or 4. Set Core Clock
3234                  * Frequency to System Bus Frequency Ratio to 1 (bits
3235                  * 31:24) even though these are only valid for CPU
3236                  * models > 2, however guests may end up dividing or
3237                  * multiplying by zero otherwise.
3238                  */
3239         case MSR_EBC_FREQUENCY_ID:
3240                 msr_info->data = 1 << 24;
3241                 break;
3242         case MSR_IA32_APICBASE:
3243                 msr_info->data = kvm_get_apic_base(vcpu);
3244                 break;
3245         case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
3246                 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
3247         case MSR_IA32_TSCDEADLINE:
3248                 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
3249                 break;
3250         case MSR_IA32_TSC_ADJUST:
3251                 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
3252                 break;
3253         case MSR_IA32_MISC_ENABLE:
3254                 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
3255                 break;
3256         case MSR_IA32_SMBASE:
3257                 if (!msr_info->host_initiated)
3258                         return 1;
3259                 msr_info->data = vcpu->arch.smbase;
3260                 break;
3261         case MSR_SMI_COUNT:
3262                 msr_info->data = vcpu->arch.smi_count;
3263                 break;
3264         case MSR_IA32_PERF_STATUS:
3265                 /* TSC increment by tick */
3266                 msr_info->data = 1000ULL;
3267                 /* CPU multiplier */
3268                 msr_info->data |= (((uint64_t)4ULL) << 40);
3269                 break;
3270         case MSR_EFER:
3271                 msr_info->data = vcpu->arch.efer;
3272                 break;
3273         case MSR_KVM_WALL_CLOCK:
3274         case MSR_KVM_WALL_CLOCK_NEW:
3275                 msr_info->data = vcpu->kvm->arch.wall_clock;
3276                 break;
3277         case MSR_KVM_SYSTEM_TIME:
3278         case MSR_KVM_SYSTEM_TIME_NEW:
3279                 msr_info->data = vcpu->arch.time;
3280                 break;
3281         case MSR_KVM_ASYNC_PF_EN:
3282                 msr_info->data = vcpu->arch.apf.msr_en_val;
3283                 break;
3284         case MSR_KVM_ASYNC_PF_INT:
3285                 msr_info->data = vcpu->arch.apf.msr_int_val;
3286                 break;
3287         case MSR_KVM_ASYNC_PF_ACK:
3288                 msr_info->data = 0;
3289                 break;
3290         case MSR_KVM_STEAL_TIME:
3291                 msr_info->data = vcpu->arch.st.msr_val;
3292                 break;
3293         case MSR_KVM_PV_EOI_EN:
3294                 msr_info->data = vcpu->arch.pv_eoi.msr_val;
3295                 break;
3296         case MSR_KVM_POLL_CONTROL:
3297                 msr_info->data = vcpu->arch.msr_kvm_poll_control;
3298                 break;
3299         case MSR_IA32_P5_MC_ADDR:
3300         case MSR_IA32_P5_MC_TYPE:
3301         case MSR_IA32_MCG_CAP:
3302         case MSR_IA32_MCG_CTL:
3303         case MSR_IA32_MCG_STATUS:
3304         case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3305                 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
3306                                    msr_info->host_initiated);
3307         case MSR_IA32_XSS:
3308                 if (!msr_info->host_initiated &&
3309                     !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3310                         return 1;
3311                 msr_info->data = vcpu->arch.ia32_xss;
3312                 break;
3313         case MSR_K7_CLK_CTL:
3314                 /*
3315                  * Provide expected ramp-up count for K7. All other
3316                  * are set to zero, indicating minimum divisors for
3317                  * every field.
3318                  *
3319                  * This prevents guest kernels on AMD host with CPU
3320                  * type 6, model 8 and higher from exploding due to
3321                  * the rdmsr failing.
3322                  */
3323                 msr_info->data = 0x20000000;
3324                 break;
3325         case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
3326         case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
3327         case HV_X64_MSR_SYNDBG_OPTIONS:
3328         case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
3329         case HV_X64_MSR_CRASH_CTL:
3330         case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
3331         case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
3332         case HV_X64_MSR_TSC_EMULATION_CONTROL:
3333         case HV_X64_MSR_TSC_EMULATION_STATUS:
3334                 return kvm_hv_get_msr_common(vcpu,
3335                                              msr_info->index, &msr_info->data,
3336                                              msr_info->host_initiated);
3337         case MSR_IA32_BBL_CR_CTL3:
3338                 /* This legacy MSR exists but isn't fully documented in current
3339                  * silicon.  It is however accessed by winxp in very narrow
3340                  * scenarios where it sets bit #19, itself documented as
3341                  * a "reserved" bit.  Best effort attempt to source coherent
3342                  * read data here should the balance of the register be
3343                  * interpreted by the guest:
3344                  *
3345                  * L2 cache control register 3: 64GB range, 256KB size,
3346                  * enabled, latency 0x1, configured
3347                  */
3348                 msr_info->data = 0xbe702111;
3349                 break;
3350         case MSR_AMD64_OSVW_ID_LENGTH:
3351                 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3352                         return 1;
3353                 msr_info->data = vcpu->arch.osvw.length;
3354                 break;
3355         case MSR_AMD64_OSVW_STATUS:
3356                 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
3357                         return 1;
3358                 msr_info->data = vcpu->arch.osvw.status;
3359                 break;
3360         case MSR_PLATFORM_INFO:
3361                 if (!msr_info->host_initiated &&
3362                     !vcpu->kvm->arch.guest_can_read_msr_platform_info)
3363                         return 1;
3364                 msr_info->data = vcpu->arch.msr_platform_info;
3365                 break;
3366         case MSR_MISC_FEATURES_ENABLES:
3367                 msr_info->data = vcpu->arch.msr_misc_features_enables;
3368                 break;
3369         case MSR_K7_HWCR:
3370                 msr_info->data = vcpu->arch.msr_hwcr;
3371                 break;
3372         default:
3373                 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
3374                         return kvm_pmu_get_msr(vcpu, msr_info);
3375                 return KVM_MSR_RET_INVALID;
3376         }
3377         return 0;
3378 }
3379 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
3380
3381 /*
3382  * Read or write a bunch of msrs. All parameters are kernel addresses.
3383  *
3384  * @return number of msrs set successfully.
3385  */
3386 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
3387                     struct kvm_msr_entry *entries,
3388                     int (*do_msr)(struct kvm_vcpu *vcpu,
3389                                   unsigned index, u64 *data))
3390 {
3391         int i;
3392
3393         for (i = 0; i < msrs->nmsrs; ++i)
3394                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
3395                         break;
3396
3397         return i;
3398 }
3399
3400 /*
3401  * Read or write a bunch of msrs. Parameters are user addresses.
3402  *
3403  * @return number of msrs set successfully.
3404  */
3405 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
3406                   int (*do_msr)(struct kvm_vcpu *vcpu,
3407                                 unsigned index, u64 *data),
3408                   int writeback)
3409 {
3410         struct kvm_msrs msrs;
3411         struct kvm_msr_entry *entries;
3412         int r, n;
3413         unsigned size;
3414
3415         r = -EFAULT;
3416         if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
3417                 goto out;
3418
3419         r = -E2BIG;
3420         if (msrs.nmsrs >= MAX_IO_MSRS)
3421                 goto out;
3422
3423         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
3424         entries = memdup_user(user_msrs->entries, size);
3425         if (IS_ERR(entries)) {
3426                 r = PTR_ERR(entries);
3427                 goto out;
3428         }
3429
3430         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
3431         if (r < 0)
3432                 goto out_free;
3433
3434         r = -EFAULT;
3435         if (writeback && copy_to_user(user_msrs->entries, entries, size))
3436                 goto out_free;
3437
3438         r = n;
3439
3440 out_free:
3441         kfree(entries);
3442 out:
3443         return r;
3444 }
3445
3446 static inline bool kvm_can_mwait_in_guest(void)
3447 {
3448         return boot_cpu_has(X86_FEATURE_MWAIT) &&
3449                 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
3450                 boot_cpu_has(X86_FEATURE_ARAT);
3451 }
3452
3453 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
3454 {
3455         int r = 0;
3456
3457         switch (ext) {
3458         case KVM_CAP_IRQCHIP:
3459         case KVM_CAP_HLT:
3460         case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
3461         case KVM_CAP_SET_TSS_ADDR:
3462         case KVM_CAP_EXT_CPUID:
3463         case KVM_CAP_EXT_EMUL_CPUID:
3464         case KVM_CAP_CLOCKSOURCE:
3465         case KVM_CAP_PIT:
3466         case KVM_CAP_NOP_IO_DELAY:
3467         case KVM_CAP_MP_STATE:
3468         case KVM_CAP_SYNC_MMU:
3469         case KVM_CAP_USER_NMI:
3470         case KVM_CAP_REINJECT_CONTROL:
3471         case KVM_CAP_IRQ_INJECT_STATUS:
3472         case KVM_CAP_IOEVENTFD:
3473         case KVM_CAP_IOEVENTFD_NO_LENGTH:
3474         case KVM_CAP_PIT2:
3475         case KVM_CAP_PIT_STATE2:
3476         case KVM_CAP_SET_IDENTITY_MAP_ADDR:
3477         case KVM_CAP_XEN_HVM:
3478         case KVM_CAP_VCPU_EVENTS:
3479         case KVM_CAP_HYPERV:
3480         case KVM_CAP_HYPERV_VAPIC:
3481         case KVM_CAP_HYPERV_SPIN:
3482         case KVM_CAP_HYPERV_SYNIC:
3483         case KVM_CAP_HYPERV_SYNIC2:
3484         case KVM_CAP_HYPERV_VP_INDEX:
3485         case KVM_CAP_HYPERV_EVENTFD:
3486         case KVM_CAP_HYPERV_TLBFLUSH:
3487         case KVM_CAP_HYPERV_SEND_IPI:
3488         case KVM_CAP_HYPERV_CPUID:
3489         case KVM_CAP_PCI_SEGMENT:
3490         case KVM_CAP_DEBUGREGS:
3491         case KVM_CAP_X86_ROBUST_SINGLESTEP:
3492         case KVM_CAP_XSAVE:
3493         case KVM_CAP_ASYNC_PF:
3494         case KVM_CAP_ASYNC_PF_INT:
3495         case KVM_CAP_GET_TSC_KHZ:
3496         case KVM_CAP_KVMCLOCK_CTRL:
3497         case KVM_CAP_READONLY_MEM:
3498         case KVM_CAP_HYPERV_TIME:
3499         case KVM_CAP_IOAPIC_POLARITY_IGNORED:
3500         case KVM_CAP_TSC_DEADLINE_TIMER:
3501         case KVM_CAP_DISABLE_QUIRKS:
3502         case KVM_CAP_SET_BOOT_CPU_ID:
3503         case KVM_CAP_SPLIT_IRQCHIP:
3504         case KVM_CAP_IMMEDIATE_EXIT:
3505         case KVM_CAP_PMU_EVENT_FILTER:
3506         case KVM_CAP_GET_MSR_FEATURES:
3507         case KVM_CAP_MSR_PLATFORM_INFO:
3508         case KVM_CAP_EXCEPTION_PAYLOAD:
3509         case KVM_CAP_SET_GUEST_DEBUG:
3510         case KVM_CAP_LAST_CPU:
3511                 r = 1;
3512                 break;
3513         case KVM_CAP_SYNC_REGS:
3514                 r = KVM_SYNC_X86_VALID_FIELDS;
3515                 break;
3516         case KVM_CAP_ADJUST_CLOCK:
3517                 r = KVM_CLOCK_TSC_STABLE;
3518                 break;
3519         case KVM_CAP_X86_DISABLE_EXITS:
3520                 r |=  KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE |
3521                       KVM_X86_DISABLE_EXITS_CSTATE;
3522                 if(kvm_can_mwait_in_guest())
3523                         r |= KVM_X86_DISABLE_EXITS_MWAIT;
3524                 break;
3525         case KVM_CAP_X86_SMM:
3526                 /* SMBASE is usually relocated above 1M on modern chipsets,
3527                  * and SMM handlers might indeed rely on 4G segment limits,
3528                  * so do not report SMM to be available if real mode is
3529                  * emulated via vm86 mode.  Still, do not go to great lengths
3530                  * to avoid userspace's usage of the feature, because it is a
3531                  * fringe case that is not enabled except via specific settings
3532                  * of the module parameters.
3533                  */
3534                 r = kvm_x86_ops.has_emulated_msr(MSR_IA32_SMBASE);
3535                 break;
3536         case KVM_CAP_VAPIC:
3537                 r = !kvm_x86_ops.cpu_has_accelerated_tpr();
3538                 break;
3539         case KVM_CAP_NR_VCPUS:
3540                 r = KVM_SOFT_MAX_VCPUS;
3541                 break;
3542         case KVM_CAP_MAX_VCPUS:
3543                 r = KVM_MAX_VCPUS;
3544                 break;
3545         case KVM_CAP_MAX_VCPU_ID:
3546                 r = KVM_MAX_VCPU_ID;
3547                 break;
3548         case KVM_CAP_PV_MMU:    /* obsolete */
3549                 r = 0;
3550                 break;
3551         case KVM_CAP_MCE:
3552                 r = KVM_MAX_MCE_BANKS;
3553                 break;
3554         case KVM_CAP_XCRS:
3555                 r = boot_cpu_has(X86_FEATURE_XSAVE);
3556                 break;
3557         case KVM_CAP_TSC_CONTROL:
3558                 r = kvm_has_tsc_control;
3559                 break;
3560         case KVM_CAP_X2APIC_API:
3561                 r = KVM_X2APIC_API_VALID_FLAGS;
3562                 break;
3563         case KVM_CAP_NESTED_STATE:
3564                 r = kvm_x86_ops.nested_ops->get_state ?
3565                         kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
3566                 break;
3567         case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
3568                 r = kvm_x86_ops.enable_direct_tlbflush != NULL;
3569                 break;
3570         case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
3571                 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
3572                 break;
3573         case KVM_CAP_SMALLER_MAXPHYADDR:
3574                 r = (int) allow_smaller_maxphyaddr;
3575                 break;
3576         case KVM_CAP_STEAL_TIME:
3577                 r = sched_info_on();
3578                 break;
3579         default:
3580                 break;
3581         }
3582         return r;
3583
3584 }
3585
3586 long kvm_arch_dev_ioctl(struct file *filp,
3587                         unsigned int ioctl, unsigned long arg)
3588 {
3589         void __user *argp = (void __user *)arg;
3590         long r;
3591
3592         switch (ioctl) {
3593         case KVM_GET_MSR_INDEX_LIST: {
3594                 struct kvm_msr_list __user *user_msr_list = argp;
3595                 struct kvm_msr_list msr_list;
3596                 unsigned n;
3597
3598                 r = -EFAULT;
3599                 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3600                         goto out;
3601                 n = msr_list.nmsrs;
3602                 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
3603                 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3604                         goto out;
3605                 r = -E2BIG;
3606                 if (n < msr_list.nmsrs)
3607                         goto out;
3608                 r = -EFAULT;
3609                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
3610                                  num_msrs_to_save * sizeof(u32)))
3611                         goto out;
3612                 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
3613                                  &emulated_msrs,
3614                                  num_emulated_msrs * sizeof(u32)))
3615                         goto out;
3616                 r = 0;
3617                 break;
3618         }
3619         case KVM_GET_SUPPORTED_CPUID:
3620         case KVM_GET_EMULATED_CPUID: {
3621                 struct kvm_cpuid2 __user *cpuid_arg = argp;
3622                 struct kvm_cpuid2 cpuid;
3623
3624                 r = -EFAULT;
3625                 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
3626                         goto out;
3627
3628                 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
3629                                             ioctl);
3630                 if (r)
3631                         goto out;
3632
3633                 r = -EFAULT;
3634                 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
3635                         goto out;
3636                 r = 0;
3637                 break;
3638         }
3639         case KVM_X86_GET_MCE_CAP_SUPPORTED:
3640                 r = -EFAULT;
3641                 if (copy_to_user(argp, &kvm_mce_cap_supported,
3642                                  sizeof(kvm_mce_cap_supported)))
3643                         goto out;
3644                 r = 0;
3645                 break;
3646         case KVM_GET_MSR_FEATURE_INDEX_LIST: {
3647                 struct kvm_msr_list __user *user_msr_list = argp;
3648                 struct kvm_msr_list msr_list;
3649                 unsigned int n;
3650
3651                 r = -EFAULT;
3652                 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
3653                         goto out;
3654                 n = msr_list.nmsrs;
3655                 msr_list.nmsrs = num_msr_based_features;
3656                 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
3657                         goto out;
3658                 r = -E2BIG;
3659                 if (n < msr_list.nmsrs)
3660                         goto out;
3661                 r = -EFAULT;
3662                 if (copy_to_user(user_msr_list->indices, &msr_based_features,
3663                                  num_msr_based_features * sizeof(u32)))
3664                         goto out;
3665                 r = 0;
3666                 break;
3667         }
3668         case KVM_GET_MSRS:
3669                 r = msr_io(NULL, argp, do_get_msr_feature, 1);
3670                 break;
3671         default:
3672                 r = -EINVAL;
3673                 break;
3674         }
3675 out:
3676         return r;
3677 }
3678
3679 static void wbinvd_ipi(void *garbage)
3680 {
3681         wbinvd();
3682 }
3683
3684 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
3685 {
3686         return kvm_arch_has_noncoherent_dma(vcpu->kvm);
3687 }
3688
3689 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3690 {
3691         /* Address WBINVD may be executed by guest */
3692         if (need_emulate_wbinvd(vcpu)) {
3693                 if (kvm_x86_ops.has_wbinvd_exit())
3694                         cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
3695                 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
3696                         smp_call_function_single(vcpu->cpu,
3697                                         wbinvd_ipi, NULL, 1);
3698         }
3699
3700         kvm_x86_ops.vcpu_load(vcpu, cpu);
3701
3702         /* Save host pkru register if supported */
3703         vcpu->arch.host_pkru = read_pkru();
3704
3705         /* Apply any externally detected TSC adjustments (due to suspend) */
3706         if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
3707                 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
3708                 vcpu->arch.tsc_offset_adjustment = 0;
3709                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3710         }
3711
3712         if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
3713                 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
3714                                 rdtsc() - vcpu->arch.last_host_tsc;
3715                 if (tsc_delta < 0)
3716                         mark_tsc_unstable("KVM discovered backwards TSC");
3717
3718                 if (kvm_check_tsc_unstable()) {
3719                         u64 offset = kvm_compute_tsc_offset(vcpu,
3720                                                 vcpu->arch.last_guest_tsc);
3721                         kvm_vcpu_write_tsc_offset(vcpu, offset);
3722                         vcpu->arch.tsc_catchup = 1;
3723                 }
3724
3725                 if (kvm_lapic_hv_timer_in_use(vcpu))
3726                         kvm_lapic_restart_hv_timer(vcpu);
3727
3728                 /*
3729                  * On a host with synchronized TSC, there is no need to update
3730                  * kvmclock on vcpu->cpu migration
3731                  */
3732                 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
3733                         kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
3734                 if (vcpu->cpu != cpu)
3735                         kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
3736                 vcpu->cpu = cpu;
3737         }
3738
3739         kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
3740 }
3741
3742 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
3743 {
3744         struct kvm_host_map map;
3745         struct kvm_steal_time *st;
3746
3747         if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3748                 return;
3749
3750         if (vcpu->arch.st.preempted)
3751                 return;
3752
3753         if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT, &map,
3754                         &vcpu->arch.st.cache, true))
3755                 return;
3756
3757         st = map.hva +
3758                 offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
3759
3760         st->preempted = vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
3761
3762         kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, true);
3763 }
3764
3765 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
3766 {
3767         int idx;
3768
3769         if (vcpu->preempted)
3770                 vcpu->arch.preempted_in_kernel = !kvm_x86_ops.get_cpl(vcpu);
3771
3772         /*
3773          * Disable page faults because we're in atomic context here.
3774          * kvm_write_guest_offset_cached() would call might_fault()
3775          * that relies on pagefault_disable() to tell if there's a
3776          * bug. NOTE: the write to guest memory may not go through if
3777          * during postcopy live migration or if there's heavy guest
3778          * paging.
3779          */
3780         pagefault_disable();
3781         /*
3782          * kvm_memslots() will be called by
3783          * kvm_write_guest_offset_cached() so take the srcu lock.
3784          */
3785         idx = srcu_read_lock(&vcpu->kvm->srcu);
3786         kvm_steal_time_set_preempted(vcpu);
3787         srcu_read_unlock(&vcpu->kvm->srcu, idx);
3788         pagefault_enable();
3789         kvm_x86_ops.vcpu_put(vcpu);
3790         vcpu->arch.last_host_tsc = rdtsc();
3791         /*
3792          * If userspace has set any breakpoints or watchpoints, dr6 is restored
3793          * on every vmexit, but if not, we might have a stale dr6 from the
3794          * guest. do_debug expects dr6 to be cleared after it runs, do the same.
3795          */
3796         set_debugreg(0, 6);
3797 }
3798
3799 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
3800                                     struct kvm_lapic_state *s)
3801 {
3802         if (vcpu->arch.apicv_active)
3803                 kvm_x86_ops.sync_pir_to_irr(vcpu);
3804
3805         return kvm_apic_get_state(vcpu, s);
3806 }
3807
3808 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
3809                                     struct kvm_lapic_state *s)
3810 {
3811         int r;
3812
3813         r = kvm_apic_set_state(vcpu, s);
3814         if (r)
3815                 return r;
3816         update_cr8_intercept(vcpu);
3817
3818         return 0;
3819 }
3820
3821 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
3822 {
3823         return (!lapic_in_kernel(vcpu) ||
3824                 kvm_apic_accept_pic_intr(vcpu));
3825 }
3826
3827 /*
3828  * if userspace requested an interrupt window, check that the
3829  * interrupt window is open.
3830  *
3831  * No need to exit to userspace if we already have an interrupt queued.
3832  */
3833 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
3834 {
3835         return kvm_arch_interrupt_allowed(vcpu) &&
3836                 !kvm_cpu_has_interrupt(vcpu) &&
3837                 !kvm_event_needs_reinjection(vcpu) &&
3838                 kvm_cpu_accept_dm_intr(vcpu);
3839 }
3840
3841 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
3842                                     struct kvm_interrupt *irq)
3843 {
3844         if (irq->irq >= KVM_NR_INTERRUPTS)
3845                 return -EINVAL;
3846
3847         if (!irqchip_in_kernel(vcpu->kvm)) {
3848                 kvm_queue_interrupt(vcpu, irq->irq, false);
3849                 kvm_make_request(KVM_REQ_EVENT, vcpu);
3850                 return 0;
3851         }
3852
3853         /*
3854          * With in-kernel LAPIC, we only use this to inject EXTINT, so
3855          * fail for in-kernel 8259.
3856          */
3857         if (pic_in_kernel(vcpu->kvm))
3858                 return -ENXIO;
3859
3860         if (vcpu->arch.pending_external_vector != -1)
3861                 return -EEXIST;
3862
3863         vcpu->arch.pending_external_vector = irq->irq;
3864         kvm_make_request(KVM_REQ_EVENT, vcpu);
3865         return 0;
3866 }
3867
3868 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
3869 {
3870         kvm_inject_nmi(vcpu);
3871
3872         return 0;
3873 }
3874
3875 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
3876 {
3877         kvm_make_request(KVM_REQ_SMI, vcpu);
3878
3879         return 0;
3880 }
3881
3882 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
3883                                            struct kvm_tpr_access_ctl *tac)
3884 {
3885         if (tac->flags)
3886                 return -EINVAL;
3887         vcpu->arch.tpr_access_reporting = !!tac->enabled;
3888         return 0;
3889 }
3890
3891 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
3892                                         u64 mcg_cap)
3893 {
3894         int r;
3895         unsigned bank_num = mcg_cap & 0xff, bank;
3896
3897         r = -EINVAL;
3898         if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
3899                 goto out;
3900         if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
3901                 goto out;
3902         r = 0;
3903         vcpu->arch.mcg_cap = mcg_cap;
3904         /* Init IA32_MCG_CTL to all 1s */
3905         if (mcg_cap & MCG_CTL_P)
3906                 vcpu->arch.mcg_ctl = ~(u64)0;
3907         /* Init IA32_MCi_CTL to all 1s */
3908         for (bank = 0; bank < bank_num; bank++)
3909                 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
3910
3911         kvm_x86_ops.setup_mce(vcpu);
3912 out:
3913         return r;
3914 }
3915
3916 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
3917                                       struct kvm_x86_mce *mce)
3918 {
3919         u64 mcg_cap = vcpu->arch.mcg_cap;
3920         unsigned bank_num = mcg_cap & 0xff;
3921         u64 *banks = vcpu->arch.mce_banks;
3922
3923         if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
3924                 return -EINVAL;
3925         /*
3926          * if IA32_MCG_CTL is not all 1s, the uncorrected error
3927          * reporting is disabled
3928          */
3929         if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3930             vcpu->arch.mcg_ctl != ~(u64)0)
3931                 return 0;
3932         banks += 4 * mce->bank;
3933         /*
3934          * if IA32_MCi_CTL is not all 1s, the uncorrected error
3935          * reporting is disabled for the bank
3936          */
3937         if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3938                 return 0;
3939         if (mce->status & MCI_STATUS_UC) {
3940                 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
3941                     !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
3942                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3943                         return 0;
3944                 }
3945                 if (banks[1] & MCI_STATUS_VAL)
3946                         mce->status |= MCI_STATUS_OVER;
3947                 banks[2] = mce->addr;
3948                 banks[3] = mce->misc;
3949                 vcpu->arch.mcg_status = mce->mcg_status;
3950                 banks[1] = mce->status;
3951                 kvm_queue_exception(vcpu, MC_VECTOR);
3952         } else if (!(banks[1] & MCI_STATUS_VAL)
3953                    || !(banks[1] & MCI_STATUS_UC)) {
3954                 if (banks[1] & MCI_STATUS_VAL)
3955                         mce->status |= MCI_STATUS_OVER;
3956                 banks[2] = mce->addr;
3957                 banks[3] = mce->misc;
3958                 banks[1] = mce->status;
3959         } else
3960                 banks[1] |= MCI_STATUS_OVER;
3961         return 0;
3962 }
3963
3964 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3965                                                struct kvm_vcpu_events *events)
3966 {
3967         process_nmi(vcpu);
3968
3969         /*
3970          * In guest mode, payload delivery should be deferred,
3971          * so that the L1 hypervisor can intercept #PF before
3972          * CR2 is modified (or intercept #DB before DR6 is
3973          * modified under nVMX). Unless the per-VM capability,
3974          * KVM_CAP_EXCEPTION_PAYLOAD, is set, we may not defer the delivery of
3975          * an exception payload and handle after a KVM_GET_VCPU_EVENTS. Since we
3976          * opportunistically defer the exception payload, deliver it if the
3977          * capability hasn't been requested before processing a
3978          * KVM_GET_VCPU_EVENTS.
3979          */
3980         if (!vcpu->kvm->arch.exception_payload_enabled &&
3981             vcpu->arch.exception.pending && vcpu->arch.exception.has_payload)
3982                 kvm_deliver_exception_payload(vcpu);
3983
3984         /*
3985          * The API doesn't provide the instruction length for software
3986          * exceptions, so don't report them. As long as the guest RIP
3987          * isn't advanced, we should expect to encounter the exception
3988          * again.
3989          */
3990         if (kvm_exception_is_soft(vcpu->arch.exception.nr)) {
3991                 events->exception.injected = 0;
3992                 events->exception.pending = 0;
3993         } else {
3994                 events->exception.injected = vcpu->arch.exception.injected;
3995                 events->exception.pending = vcpu->arch.exception.pending;
3996                 /*
3997                  * For ABI compatibility, deliberately conflate
3998                  * pending and injected exceptions when
3999                  * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
4000                  */
4001                 if (!vcpu->kvm->arch.exception_payload_enabled)
4002                         events->exception.injected |=
4003                                 vcpu->arch.exception.pending;
4004         }
4005         events->exception.nr = vcpu->arch.exception.nr;
4006         events->exception.has_error_code = vcpu->arch.exception.has_error_code;
4007         events->exception.error_code = vcpu->arch.exception.error_code;
4008         events->exception_has_payload = vcpu->arch.exception.has_payload;
4009         events->exception_payload = vcpu->arch.exception.payload;
4010
4011         events->interrupt.injected =
4012                 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
4013         events->interrupt.nr = vcpu->arch.interrupt.nr;
4014         events->interrupt.soft = 0;
4015         events->interrupt.shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
4016
4017         events->nmi.injected = vcpu->arch.nmi_injected;
4018         events->nmi.pending = vcpu->arch.nmi_pending != 0;
4019         events->nmi.masked = kvm_x86_ops.get_nmi_mask(vcpu);
4020         events->nmi.pad = 0;
4021
4022         events->sipi_vector = 0; /* never valid when reporting to user space */
4023
4024         events->smi.smm = is_smm(vcpu);
4025         events->smi.pending = vcpu->arch.smi_pending;
4026         events->smi.smm_inside_nmi =
4027                 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
4028         events->smi.latched_init = kvm_lapic_latched_init(vcpu);
4029
4030         events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
4031                          | KVM_VCPUEVENT_VALID_SHADOW
4032                          | KVM_VCPUEVENT_VALID_SMM);
4033         if (vcpu->kvm->arch.exception_payload_enabled)
4034                 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
4035
4036         memset(&events->reserved, 0, sizeof(events->reserved));
4037 }
4038
4039 static void kvm_smm_changed(struct kvm_vcpu *vcpu);
4040
4041 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
4042                                               struct kvm_vcpu_events *events)
4043 {
4044         if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
4045                               | KVM_VCPUEVENT_VALID_SIPI_VECTOR
4046                               | KVM_VCPUEVENT_VALID_SHADOW
4047                               | KVM_VCPUEVENT_VALID_SMM
4048                               | KVM_VCPUEVENT_VALID_PAYLOAD))
4049                 return -EINVAL;
4050
4051         if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
4052                 if (!vcpu->kvm->arch.exception_payload_enabled)
4053                         return -EINVAL;
4054                 if (events->exception.pending)
4055                         events->exception.injected = 0;
4056                 else
4057                         events->exception_has_payload = 0;
4058         } else {
4059                 events->exception.pending = 0;
4060                 events->exception_has_payload = 0;
4061         }
4062
4063         if ((events->exception.injected || events->exception.pending) &&
4064             (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
4065                 return -EINVAL;
4066
4067         /* INITs are latched while in SMM */
4068         if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
4069             (events->smi.smm || events->smi.pending) &&
4070             vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
4071                 return -EINVAL;
4072
4073         process_nmi(vcpu);
4074         vcpu->arch.exception.injected = events->exception.injected;
4075         vcpu->arch.exception.pending = events->exception.pending;
4076         vcpu->arch.exception.nr = events->exception.nr;
4077         vcpu->arch.exception.has_error_code = events->exception.has_error_code;
4078         vcpu->arch.exception.error_code = events->exception.error_code;
4079         vcpu->arch.exception.has_payload = events->exception_has_payload;
4080         vcpu->arch.exception.payload = events->exception_payload;
4081
4082         vcpu->arch.interrupt.injected = events->interrupt.injected;
4083         vcpu->arch.interrupt.nr = events->interrupt.nr;
4084         vcpu->arch.interrupt.soft = events->interrupt.soft;
4085         if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
4086                 kvm_x86_ops.set_interrupt_shadow(vcpu,
4087                                                   events->interrupt.shadow);
4088
4089         vcpu->arch.nmi_injected = events->nmi.injected;
4090         if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
4091                 vcpu->arch.nmi_pending = events->nmi.pending;
4092         kvm_x86_ops.set_nmi_mask(vcpu, events->nmi.masked);
4093
4094         if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
4095             lapic_in_kernel(vcpu))
4096                 vcpu->arch.apic->sipi_vector = events->sipi_vector;
4097
4098         if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
4099                 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
4100                         if (events->smi.smm)
4101                                 vcpu->arch.hflags |= HF_SMM_MASK;
4102                         else
4103                                 vcpu->arch.hflags &= ~HF_SMM_MASK;
4104                         kvm_smm_changed(vcpu);
4105                 }
4106
4107                 vcpu->arch.smi_pending = events->smi.pending;
4108
4109                 if (events->smi.smm) {
4110                         if (events->smi.smm_inside_nmi)
4111                                 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
4112                         else
4113                                 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
4114                 }
4115
4116                 if (lapic_in_kernel(vcpu)) {
4117                         if (events->smi.latched_init)
4118                                 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4119                         else
4120                                 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
4121                 }
4122         }
4123
4124         kvm_make_request(KVM_REQ_EVENT, vcpu);
4125
4126         return 0;
4127 }
4128
4129 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
4130                                              struct kvm_debugregs *dbgregs)
4131 {
4132         unsigned long val;
4133
4134         memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
4135         kvm_get_dr(vcpu, 6, &val);
4136         dbgregs->dr6 = val;
4137         dbgregs->dr7 = vcpu->arch.dr7;
4138         dbgregs->flags = 0;
4139         memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
4140 }
4141
4142 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
4143                                             struct kvm_debugregs *dbgregs)
4144 {
4145         if (dbgregs->flags)
4146                 return -EINVAL;
4147
4148         if (dbgregs->dr6 & ~0xffffffffull)
4149                 return -EINVAL;
4150         if (dbgregs->dr7 & ~0xffffffffull)
4151                 return -EINVAL;
4152
4153         memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
4154         kvm_update_dr0123(vcpu);
4155         vcpu->arch.dr6 = dbgregs->dr6;
4156         vcpu->arch.dr7 = dbgregs->dr7;
4157         kvm_update_dr7(vcpu);
4158
4159         return 0;
4160 }
4161
4162 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
4163
4164 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
4165 {
4166         struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4167         u64 xstate_bv = xsave->header.xfeatures;
4168         u64 valid;
4169
4170         /*
4171          * Copy legacy XSAVE area, to avoid complications with CPUID
4172          * leaves 0 and 1 in the loop below.
4173          */
4174         memcpy(dest, xsave, XSAVE_HDR_OFFSET);
4175
4176         /* Set XSTATE_BV */
4177         xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
4178         *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
4179
4180         /*
4181          * Copy each region from the possibly compacted offset to the
4182          * non-compacted offset.
4183          */
4184         valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4185         while (valid) {
4186                 u64 xfeature_mask = valid & -valid;
4187                 int xfeature_nr = fls64(xfeature_mask) - 1;
4188                 void *src = get_xsave_addr(xsave, xfeature_nr);
4189
4190                 if (src) {
4191                         u32 size, offset, ecx, edx;
4192                         cpuid_count(XSTATE_CPUID, xfeature_nr,
4193                                     &size, &offset, &ecx, &edx);
4194                         if (xfeature_nr == XFEATURE_PKRU)
4195                                 memcpy(dest + offset, &vcpu->arch.pkru,
4196                                        sizeof(vcpu->arch.pkru));
4197                         else
4198                                 memcpy(dest + offset, src, size);
4199
4200                 }
4201
4202                 valid -= xfeature_mask;
4203         }
4204 }
4205
4206 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
4207 {
4208         struct xregs_state *xsave = &vcpu->arch.guest_fpu->state.xsave;
4209         u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
4210         u64 valid;
4211
4212         /*
4213          * Copy legacy XSAVE area, to avoid complications with CPUID
4214          * leaves 0 and 1 in the loop below.
4215          */
4216         memcpy(xsave, src, XSAVE_HDR_OFFSET);
4217
4218         /* Set XSTATE_BV and possibly XCOMP_BV.  */
4219         xsave->header.xfeatures = xstate_bv;
4220         if (boot_cpu_has(X86_FEATURE_XSAVES))
4221                 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
4222
4223         /*
4224          * Copy each region from the non-compacted offset to the
4225          * possibly compacted offset.
4226          */
4227         valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
4228         while (valid) {
4229                 u64 xfeature_mask = valid & -valid;
4230                 int xfeature_nr = fls64(xfeature_mask) - 1;
4231                 void *dest = get_xsave_addr(xsave, xfeature_nr);
4232
4233                 if (dest) {
4234                         u32 size, offset, ecx, edx;
4235                         cpuid_count(XSTATE_CPUID, xfeature_nr,
4236                                     &size, &offset, &ecx, &edx);
4237                         if (xfeature_nr == XFEATURE_PKRU)
4238                                 memcpy(&vcpu->arch.pkru, src + offset,
4239                                        sizeof(vcpu->arch.pkru));
4240                         else
4241                                 memcpy(dest, src + offset, size);
4242                 }
4243
4244                 valid -= xfeature_mask;
4245         }
4246 }
4247
4248 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
4249                                          struct kvm_xsave *guest_xsave)
4250 {
4251         if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4252                 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
4253                 fill_xsave((u8 *) guest_xsave->region, vcpu);
4254         } else {
4255                 memcpy(guest_xsave->region,
4256                         &vcpu->arch.guest_fpu->state.fxsave,
4257                         sizeof(struct fxregs_state));
4258                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
4259                         XFEATURE_MASK_FPSSE;
4260         }
4261 }
4262
4263 #define XSAVE_MXCSR_OFFSET 24
4264
4265 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
4266                                         struct kvm_xsave *guest_xsave)
4267 {
4268         u64 xstate_bv =
4269                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
4270         u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
4271
4272         if (boot_cpu_has(X86_FEATURE_XSAVE)) {
4273                 /*
4274                  * Here we allow setting states that are not present in
4275                  * CPUID leaf 0xD, index 0, EDX:EAX.  This is for compatibility
4276                  * with old userspace.
4277                  */
4278                 if (xstate_bv & ~supported_xcr0 || mxcsr & ~mxcsr_feature_mask)
4279                         return -EINVAL;
4280                 load_xsave(vcpu, (u8 *)guest_xsave->region);
4281         } else {
4282                 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
4283                         mxcsr & ~mxcsr_feature_mask)
4284                         return -EINVAL;
4285                 memcpy(&vcpu->arch.guest_fpu->state.fxsave,
4286                         guest_xsave->region, sizeof(struct fxregs_state));
4287         }
4288         return 0;
4289 }
4290
4291 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
4292                                         struct kvm_xcrs *guest_xcrs)
4293 {
4294         if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
4295                 guest_xcrs->nr_xcrs = 0;
4296                 return;
4297         }
4298
4299         guest_xcrs->nr_xcrs = 1;
4300         guest_xcrs->flags = 0;
4301         guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
4302         guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
4303 }
4304
4305 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
4306                                        struct kvm_xcrs *guest_xcrs)
4307 {
4308         int i, r = 0;
4309
4310         if (!boot_cpu_has(X86_FEATURE_XSAVE))
4311                 return -EINVAL;
4312
4313         if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
4314                 return -EINVAL;
4315
4316         for (i = 0; i < guest_xcrs->nr_xcrs; i++)
4317                 /* Only support XCR0 currently */
4318                 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
4319                         r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
4320                                 guest_xcrs->xcrs[i].value);
4321                         break;
4322                 }
4323         if (r)
4324                 r = -EINVAL;
4325         return r;
4326 }
4327
4328 /*
4329  * kvm_set_guest_paused() indicates to the guest kernel that it has been
4330  * stopped by the hypervisor.  This function will be called from the host only.
4331  * EINVAL is returned when the host attempts to set the flag for a guest that
4332  * does not support pv clocks.
4333  */
4334 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
4335 {
4336         if (!vcpu->arch.pv_time_enabled)
4337                 return -EINVAL;
4338         vcpu->arch.pvclock_set_guest_stopped_request = true;
4339         kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4340         return 0;
4341 }
4342
4343 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
4344                                      struct kvm_enable_cap *cap)
4345 {
4346         int r;
4347         uint16_t vmcs_version;
4348         void __user *user_ptr;
4349
4350         if (cap->flags)
4351                 return -EINVAL;
4352
4353         switch (cap->cap) {
4354         case KVM_CAP_HYPERV_SYNIC2:
4355                 if (cap->args[0])
4356                         return -EINVAL;
4357                 fallthrough;
4358
4359         case KVM_CAP_HYPERV_SYNIC:
4360                 if (!irqchip_in_kernel(vcpu->kvm))
4361                         return -EINVAL;
4362                 return kvm_hv_activate_synic(vcpu, cap->cap ==
4363                                              KVM_CAP_HYPERV_SYNIC2);
4364         case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4365                 if (!kvm_x86_ops.nested_ops->enable_evmcs)
4366                         return -ENOTTY;
4367                 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
4368                 if (!r) {
4369                         user_ptr = (void __user *)(uintptr_t)cap->args[0];
4370                         if (copy_to_user(user_ptr, &vmcs_version,
4371                                          sizeof(vmcs_version)))
4372                                 r = -EFAULT;
4373                 }
4374                 return r;
4375         case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4376                 if (!kvm_x86_ops.enable_direct_tlbflush)
4377                         return -ENOTTY;
4378
4379                 return kvm_x86_ops.enable_direct_tlbflush(vcpu);
4380
4381         default:
4382                 return -EINVAL;
4383         }
4384 }
4385
4386 long kvm_arch_vcpu_ioctl(struct file *filp,
4387                          unsigned int ioctl, unsigned long arg)
4388 {
4389         struct kvm_vcpu *vcpu = filp->private_data;
4390         void __user *argp = (void __user *)arg;
4391         int r;
4392         union {
4393                 struct kvm_lapic_state *lapic;
4394                 struct kvm_xsave *xsave;
4395                 struct kvm_xcrs *xcrs;
4396                 void *buffer;
4397         } u;
4398
4399         vcpu_load(vcpu);
4400
4401         u.buffer = NULL;
4402         switch (ioctl) {
4403         case KVM_GET_LAPIC: {
4404                 r = -EINVAL;
4405                 if (!lapic_in_kernel(vcpu))
4406                         goto out;
4407                 u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
4408                                 GFP_KERNEL_ACCOUNT);
4409
4410                 r = -ENOMEM;
4411                 if (!u.lapic)
4412                         goto out;
4413                 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
4414                 if (r)
4415                         goto out;
4416                 r = -EFAULT;
4417                 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
4418                         goto out;
4419                 r = 0;
4420                 break;
4421         }
4422         case KVM_SET_LAPIC: {
4423                 r = -EINVAL;
4424                 if (!lapic_in_kernel(vcpu))
4425                         goto out;
4426                 u.lapic = memdup_user(argp, sizeof(*u.lapic));
4427                 if (IS_ERR(u.lapic)) {
4428                         r = PTR_ERR(u.lapic);
4429                         goto out_nofree;
4430                 }
4431
4432                 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
4433                 break;
4434         }
4435         case KVM_INTERRUPT: {
4436                 struct kvm_interrupt irq;
4437
4438                 r = -EFAULT;
4439                 if (copy_from_user(&irq, argp, sizeof(irq)))
4440                         goto out;
4441                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
4442                 break;
4443         }
4444         case KVM_NMI: {
4445                 r = kvm_vcpu_ioctl_nmi(vcpu);
4446                 break;
4447         }
4448         case KVM_SMI: {
4449                 r = kvm_vcpu_ioctl_smi(vcpu);
4450                 break;
4451         }
4452         case KVM_SET_CPUID: {
4453                 struct kvm_cpuid __user *cpuid_arg = argp;
4454                 struct kvm_cpuid cpuid;
4455
4456                 r = -EFAULT;
4457                 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4458                         goto out;
4459                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4460                 break;
4461         }
4462         case KVM_SET_CPUID2: {
4463                 struct kvm_cpuid2 __user *cpuid_arg = argp;
4464                 struct kvm_cpuid2 cpuid;
4465
4466                 r = -EFAULT;
4467                 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4468                         goto out;
4469                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
4470                                               cpuid_arg->entries);
4471                 break;
4472         }
4473         case KVM_GET_CPUID2: {
4474                 struct kvm_cpuid2 __user *cpuid_arg = argp;
4475                 struct kvm_cpuid2 cpuid;
4476
4477                 r = -EFAULT;
4478                 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4479                         goto out;
4480                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
4481                                               cpuid_arg->entries);
4482                 if (r)
4483                         goto out;
4484                 r = -EFAULT;
4485                 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4486                         goto out;
4487                 r = 0;
4488                 break;
4489         }
4490         case KVM_GET_MSRS: {
4491                 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4492                 r = msr_io(vcpu, argp, do_get_msr, 1);
4493                 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4494                 break;
4495         }
4496         case KVM_SET_MSRS: {
4497                 int idx = srcu_read_lock(&vcpu->kvm->srcu);
4498                 r = msr_io(vcpu, argp, do_set_msr, 0);
4499                 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4500                 break;
4501         }
4502         case KVM_TPR_ACCESS_REPORTING: {
4503                 struct kvm_tpr_access_ctl tac;
4504
4505                 r = -EFAULT;
4506                 if (copy_from_user(&tac, argp, sizeof(tac)))
4507                         goto out;
4508                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
4509                 if (r)
4510                         goto out;
4511                 r = -EFAULT;
4512                 if (copy_to_user(argp, &tac, sizeof(tac)))
4513                         goto out;
4514                 r = 0;
4515                 break;
4516         };
4517         case KVM_SET_VAPIC_ADDR: {
4518                 struct kvm_vapic_addr va;
4519                 int idx;
4520
4521                 r = -EINVAL;
4522                 if (!lapic_in_kernel(vcpu))
4523                         goto out;
4524                 r = -EFAULT;
4525                 if (copy_from_user(&va, argp, sizeof(va)))
4526                         goto out;
4527                 idx = srcu_read_lock(&vcpu->kvm->srcu);
4528                 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
4529                 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4530                 break;
4531         }
4532         case KVM_X86_SETUP_MCE: {
4533                 u64 mcg_cap;
4534
4535                 r = -EFAULT;
4536                 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
4537                         goto out;
4538                 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
4539                 break;
4540         }
4541         case KVM_X86_SET_MCE: {
4542                 struct kvm_x86_mce mce;
4543
4544                 r = -EFAULT;
4545                 if (copy_from_user(&mce, argp, sizeof(mce)))
4546                         goto out;
4547                 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
4548                 break;
4549         }
4550         case KVM_GET_VCPU_EVENTS: {
4551                 struct kvm_vcpu_events events;
4552
4553                 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
4554
4555                 r = -EFAULT;
4556                 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
4557                         break;
4558                 r = 0;
4559                 break;
4560         }
4561         case KVM_SET_VCPU_EVENTS: {
4562                 struct kvm_vcpu_events events;
4563
4564                 r = -EFAULT;
4565                 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
4566                         break;
4567
4568                 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
4569                 break;
4570         }
4571         case KVM_GET_DEBUGREGS: {
4572                 struct kvm_debugregs dbgregs;
4573
4574                 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
4575
4576                 r = -EFAULT;
4577                 if (copy_to_user(argp, &dbgregs,
4578                                  sizeof(struct kvm_debugregs)))
4579                         break;
4580                 r = 0;
4581                 break;
4582         }
4583         case KVM_SET_DEBUGREGS: {
4584                 struct kvm_debugregs dbgregs;
4585
4586                 r = -EFAULT;
4587                 if (copy_from_user(&dbgregs, argp,
4588                                    sizeof(struct kvm_debugregs)))
4589                         break;
4590
4591                 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
4592                 break;
4593         }
4594         case KVM_GET_XSAVE: {
4595                 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
4596                 r = -ENOMEM;
4597                 if (!u.xsave)
4598                         break;
4599
4600                 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
4601
4602                 r = -EFAULT;
4603                 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
4604                         break;
4605                 r = 0;
4606                 break;
4607         }
4608         case KVM_SET_XSAVE: {
4609                 u.xsave = memdup_user(argp, sizeof(*u.xsave));
4610                 if (IS_ERR(u.xsave)) {
4611                         r = PTR_ERR(u.xsave);
4612                         goto out_nofree;
4613                 }
4614
4615                 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
4616                 break;
4617         }
4618         case KVM_GET_XCRS: {
4619                 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
4620                 r = -ENOMEM;
4621                 if (!u.xcrs)
4622                         break;
4623
4624                 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
4625
4626                 r = -EFAULT;
4627                 if (copy_to_user(argp, u.xcrs,
4628                                  sizeof(struct kvm_xcrs)))
4629                         break;
4630                 r = 0;
4631                 break;
4632         }
4633         case KVM_SET_XCRS: {
4634                 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
4635                 if (IS_ERR(u.xcrs)) {
4636                         r = PTR_ERR(u.xcrs);
4637                         goto out_nofree;
4638                 }
4639
4640                 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
4641                 break;
4642         }
4643         case KVM_SET_TSC_KHZ: {
4644                 u32 user_tsc_khz;
4645
4646                 r = -EINVAL;
4647                 user_tsc_khz = (u32)arg;
4648
4649                 if (kvm_has_tsc_control &&
4650                     user_tsc_khz >= kvm_max_guest_tsc_khz)
4651                         goto out;
4652
4653                 if (user_tsc_khz == 0)
4654                         user_tsc_khz = tsc_khz;
4655
4656                 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
4657                         r = 0;
4658
4659                 goto out;
4660         }
4661         case KVM_GET_TSC_KHZ: {
4662                 r = vcpu->arch.virtual_tsc_khz;
4663                 goto out;
4664         }
4665         case KVM_KVMCLOCK_CTRL: {
4666                 r = kvm_set_guest_paused(vcpu);
4667                 goto out;
4668         }
4669         case KVM_ENABLE_CAP: {
4670                 struct kvm_enable_cap cap;
4671
4672                 r = -EFAULT;
4673                 if (copy_from_user(&cap, argp, sizeof(cap)))
4674                         goto out;
4675                 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
4676                 break;
4677         }
4678         case KVM_GET_NESTED_STATE: {
4679                 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4680                 u32 user_data_size;
4681
4682                 r = -EINVAL;
4683                 if (!kvm_x86_ops.nested_ops->get_state)
4684                         break;
4685
4686                 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
4687                 r = -EFAULT;
4688                 if (get_user(user_data_size, &user_kvm_nested_state->size))
4689                         break;
4690
4691                 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
4692                                                      user_data_size);
4693                 if (r < 0)
4694                         break;
4695
4696                 if (r > user_data_size) {
4697                         if (put_user(r, &user_kvm_nested_state->size))
4698                                 r = -EFAULT;
4699                         else
4700                                 r = -E2BIG;
4701                         break;
4702                 }
4703
4704                 r = 0;
4705                 break;
4706         }
4707         case KVM_SET_NESTED_STATE: {
4708                 struct kvm_nested_state __user *user_kvm_nested_state = argp;
4709                 struct kvm_nested_state kvm_state;
4710                 int idx;
4711
4712                 r = -EINVAL;
4713                 if (!kvm_x86_ops.nested_ops->set_state)
4714                         break;
4715
4716                 r = -EFAULT;
4717                 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
4718                         break;
4719
4720                 r = -EINVAL;
4721                 if (kvm_state.size < sizeof(kvm_state))
4722                         break;
4723
4724                 if (kvm_state.flags &
4725                     ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
4726                       | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
4727                       | KVM_STATE_NESTED_GIF_SET))
4728                         break;
4729
4730                 /* nested_run_pending implies guest_mode.  */
4731                 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
4732                     && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
4733                         break;
4734
4735                 idx = srcu_read_lock(&vcpu->kvm->srcu);
4736                 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
4737                 srcu_read_unlock(&vcpu->kvm->srcu, idx);
4738                 break;
4739         }
4740         case KVM_GET_SUPPORTED_HV_CPUID: {
4741                 struct kvm_cpuid2 __user *cpuid_arg = argp;
4742                 struct kvm_cpuid2 cpuid;
4743
4744                 r = -EFAULT;
4745                 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4746                         goto out;
4747
4748                 r = kvm_vcpu_ioctl_get_hv_cpuid(vcpu, &cpuid,
4749                                                 cpuid_arg->entries);
4750                 if (r)
4751                         goto out;
4752
4753                 r = -EFAULT;
4754                 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4755                         goto out;
4756                 r = 0;
4757                 break;
4758         }
4759         default:
4760                 r = -EINVAL;
4761         }
4762 out:
4763         kfree(u.buffer);
4764 out_nofree:
4765         vcpu_put(vcpu);
4766         return r;
4767 }
4768
4769 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
4770 {
4771         return VM_FAULT_SIGBUS;
4772 }
4773
4774 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
4775 {
4776         int ret;
4777
4778         if (addr > (unsigned int)(-3 * PAGE_SIZE))
4779                 return -EINVAL;
4780         ret = kvm_x86_ops.set_tss_addr(kvm, addr);
4781         return ret;
4782 }
4783
4784 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
4785                                               u64 ident_addr)
4786 {
4787         return kvm_x86_ops.set_identity_map_addr(kvm, ident_addr);
4788 }
4789
4790 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
4791                                          unsigned long kvm_nr_mmu_pages)
4792 {
4793         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
4794                 return -EINVAL;
4795
4796         mutex_lock(&kvm->slots_lock);
4797
4798         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
4799         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
4800
4801         mutex_unlock(&kvm->slots_lock);
4802         return 0;
4803 }
4804
4805 static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
4806 {
4807         return kvm->arch.n_max_mmu_pages;
4808 }
4809
4810 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4811 {
4812         struct kvm_pic *pic = kvm->arch.vpic;
4813         int r;
4814
4815         r = 0;
4816         switch (chip->chip_id) {
4817         case KVM_IRQCHIP_PIC_MASTER:
4818                 memcpy(&chip->chip.pic, &pic->pics[0],
4819                         sizeof(struct kvm_pic_state));
4820                 break;
4821         case KVM_IRQCHIP_PIC_SLAVE:
4822                 memcpy(&chip->chip.pic, &pic->pics[1],
4823                         sizeof(struct kvm_pic_state));
4824                 break;
4825         case KVM_IRQCHIP_IOAPIC:
4826                 kvm_get_ioapic(kvm, &chip->chip.ioapic);
4827                 break;
4828         default:
4829                 r = -EINVAL;
4830                 break;
4831         }
4832         return r;
4833 }
4834
4835 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
4836 {
4837         struct kvm_pic *pic = kvm->arch.vpic;
4838         int r;
4839
4840         r = 0;
4841         switch (chip->chip_id) {
4842         case KVM_IRQCHIP_PIC_MASTER:
4843                 spin_lock(&pic->lock);
4844                 memcpy(&pic->pics[0], &chip->chip.pic,
4845                         sizeof(struct kvm_pic_state));
4846                 spin_unlock(&pic->lock);
4847                 break;
4848         case KVM_IRQCHIP_PIC_SLAVE:
4849                 spin_lock(&pic->lock);
4850                 memcpy(&pic->pics[1], &chip->chip.pic,
4851                         sizeof(struct kvm_pic_state));
4852                 spin_unlock(&pic->lock);
4853                 break;
4854         case KVM_IRQCHIP_IOAPIC:
4855                 kvm_set_ioapic(kvm, &chip->chip.ioapic);
4856                 break;
4857         default:
4858                 r = -EINVAL;
4859                 break;
4860         }
4861         kvm_pic_update_irq(pic);
4862         return r;
4863 }
4864
4865 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4866 {
4867         struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
4868
4869         BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
4870
4871         mutex_lock(&kps->lock);
4872         memcpy(ps, &kps->channels, sizeof(*ps));
4873         mutex_unlock(&kps->lock);
4874         return 0;
4875 }
4876
4877 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
4878 {
4879         int i;
4880         struct kvm_pit *pit = kvm->arch.vpit;
4881
4882         mutex_lock(&pit->pit_state.lock);
4883         memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
4884         for (i = 0; i < 3; i++)
4885                 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
4886         mutex_unlock(&pit->pit_state.lock);
4887         return 0;
4888 }
4889
4890 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4891 {
4892         mutex_lock(&kvm->arch.vpit->pit_state.lock);
4893         memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
4894                 sizeof(ps->channels));
4895         ps->flags = kvm->arch.vpit->pit_state.flags;
4896         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
4897         memset(&ps->reserved, 0, sizeof(ps->reserved));
4898         return 0;
4899 }
4900
4901 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
4902 {
4903         int start = 0;
4904         int i;
4905         u32 prev_legacy, cur_legacy;
4906         struct kvm_pit *pit = kvm->arch.vpit;
4907
4908         mutex_lock(&pit->pit_state.lock);
4909         prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
4910         cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
4911         if (!prev_legacy && cur_legacy)
4912                 start = 1;
4913         memcpy(&pit->pit_state.channels, &ps->channels,
4914                sizeof(pit->pit_state.channels));
4915         pit->pit_state.flags = ps->flags;
4916         for (i = 0; i < 3; i++)
4917                 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
4918                                    start && i == 0);
4919         mutex_unlock(&pit->pit_state.lock);
4920         return 0;
4921 }
4922
4923 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
4924                                  struct kvm_reinject_control *control)
4925 {
4926         struct kvm_pit *pit = kvm->arch.vpit;
4927
4928         /* pit->pit_state.lock was overloaded to prevent userspace from getting
4929          * an inconsistent state after running multiple KVM_REINJECT_CONTROL
4930          * ioctls in parallel.  Use a separate lock if that ioctl isn't rare.
4931          */
4932         mutex_lock(&pit->pit_state.lock);
4933         kvm_pit_set_reinject(pit, control->pit_reinject);
4934         mutex_unlock(&pit->pit_state.lock);
4935
4936         return 0;
4937 }
4938
4939 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
4940 {
4941         /*
4942          * Flush potentially hardware-cached dirty pages to dirty_bitmap.
4943          */
4944         if (kvm_x86_ops.flush_log_dirty)
4945                 kvm_x86_ops.flush_log_dirty(kvm);
4946 }
4947
4948 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
4949                         bool line_status)
4950 {
4951         if (!irqchip_in_kernel(kvm))
4952                 return -ENXIO;
4953
4954         irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
4955                                         irq_event->irq, irq_event->level,
4956                                         line_status);
4957         return 0;
4958 }
4959
4960 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4961                             struct kvm_enable_cap *cap)
4962 {
4963         int r;
4964
4965         if (cap->flags)
4966                 return -EINVAL;
4967
4968         switch (cap->cap) {
4969         case KVM_CAP_DISABLE_QUIRKS:
4970                 kvm->arch.disabled_quirks = cap->args[0];
4971                 r = 0;
4972                 break;
4973         case KVM_CAP_SPLIT_IRQCHIP: {
4974                 mutex_lock(&kvm->lock);
4975                 r = -EINVAL;
4976                 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
4977                         goto split_irqchip_unlock;
4978                 r = -EEXIST;
4979                 if (irqchip_in_kernel(kvm))
4980                         goto split_irqchip_unlock;
4981                 if (kvm->created_vcpus)
4982                         goto split_irqchip_unlock;
4983                 r = kvm_setup_empty_irq_routing(kvm);
4984                 if (r)
4985                         goto split_irqchip_unlock;
4986                 /* Pairs with irqchip_in_kernel. */
4987                 smp_wmb();
4988                 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
4989                 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
4990                 r = 0;
4991 split_irqchip_unlock:
4992                 mutex_unlock(&kvm->lock);
4993                 break;
4994         }
4995         case KVM_CAP_X2APIC_API:
4996                 r = -EINVAL;
4997                 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
4998                         break;
4999
5000                 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
5001                         kvm->arch.x2apic_format = true;
5002                 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
5003                         kvm->arch.x2apic_broadcast_quirk_disabled = true;
5004
5005                 r = 0;
5006                 break;
5007         case KVM_CAP_X86_DISABLE_EXITS:
5008                 r = -EINVAL;
5009                 if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
5010                         break;
5011
5012                 if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
5013                         kvm_can_mwait_in_guest())
5014                         kvm->arch.mwait_in_guest = true;
5015                 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
5016                         kvm->arch.hlt_in_guest = true;
5017                 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
5018                         kvm->arch.pause_in_guest = true;
5019                 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
5020                         kvm->arch.cstate_in_guest = true;
5021                 r = 0;
5022                 break;
5023         case KVM_CAP_MSR_PLATFORM_INFO:
5024                 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
5025                 r = 0;
5026                 break;
5027         case KVM_CAP_EXCEPTION_PAYLOAD:
5028                 kvm->arch.exception_payload_enabled = cap->args[0];
5029                 r = 0;
5030                 break;
5031         default:
5032                 r = -EINVAL;
5033                 break;
5034         }
5035         return r;
5036 }
5037
5038 long kvm_arch_vm_ioctl(struct file *filp,
5039                        unsigned int ioctl, unsigned long arg)
5040 {
5041         struct kvm *kvm = filp->private_data;
5042         void __user *argp = (void __user *)arg;
5043         int r = -ENOTTY;
5044         /*
5045          * This union makes it completely explicit to gcc-3.x
5046          * that these two variables' stack usage should be
5047          * combined, not added together.
5048          */
5049         union {
5050                 struct kvm_pit_state ps;
5051                 struct kvm_pit_state2 ps2;
5052                 struct kvm_pit_config pit_config;
5053         } u;
5054
5055         switch (ioctl) {
5056         case KVM_SET_TSS_ADDR:
5057                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
5058                 break;
5059         case KVM_SET_IDENTITY_MAP_ADDR: {
5060                 u64 ident_addr;
5061
5062                 mutex_lock(&kvm->lock);
5063                 r = -EINVAL;
5064                 if (kvm->created_vcpus)
5065                         goto set_identity_unlock;
5066                 r = -EFAULT;
5067                 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
5068                         goto set_identity_unlock;
5069                 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
5070 set_identity_unlock:
5071                 mutex_unlock(&kvm->lock);
5072                 break;
5073         }
5074         case KVM_SET_NR_MMU_PAGES:
5075                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
5076                 break;
5077         case KVM_GET_NR_MMU_PAGES:
5078                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
5079                 break;
5080         case KVM_CREATE_IRQCHIP: {
5081                 mutex_lock(&kvm->lock);
5082
5083                 r = -EEXIST;
5084                 if (irqchip_in_kernel(kvm))
5085                         goto create_irqchip_unlock;
5086
5087                 r = -EINVAL;
5088                 if (kvm->created_vcpus)
5089                         goto create_irqchip_unlock;
5090
5091                 r = kvm_pic_init(kvm);
5092                 if (r)
5093                         goto create_irqchip_unlock;
5094
5095                 r = kvm_ioapic_init(kvm);
5096                 if (r) {
5097                         kvm_pic_destroy(kvm);
5098                         goto create_irqchip_unlock;
5099                 }
5100
5101                 r = kvm_setup_default_irq_routing(kvm);
5102                 if (r) {
5103                         kvm_ioapic_destroy(kvm);
5104                         kvm_pic_destroy(kvm);
5105                         goto create_irqchip_unlock;
5106                 }
5107                 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
5108                 smp_wmb();
5109                 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
5110         create_irqchip_unlock:
5111                 mutex_unlock(&kvm->lock);
5112                 break;
5113         }
5114         case KVM_CREATE_PIT:
5115                 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
5116                 goto create_pit;
5117         case KVM_CREATE_PIT2:
5118                 r = -EFAULT;
5119                 if (copy_from_user(&u.pit_config, argp,
5120                                    sizeof(struct kvm_pit_config)))
5121                         goto out;
5122         create_pit:
5123                 mutex_lock(&kvm->lock);
5124                 r = -EEXIST;
5125                 if (kvm->arch.vpit)
5126                         goto create_pit_unlock;
5127                 r = -ENOMEM;
5128                 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
5129                 if (kvm->arch.vpit)
5130                         r = 0;
5131         create_pit_unlock:
5132                 mutex_unlock(&kvm->lock);
5133                 break;
5134         case KVM_GET_IRQCHIP: {
5135                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5136                 struct kvm_irqchip *chip;
5137
5138                 chip = memdup_user(argp, sizeof(*chip));
5139                 if (IS_ERR(chip)) {
5140                         r = PTR_ERR(chip);
5141                         goto out;
5142                 }
5143
5144                 r = -ENXIO;
5145                 if (!irqchip_kernel(kvm))
5146                         goto get_irqchip_out;
5147                 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
5148                 if (r)
5149                         goto get_irqchip_out;
5150                 r = -EFAULT;
5151                 if (copy_to_user(argp, chip, sizeof(*chip)))
5152                         goto get_irqchip_out;
5153                 r = 0;
5154         get_irqchip_out:
5155                 kfree(chip);
5156                 break;
5157         }
5158         case KVM_SET_IRQCHIP: {
5159                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
5160                 struct kvm_irqchip *chip;
5161
5162                 chip = memdup_user(argp, sizeof(*chip));
5163                 if (IS_ERR(chip)) {
5164                         r = PTR_ERR(chip);
5165                         goto out;
5166                 }
5167
5168                 r = -ENXIO;
5169                 if (!irqchip_kernel(kvm))
5170                         goto set_irqchip_out;
5171                 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
5172         set_irqchip_out:
5173                 kfree(chip);
5174                 break;
5175         }
5176         case KVM_GET_PIT: {
5177                 r = -EFAULT;
5178                 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
5179                         goto out;
5180                 r = -ENXIO;
5181                 if (!kvm->arch.vpit)
5182                         goto out;
5183                 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
5184                 if (r)
5185                         goto out;
5186                 r = -EFAULT;
5187                 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
5188                         goto out;
5189                 r = 0;
5190                 break;
5191         }
5192         case KVM_SET_PIT: {
5193                 r = -EFAULT;
5194                 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
5195                         goto out;
5196                 mutex_lock(&kvm->lock);
5197                 r = -ENXIO;
5198                 if (!kvm->arch.vpit)
5199                         goto set_pit_out;
5200                 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
5201 set_pit_out:
5202                 mutex_unlock(&kvm->lock);
5203                 break;
5204         }
5205         case KVM_GET_PIT2: {
5206                 r = -ENXIO;
5207                 if (!kvm->arch.vpit)
5208                         goto out;
5209                 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
5210                 if (r)
5211                         goto out;
5212                 r = -EFAULT;
5213                 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
5214                         goto out;
5215                 r = 0;
5216                 break;
5217         }
5218         case KVM_SET_PIT2: {
5219                 r = -EFAULT;
5220                 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
5221                         goto out;
5222                 mutex_lock(&kvm->lock);
5223                 r = -ENXIO;
5224                 if (!kvm->arch.vpit)
5225                         goto set_pit2_out;
5226                 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
5227 set_pit2_out:
5228                 mutex_unlock(&kvm->lock);
5229                 break;
5230         }
5231         case KVM_REINJECT_CONTROL: {
5232                 struct kvm_reinject_control control;
5233                 r =  -EFAULT;
5234                 if (copy_from_user(&control, argp, sizeof(control)))
5235                         goto out;
5236                 r = -ENXIO;
5237                 if (!kvm->arch.vpit)
5238                         goto out;
5239                 r = kvm_vm_ioctl_reinject(kvm, &control);
5240                 break;
5241         }
5242         case KVM_SET_BOOT_CPU_ID:
5243                 r = 0;
5244                 mutex_lock(&kvm->lock);
5245                 if (kvm->created_vcpus)
5246                         r = -EBUSY;
5247                 else
5248                         kvm->arch.bsp_vcpu_id = arg;
5249                 mutex_unlock(&kvm->lock);
5250                 break;
5251         case KVM_XEN_HVM_CONFIG: {
5252                 struct kvm_xen_hvm_config xhc;
5253                 r = -EFAULT;
5254                 if (copy_from_user(&xhc, argp, sizeof(xhc)))
5255                         goto out;
5256                 r = -EINVAL;
5257                 if (xhc.flags)
5258                         goto out;
5259                 memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
5260                 r = 0;
5261                 break;
5262         }
5263         case KVM_SET_CLOCK: {
5264                 struct kvm_clock_data user_ns;
5265                 u64 now_ns;
5266
5267                 r = -EFAULT;
5268                 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
5269                         goto out;
5270
5271                 r = -EINVAL;
5272                 if (user_ns.flags)
5273                         goto out;
5274
5275                 r = 0;
5276                 /*
5277                  * TODO: userspace has to take care of races with VCPU_RUN, so
5278                  * kvm_gen_update_masterclock() can be cut down to locked
5279                  * pvclock_update_vm_gtod_copy().
5280                  */
5281                 kvm_gen_update_masterclock(kvm);
5282                 now_ns = get_kvmclock_ns(kvm);
5283                 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
5284                 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
5285                 break;
5286         }
5287         case KVM_GET_CLOCK: {
5288                 struct kvm_clock_data user_ns;
5289                 u64 now_ns;
5290
5291                 now_ns = get_kvmclock_ns(kvm);
5292                 user_ns.clock = now_ns;
5293                 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
5294                 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
5295
5296                 r = -EFAULT;
5297                 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
5298                         goto out;
5299                 r = 0;
5300                 break;
5301         }
5302         case KVM_MEMORY_ENCRYPT_OP: {
5303                 r = -ENOTTY;
5304                 if (kvm_x86_ops.mem_enc_op)
5305                         r = kvm_x86_ops.mem_enc_op(kvm, argp);
5306                 break;
5307         }
5308         case KVM_MEMORY_ENCRYPT_REG_REGION: {
5309                 struct kvm_enc_region region;
5310
5311                 r = -EFAULT;
5312                 if (copy_from_user(&region, argp, sizeof(region)))
5313                         goto out;
5314
5315                 r = -ENOTTY;
5316                 if (kvm_x86_ops.mem_enc_reg_region)
5317                         r = kvm_x86_ops.mem_enc_reg_region(kvm, &region);
5318                 break;
5319         }
5320         case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
5321                 struct kvm_enc_region region;
5322
5323                 r = -EFAULT;
5324                 if (copy_from_user(&region, argp, sizeof(region)))
5325                         goto out;
5326
5327                 r = -ENOTTY;
5328                 if (kvm_x86_ops.mem_enc_unreg_region)
5329                         r = kvm_x86_ops.mem_enc_unreg_region(kvm, &region);
5330                 break;
5331         }
5332         case KVM_HYPERV_EVENTFD: {
5333                 struct kvm_hyperv_eventfd hvevfd;
5334
5335                 r = -EFAULT;
5336                 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
5337                         goto out;
5338                 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
5339                 break;
5340         }
5341         case KVM_SET_PMU_EVENT_FILTER:
5342                 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
5343                 break;
5344         default:
5345                 r = -ENOTTY;
5346         }
5347 out:
5348         return r;
5349 }
5350
5351 static void kvm_init_msr_list(void)
5352 {
5353         struct x86_pmu_capability x86_pmu;
5354         u32 dummy[2];
5355         unsigned i;
5356
5357         BUILD_BUG_ON_MSG(INTEL_PMC_MAX_FIXED != 4,
5358                          "Please update the fixed PMCs in msrs_to_saved_all[]");
5359
5360         perf_get_x86_pmu_capability(&x86_pmu);
5361
5362         num_msrs_to_save = 0;
5363         num_emulated_msrs = 0;
5364         num_msr_based_features = 0;
5365
5366         for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
5367                 if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
5368                         continue;
5369
5370                 /*
5371                  * Even MSRs that are valid in the host may not be exposed
5372                  * to the guests in some cases.
5373                  */
5374                 switch (msrs_to_save_all[i]) {
5375                 case MSR_IA32_BNDCFGS:
5376                         if (!kvm_mpx_supported())
5377                                 continue;
5378                         break;
5379                 case MSR_TSC_AUX:
5380                         if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP))
5381                                 continue;
5382                         break;
5383                 case MSR_IA32_UMWAIT_CONTROL:
5384                         if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
5385                                 continue;
5386                         break;
5387                 case MSR_IA32_RTIT_CTL:
5388                 case MSR_IA32_RTIT_STATUS:
5389                         if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
5390                                 continue;
5391                         break;
5392                 case MSR_IA32_RTIT_CR3_MATCH:
5393                         if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5394                             !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
5395                                 continue;
5396                         break;
5397                 case MSR_IA32_RTIT_OUTPUT_BASE:
5398                 case MSR_IA32_RTIT_OUTPUT_MASK:
5399                         if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5400                                 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
5401                                  !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
5402                                 continue;
5403                         break;
5404                 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
5405                         if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
5406                                 msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
5407                                 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
5408                                 continue;
5409                         break;
5410                 case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR0 + 17:
5411                         if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
5412                             min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5413                                 continue;
5414                         break;
5415                 case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL0 + 17:
5416                         if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
5417                             min(INTEL_PMC_MAX_GENERIC, x86_pmu.num_counters_gp))
5418                                 continue;
5419                         break;
5420                 default:
5421                         break;
5422                 }
5423
5424                 msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
5425         }
5426
5427         for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
5428                 if (!kvm_x86_ops.has_emulated_msr(emulated_msrs_all[i]))
5429                         continue;
5430
5431                 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
5432         }
5433
5434         for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
5435                 struct kvm_msr_entry msr;
5436
5437                 msr.index = msr_based_features_all[i];
5438                 if (kvm_get_msr_feature(&msr))
5439                         continue;
5440
5441                 msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
5442         }
5443 }
5444
5445 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
5446                            const void *v)
5447 {
5448         int handled = 0;
5449         int n;
5450
5451         do {
5452                 n = min(len, 8);
5453                 if (!(lapic_in_kernel(vcpu) &&
5454                       !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
5455                     && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
5456                         break;
5457                 handled += n;
5458                 addr += n;
5459                 len -= n;
5460                 v += n;
5461         } while (len);
5462
5463         return handled;
5464 }
5465
5466 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
5467 {
5468         int handled = 0;
5469         int n;
5470
5471         do {
5472                 n = min(len, 8);
5473                 if (!(lapic_in_kernel(vcpu) &&
5474                       !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
5475                                          addr, n, v))
5476                     && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
5477                         break;
5478                 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
5479                 handled += n;
5480                 addr += n;
5481                 len -= n;
5482                 v += n;
5483         } while (len);
5484
5485         return handled;
5486 }
5487
5488 static void kvm_set_segment(struct kvm_vcpu *vcpu,
5489                         struct kvm_segment *var, int seg)
5490 {
5491         kvm_x86_ops.set_segment(vcpu, var, seg);
5492 }
5493
5494 void kvm_get_segment(struct kvm_vcpu *vcpu,
5495                      struct kvm_segment *var, int seg)
5496 {
5497         kvm_x86_ops.get_segment(vcpu, var, seg);
5498 }
5499
5500 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
5501                            struct x86_exception *exception)
5502 {
5503         gpa_t t_gpa;
5504
5505         BUG_ON(!mmu_is_nested(vcpu));
5506
5507         /* NPT walks are always user-walks */
5508         access |= PFERR_USER_MASK;
5509         t_gpa  = vcpu->arch.mmu->gva_to_gpa(vcpu, gpa, access, exception);
5510
5511         return t_gpa;
5512 }
5513
5514 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
5515                               struct x86_exception *exception)
5516 {
5517         u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5518         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5519 }
5520
5521  gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
5522                                 struct x86_exception *exception)
5523 {
5524         u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5525         access |= PFERR_FETCH_MASK;
5526         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5527 }
5528
5529 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
5530                                struct x86_exception *exception)
5531 {
5532         u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5533         access |= PFERR_WRITE_MASK;
5534         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5535 }
5536
5537 /* uses this to access any guest's mapped memory without checking CPL */
5538 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
5539                                 struct x86_exception *exception)
5540 {
5541         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
5542 }
5543
5544 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5545                                       struct kvm_vcpu *vcpu, u32 access,
5546                                       struct x86_exception *exception)
5547 {
5548         void *data = val;
5549         int r = X86EMUL_CONTINUE;
5550
5551         while (bytes) {
5552                 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
5553                                                             exception);
5554                 unsigned offset = addr & (PAGE_SIZE-1);
5555                 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
5556                 int ret;
5557
5558                 if (gpa == UNMAPPED_GVA)
5559                         return X86EMUL_PROPAGATE_FAULT;
5560                 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
5561                                                offset, toread);
5562                 if (ret < 0) {
5563                         r = X86EMUL_IO_NEEDED;
5564                         goto out;
5565                 }
5566
5567                 bytes -= toread;
5568                 data += toread;
5569                 addr += toread;
5570         }
5571 out:
5572         return r;
5573 }
5574
5575 /* used for instruction fetching */
5576 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
5577                                 gva_t addr, void *val, unsigned int bytes,
5578                                 struct x86_exception *exception)
5579 {
5580         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5581         u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5582         unsigned offset;
5583         int ret;
5584
5585         /* Inline kvm_read_guest_virt_helper for speed.  */
5586         gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
5587                                                     exception);
5588         if (unlikely(gpa == UNMAPPED_GVA))
5589                 return X86EMUL_PROPAGATE_FAULT;
5590
5591         offset = addr & (PAGE_SIZE-1);
5592         if (WARN_ON(offset + bytes > PAGE_SIZE))
5593                 bytes = (unsigned)PAGE_SIZE - offset;
5594         ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
5595                                        offset, bytes);
5596         if (unlikely(ret < 0))
5597                 return X86EMUL_IO_NEEDED;
5598
5599         return X86EMUL_CONTINUE;
5600 }
5601
5602 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
5603                                gva_t addr, void *val, unsigned int bytes,
5604                                struct x86_exception *exception)
5605 {
5606         u32 access = (kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
5607
5608         /*
5609          * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
5610          * is returned, but our callers are not ready for that and they blindly
5611          * call kvm_inject_page_fault.  Ensure that they at least do not leak
5612          * uninitialized kernel stack memory into cr2 and error code.
5613          */
5614         memset(exception, 0, sizeof(*exception));
5615         return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
5616                                           exception);
5617 }
5618 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
5619
5620 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
5621                              gva_t addr, void *val, unsigned int bytes,
5622                              struct x86_exception *exception, bool system)
5623 {
5624         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5625         u32 access = 0;
5626
5627         if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
5628                 access |= PFERR_USER_MASK;
5629
5630         return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
5631 }
5632
5633 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
5634                 unsigned long addr, void *val, unsigned int bytes)
5635 {
5636         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5637         int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
5638
5639         return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
5640 }
5641
5642 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
5643                                       struct kvm_vcpu *vcpu, u32 access,
5644                                       struct x86_exception *exception)
5645 {
5646         void *data = val;
5647         int r = X86EMUL_CONTINUE;
5648
5649         while (bytes) {
5650                 gpa_t gpa =  vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
5651                                                              access,
5652                                                              exception);
5653                 unsigned offset = addr & (PAGE_SIZE-1);
5654                 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
5655                 int ret;
5656
5657                 if (gpa == UNMAPPED_GVA)
5658                         return X86EMUL_PROPAGATE_FAULT;
5659                 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
5660                 if (ret < 0) {
5661                         r = X86EMUL_IO_NEEDED;
5662                         goto out;
5663                 }
5664
5665                 bytes -= towrite;
5666                 data += towrite;
5667                 addr += towrite;
5668         }
5669 out:
5670         return r;
5671 }
5672
5673 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
5674                               unsigned int bytes, struct x86_exception *exception,
5675                               bool system)
5676 {
5677         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5678         u32 access = PFERR_WRITE_MASK;
5679
5680         if (!system && kvm_x86_ops.get_cpl(vcpu) == 3)
5681                 access |= PFERR_USER_MASK;
5682
5683         return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5684                                            access, exception);
5685 }
5686
5687 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
5688                                 unsigned int bytes, struct x86_exception *exception)
5689 {
5690         /* kvm_write_guest_virt_system can pull in tons of pages. */
5691         vcpu->arch.l1tf_flush_l1d = true;
5692
5693         return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
5694                                            PFERR_WRITE_MASK, exception);
5695 }
5696 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
5697
5698 int handle_ud(struct kvm_vcpu *vcpu)
5699 {
5700         static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
5701         int emul_type = EMULTYPE_TRAP_UD;
5702         char sig[5]; /* ud2; .ascii "kvm" */
5703         struct x86_exception e;
5704
5705         if (force_emulation_prefix &&
5706             kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
5707                                 sig, sizeof(sig), &e) == 0 &&
5708             memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
5709                 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
5710                 emul_type = EMULTYPE_TRAP_UD_FORCED;
5711         }
5712
5713         return kvm_emulate_instruction(vcpu, emul_type);
5714 }
5715 EXPORT_SYMBOL_GPL(handle_ud);
5716
5717 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5718                             gpa_t gpa, bool write)
5719 {
5720         /* For APIC access vmexit */
5721         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
5722                 return 1;
5723
5724         if (vcpu_match_mmio_gpa(vcpu, gpa)) {
5725                 trace_vcpu_match_mmio(gva, gpa, write, true);
5726                 return 1;
5727         }
5728
5729         return 0;
5730 }
5731
5732 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
5733                                 gpa_t *gpa, struct x86_exception *exception,
5734                                 bool write)
5735 {
5736         u32 access = ((kvm_x86_ops.get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
5737                 | (write ? PFERR_WRITE_MASK : 0);
5738
5739         /*
5740          * currently PKRU is only applied to ept enabled guest so
5741          * there is no pkey in EPT page table for L1 guest or EPT
5742          * shadow page table for L2 guest.
5743          */
5744         if (vcpu_match_mmio_gva(vcpu, gva)
5745             && !permission_fault(vcpu, vcpu->arch.walk_mmu,
5746                                  vcpu->arch.mmio_access, 0, access)) {
5747                 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
5748                                         (gva & (PAGE_SIZE - 1));
5749                 trace_vcpu_match_mmio(gva, *gpa, write, false);
5750                 return 1;
5751         }
5752
5753         *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
5754
5755         if (*gpa == UNMAPPED_GVA)
5756                 return -1;
5757
5758         return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
5759 }
5760
5761 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
5762                         const void *val, int bytes)
5763 {
5764         int ret;
5765
5766         ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
5767         if (ret < 0)
5768                 return 0;
5769         kvm_page_track_write(vcpu, gpa, val, bytes);
5770         return 1;
5771 }
5772
5773 struct read_write_emulator_ops {
5774         int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
5775                                   int bytes);
5776         int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
5777                                   void *val, int bytes);
5778         int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5779                                int bytes, void *val);
5780         int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
5781                                     void *val, int bytes);
5782         bool write;
5783 };
5784
5785 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
5786 {
5787         if (vcpu->mmio_read_completed) {
5788                 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
5789                                vcpu->mmio_fragments[0].gpa, val);
5790                 vcpu->mmio_read_completed = 0;
5791                 return 1;
5792         }
5793
5794         return 0;
5795 }
5796
5797 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5798                         void *val, int bytes)
5799 {
5800         return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
5801 }
5802
5803 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
5804                          void *val, int bytes)
5805 {
5806         return emulator_write_phys(vcpu, gpa, val, bytes);
5807 }
5808
5809 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
5810 {
5811         trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
5812         return vcpu_mmio_write(vcpu, gpa, bytes, val);
5813 }
5814
5815 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5816                           void *val, int bytes)
5817 {
5818         trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
5819         return X86EMUL_IO_NEEDED;
5820 }
5821
5822 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
5823                            void *val, int bytes)
5824 {
5825         struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
5826
5827         memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
5828         return X86EMUL_CONTINUE;
5829 }
5830
5831 static const struct read_write_emulator_ops read_emultor = {
5832         .read_write_prepare = read_prepare,
5833         .read_write_emulate = read_emulate,
5834         .read_write_mmio = vcpu_mmio_read,
5835         .read_write_exit_mmio = read_exit_mmio,
5836 };
5837
5838 static const struct read_write_emulator_ops write_emultor = {
5839         .read_write_emulate = write_emulate,
5840         .read_write_mmio = write_mmio,
5841         .read_write_exit_mmio = write_exit_mmio,
5842         .write = true,
5843 };
5844
5845 static int emulator_read_write_onepage(unsigned long addr, void *val,
5846                                        unsigned int bytes,
5847                                        struct x86_exception *exception,
5848                                        struct kvm_vcpu *vcpu,
5849                                        const struct read_write_emulator_ops *ops)
5850 {
5851         gpa_t gpa;
5852         int handled, ret;
5853         bool write = ops->write;
5854         struct kvm_mmio_fragment *frag;
5855         struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
5856
5857         /*
5858          * If the exit was due to a NPF we may already have a GPA.
5859          * If the GPA is present, use it to avoid the GVA to GPA table walk.
5860          * Note, this cannot be used on string operations since string
5861          * operation using rep will only have the initial GPA from the NPF
5862          * occurred.
5863          */
5864         if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
5865             (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
5866                 gpa = ctxt->gpa_val;
5867                 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
5868         } else {
5869                 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
5870                 if (ret < 0)
5871                         return X86EMUL_PROPAGATE_FAULT;
5872         }
5873
5874         if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
5875                 return X86EMUL_CONTINUE;
5876
5877         /*
5878          * Is this MMIO handled locally?
5879          */
5880         handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
5881         if (handled == bytes)
5882                 return X86EMUL_CONTINUE;
5883
5884         gpa += handled;
5885         bytes -= handled;
5886         val += handled;
5887
5888         WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
5889         frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
5890         frag->gpa = gpa;
5891         frag->data = val;
5892         frag->len = bytes;
5893         return X86EMUL_CONTINUE;
5894 }
5895
5896 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
5897                         unsigned long addr,
5898                         void *val, unsigned int bytes,
5899                         struct x86_exception *exception,
5900                         const struct read_write_emulator_ops *ops)
5901 {
5902         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5903         gpa_t gpa;
5904         int rc;
5905
5906         if (ops->read_write_prepare &&
5907                   ops->read_write_prepare(vcpu, val, bytes))
5908                 return X86EMUL_CONTINUE;
5909
5910         vcpu->mmio_nr_fragments = 0;
5911
5912         /* Crossing a page boundary? */
5913         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
5914                 int now;
5915
5916                 now = -addr & ~PAGE_MASK;
5917                 rc = emulator_read_write_onepage(addr, val, now, exception,
5918                                                  vcpu, ops);
5919
5920                 if (rc != X86EMUL_CONTINUE)
5921                         return rc;
5922                 addr += now;
5923                 if (ctxt->mode != X86EMUL_MODE_PROT64)
5924                         addr = (u32)addr;
5925                 val += now;
5926                 bytes -= now;
5927         }
5928
5929         rc = emulator_read_write_onepage(addr, val, bytes, exception,
5930                                          vcpu, ops);
5931         if (rc != X86EMUL_CONTINUE)
5932                 return rc;
5933
5934         if (!vcpu->mmio_nr_fragments)
5935                 return rc;
5936
5937         gpa = vcpu->mmio_fragments[0].gpa;
5938
5939         vcpu->mmio_needed = 1;
5940         vcpu->mmio_cur_fragment = 0;
5941
5942         vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
5943         vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
5944         vcpu->run->exit_reason = KVM_EXIT_MMIO;
5945         vcpu->run->mmio.phys_addr = gpa;
5946
5947         return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
5948 }
5949
5950 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
5951                                   unsigned long addr,
5952                                   void *val,
5953                                   unsigned int bytes,
5954                                   struct x86_exception *exception)
5955 {
5956         return emulator_read_write(ctxt, addr, val, bytes,
5957                                    exception, &read_emultor);
5958 }
5959
5960 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
5961                             unsigned long addr,
5962                             const void *val,
5963                             unsigned int bytes,
5964                             struct x86_exception *exception)
5965 {
5966         return emulator_read_write(ctxt, addr, (void *)val, bytes,
5967                                    exception, &write_emultor);
5968 }
5969
5970 #define CMPXCHG_TYPE(t, ptr, old, new) \
5971         (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
5972
5973 #ifdef CONFIG_X86_64
5974 #  define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
5975 #else
5976 #  define CMPXCHG64(ptr, old, new) \
5977         (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
5978 #endif
5979
5980 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
5981                                      unsigned long addr,
5982                                      const void *old,
5983                                      const void *new,
5984                                      unsigned int bytes,
5985                                      struct x86_exception *exception)
5986 {
5987         struct kvm_host_map map;
5988         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5989         u64 page_line_mask;
5990         gpa_t gpa;
5991         char *kaddr;
5992         bool exchanged;
5993
5994         /* guests cmpxchg8b have to be emulated atomically */
5995         if (bytes > 8 || (bytes & (bytes - 1)))
5996                 goto emul_write;
5997
5998         gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
5999
6000         if (gpa == UNMAPPED_GVA ||
6001             (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
6002                 goto emul_write;
6003
6004         /*
6005          * Emulate the atomic as a straight write to avoid #AC if SLD is
6006          * enabled in the host and the access splits a cache line.
6007          */
6008         if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
6009                 page_line_mask = ~(cache_line_size() - 1);
6010         else
6011                 page_line_mask = PAGE_MASK;
6012
6013         if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
6014                 goto emul_write;
6015
6016         if (kvm_vcpu_map(vcpu, gpa_to_gfn(gpa), &map))
6017                 goto emul_write;
6018
6019         kaddr = map.hva + offset_in_page(gpa);
6020
6021         switch (bytes) {
6022         case 1:
6023                 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
6024                 break;
6025         case 2:
6026                 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
6027                 break;
6028         case 4:
6029                 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
6030                 break;
6031         case 8:
6032                 exchanged = CMPXCHG64(kaddr, old, new);
6033                 break;
6034         default:
6035                 BUG();
6036         }
6037
6038         kvm_vcpu_unmap(vcpu, &map, true);
6039
6040         if (!exchanged)
6041                 return X86EMUL_CMPXCHG_FAILED;
6042
6043         kvm_page_track_write(vcpu, gpa, new, bytes);
6044
6045         return X86EMUL_CONTINUE;
6046
6047 emul_write:
6048         printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
6049
6050         return emulator_write_emulated(ctxt, addr, new, bytes, exception);
6051 }
6052
6053 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
6054 {
6055         int r = 0, i;
6056
6057         for (i = 0; i < vcpu->arch.pio.count; i++) {
6058                 if (vcpu->arch.pio.in)
6059                         r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
6060                                             vcpu->arch.pio.size, pd);
6061                 else
6062                         r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
6063                                              vcpu->arch.pio.port, vcpu->arch.pio.size,
6064                                              pd);
6065                 if (r)
6066                         break;
6067                 pd += vcpu->arch.pio.size;
6068         }
6069         return r;
6070 }
6071
6072 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
6073                                unsigned short port, void *val,
6074                                unsigned int count, bool in)
6075 {
6076         vcpu->arch.pio.port = port;
6077         vcpu->arch.pio.in = in;
6078         vcpu->arch.pio.count  = count;
6079         vcpu->arch.pio.size = size;
6080
6081         if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
6082                 vcpu->arch.pio.count = 0;
6083                 return 1;
6084         }
6085
6086         vcpu->run->exit_reason = KVM_EXIT_IO;
6087         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
6088         vcpu->run->io.size = size;
6089         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
6090         vcpu->run->io.count = count;
6091         vcpu->run->io.port = port;
6092
6093         return 0;
6094 }
6095
6096 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
6097                            unsigned short port, void *val, unsigned int count)
6098 {
6099         int ret;
6100
6101         if (vcpu->arch.pio.count)
6102                 goto data_avail;
6103
6104         memset(vcpu->arch.pio_data, 0, size * count);
6105
6106         ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
6107         if (ret) {
6108 data_avail:
6109                 memcpy(val, vcpu->arch.pio_data, size * count);
6110                 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
6111                 vcpu->arch.pio.count = 0;
6112                 return 1;
6113         }
6114
6115         return 0;
6116 }
6117
6118 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
6119                                     int size, unsigned short port, void *val,
6120                                     unsigned int count)
6121 {
6122         return emulator_pio_in(emul_to_vcpu(ctxt), size, port, val, count);
6123
6124 }
6125
6126 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
6127                             unsigned short port, const void *val,
6128                             unsigned int count)
6129 {
6130         memcpy(vcpu->arch.pio_data, val, size * count);
6131         trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
6132         return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
6133 }
6134
6135 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
6136                                      int size, unsigned short port,
6137                                      const void *val, unsigned int count)
6138 {
6139         return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
6140 }
6141
6142 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
6143 {
6144         return kvm_x86_ops.get_segment_base(vcpu, seg);
6145 }
6146
6147 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
6148 {
6149         kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
6150 }
6151
6152 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
6153 {
6154         if (!need_emulate_wbinvd(vcpu))
6155                 return X86EMUL_CONTINUE;
6156
6157         if (kvm_x86_ops.has_wbinvd_exit()) {
6158                 int cpu = get_cpu();
6159
6160                 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
6161                 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
6162                                 wbinvd_ipi, NULL, 1);
6163                 put_cpu();
6164                 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
6165         } else
6166                 wbinvd();
6167         return X86EMUL_CONTINUE;
6168 }
6169
6170 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
6171 {
6172         kvm_emulate_wbinvd_noskip(vcpu);
6173         return kvm_skip_emulated_instruction(vcpu);
6174 }
6175 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
6176
6177
6178
6179 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
6180 {
6181         kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
6182 }
6183
6184 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
6185                            unsigned long *dest)
6186 {
6187         return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
6188 }
6189
6190 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
6191                            unsigned long value)
6192 {
6193
6194         return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
6195 }
6196
6197 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
6198 {
6199         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
6200 }
6201
6202 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
6203 {
6204         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6205         unsigned long value;
6206
6207         switch (cr) {
6208         case 0:
6209                 value = kvm_read_cr0(vcpu);
6210                 break;
6211         case 2:
6212                 value = vcpu->arch.cr2;
6213                 break;
6214         case 3:
6215                 value = kvm_read_cr3(vcpu);
6216                 break;
6217         case 4:
6218                 value = kvm_read_cr4(vcpu);
6219                 break;
6220         case 8:
6221                 value = kvm_get_cr8(vcpu);
6222                 break;
6223         default:
6224                 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6225                 return 0;
6226         }
6227
6228         return value;
6229 }
6230
6231 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
6232 {
6233         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6234         int res = 0;
6235
6236         switch (cr) {
6237         case 0:
6238                 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
6239                 break;
6240         case 2:
6241                 vcpu->arch.cr2 = val;
6242                 break;
6243         case 3:
6244                 res = kvm_set_cr3(vcpu, val);
6245                 break;
6246         case 4:
6247                 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
6248                 break;
6249         case 8:
6250                 res = kvm_set_cr8(vcpu, val);
6251                 break;
6252         default:
6253                 kvm_err("%s: unexpected cr %u\n", __func__, cr);
6254                 res = -1;
6255         }
6256
6257         return res;
6258 }
6259
6260 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
6261 {
6262         return kvm_x86_ops.get_cpl(emul_to_vcpu(ctxt));
6263 }
6264
6265 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6266 {
6267         kvm_x86_ops.get_gdt(emul_to_vcpu(ctxt), dt);
6268 }
6269
6270 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6271 {
6272         kvm_x86_ops.get_idt(emul_to_vcpu(ctxt), dt);
6273 }
6274
6275 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6276 {
6277         kvm_x86_ops.set_gdt(emul_to_vcpu(ctxt), dt);
6278 }
6279
6280 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
6281 {
6282         kvm_x86_ops.set_idt(emul_to_vcpu(ctxt), dt);
6283 }
6284
6285 static unsigned long emulator_get_cached_segment_base(
6286         struct x86_emulate_ctxt *ctxt, int seg)
6287 {
6288         return get_segment_base(emul_to_vcpu(ctxt), seg);
6289 }
6290
6291 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
6292                                  struct desc_struct *desc, u32 *base3,
6293                                  int seg)
6294 {
6295         struct kvm_segment var;
6296
6297         kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
6298         *selector = var.selector;
6299
6300         if (var.unusable) {
6301                 memset(desc, 0, sizeof(*desc));
6302                 if (base3)
6303                         *base3 = 0;
6304                 return false;
6305         }
6306
6307         if (var.g)
6308                 var.limit >>= 12;
6309         set_desc_limit(desc, var.limit);
6310         set_desc_base(desc, (unsigned long)var.base);
6311 #ifdef CONFIG_X86_64
6312         if (base3)
6313                 *base3 = var.base >> 32;
6314 #endif
6315         desc->type = var.type;
6316         desc->s = var.s;
6317         desc->dpl = var.dpl;
6318         desc->p = var.present;
6319         desc->avl = var.avl;
6320         desc->l = var.l;
6321         desc->d = var.db;
6322         desc->g = var.g;
6323
6324         return true;
6325 }
6326
6327 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
6328                                  struct desc_struct *desc, u32 base3,
6329                                  int seg)
6330 {
6331         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6332         struct kvm_segment var;
6333
6334         var.selector = selector;
6335         var.base = get_desc_base(desc);
6336 #ifdef CONFIG_X86_64
6337         var.base |= ((u64)base3) << 32;
6338 #endif
6339         var.limit = get_desc_limit(desc);
6340         if (desc->g)
6341                 var.limit = (var.limit << 12) | 0xfff;
6342         var.type = desc->type;
6343         var.dpl = desc->dpl;
6344         var.db = desc->d;
6345         var.s = desc->s;
6346         var.l = desc->l;
6347         var.g = desc->g;
6348         var.avl = desc->avl;
6349         var.present = desc->p;
6350         var.unusable = !var.present;
6351         var.padding = 0;
6352
6353         kvm_set_segment(vcpu, &var, seg);
6354         return;
6355 }
6356
6357 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
6358                             u32 msr_index, u64 *pdata)
6359 {
6360         return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
6361 }
6362
6363 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
6364                             u32 msr_index, u64 data)
6365 {
6366         return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
6367 }
6368
6369 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
6370 {
6371         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6372
6373         return vcpu->arch.smbase;
6374 }
6375
6376 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
6377 {
6378         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6379
6380         vcpu->arch.smbase = smbase;
6381 }
6382
6383 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
6384                               u32 pmc)
6385 {
6386         return kvm_pmu_is_valid_rdpmc_ecx(emul_to_vcpu(ctxt), pmc);
6387 }
6388
6389 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
6390                              u32 pmc, u64 *pdata)
6391 {
6392         return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
6393 }
6394
6395 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
6396 {
6397         emul_to_vcpu(ctxt)->arch.halt_request = 1;
6398 }
6399
6400 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
6401                               struct x86_instruction_info *info,
6402                               enum x86_intercept_stage stage)
6403 {
6404         return kvm_x86_ops.check_intercept(emul_to_vcpu(ctxt), info, stage,
6405                                             &ctxt->exception);
6406 }
6407
6408 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
6409                               u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
6410                               bool exact_only)
6411 {
6412         return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
6413 }
6414
6415 static bool emulator_guest_has_long_mode(struct x86_emulate_ctxt *ctxt)
6416 {
6417         return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_LM);
6418 }
6419
6420 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
6421 {
6422         return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
6423 }
6424
6425 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
6426 {
6427         return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
6428 }
6429
6430 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
6431 {
6432         return kvm_register_read(emul_to_vcpu(ctxt), reg);
6433 }
6434
6435 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
6436 {
6437         kvm_register_write(emul_to_vcpu(ctxt), reg, val);
6438 }
6439
6440 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
6441 {
6442         kvm_x86_ops.set_nmi_mask(emul_to_vcpu(ctxt), masked);
6443 }
6444
6445 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
6446 {
6447         return emul_to_vcpu(ctxt)->arch.hflags;
6448 }
6449
6450 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
6451 {
6452         emul_to_vcpu(ctxt)->arch.hflags = emul_flags;
6453 }
6454
6455 static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt,
6456                                   const char *smstate)
6457 {
6458         return kvm_x86_ops.pre_leave_smm(emul_to_vcpu(ctxt), smstate);
6459 }
6460
6461 static void emulator_post_leave_smm(struct x86_emulate_ctxt *ctxt)
6462 {
6463         kvm_smm_changed(emul_to_vcpu(ctxt));
6464 }
6465
6466 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
6467 {
6468         return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
6469 }
6470
6471 static const struct x86_emulate_ops emulate_ops = {
6472         .read_gpr            = emulator_read_gpr,
6473         .write_gpr           = emulator_write_gpr,
6474         .read_std            = emulator_read_std,
6475         .write_std           = emulator_write_std,
6476         .read_phys           = kvm_read_guest_phys_system,
6477         .fetch               = kvm_fetch_guest_virt,
6478         .read_emulated       = emulator_read_emulated,
6479         .write_emulated      = emulator_write_emulated,
6480         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
6481         .invlpg              = emulator_invlpg,
6482         .pio_in_emulated     = emulator_pio_in_emulated,
6483         .pio_out_emulated    = emulator_pio_out_emulated,
6484         .get_segment         = emulator_get_segment,
6485         .set_segment         = emulator_set_segment,
6486         .get_cached_segment_base = emulator_get_cached_segment_base,
6487         .get_gdt             = emulator_get_gdt,
6488         .get_idt             = emulator_get_idt,
6489         .set_gdt             = emulator_set_gdt,
6490         .set_idt             = emulator_set_idt,
6491         .get_cr              = emulator_get_cr,
6492         .set_cr              = emulator_set_cr,
6493         .cpl                 = emulator_get_cpl,
6494         .get_dr              = emulator_get_dr,
6495         .set_dr              = emulator_set_dr,
6496         .get_smbase          = emulator_get_smbase,
6497         .set_smbase          = emulator_set_smbase,
6498         .set_msr             = emulator_set_msr,
6499         .get_msr             = emulator_get_msr,
6500         .check_pmc           = emulator_check_pmc,
6501         .read_pmc            = emulator_read_pmc,
6502         .halt                = emulator_halt,
6503         .wbinvd              = emulator_wbinvd,
6504         .fix_hypercall       = emulator_fix_hypercall,
6505         .intercept           = emulator_intercept,
6506         .get_cpuid           = emulator_get_cpuid,
6507         .guest_has_long_mode = emulator_guest_has_long_mode,
6508         .guest_has_movbe     = emulator_guest_has_movbe,
6509         .guest_has_fxsr      = emulator_guest_has_fxsr,
6510         .set_nmi_mask        = emulator_set_nmi_mask,
6511         .get_hflags          = emulator_get_hflags,
6512         .set_hflags          = emulator_set_hflags,
6513         .pre_leave_smm       = emulator_pre_leave_smm,
6514         .post_leave_smm      = emulator_post_leave_smm,
6515         .set_xcr             = emulator_set_xcr,
6516 };
6517
6518 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
6519 {
6520         u32 int_shadow = kvm_x86_ops.get_interrupt_shadow(vcpu);
6521         /*
6522          * an sti; sti; sequence only disable interrupts for the first
6523          * instruction. So, if the last instruction, be it emulated or
6524          * not, left the system with the INT_STI flag enabled, it
6525          * means that the last instruction is an sti. We should not
6526          * leave the flag on in this case. The same goes for mov ss
6527          */
6528         if (int_shadow & mask)
6529                 mask = 0;
6530         if (unlikely(int_shadow || mask)) {
6531                 kvm_x86_ops.set_interrupt_shadow(vcpu, mask);
6532                 if (!mask)
6533                         kvm_make_request(KVM_REQ_EVENT, vcpu);
6534         }
6535 }
6536
6537 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
6538 {
6539         struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6540         if (ctxt->exception.vector == PF_VECTOR)
6541                 return kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
6542
6543         if (ctxt->exception.error_code_valid)
6544                 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
6545                                       ctxt->exception.error_code);
6546         else
6547                 kvm_queue_exception(vcpu, ctxt->exception.vector);
6548         return false;
6549 }
6550
6551 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
6552 {
6553         struct x86_emulate_ctxt *ctxt;
6554
6555         ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
6556         if (!ctxt) {
6557                 pr_err("kvm: failed to allocate vcpu's emulator\n");
6558                 return NULL;
6559         }
6560
6561         ctxt->vcpu = vcpu;
6562         ctxt->ops = &emulate_ops;
6563         vcpu->arch.emulate_ctxt = ctxt;
6564
6565         return ctxt;
6566 }
6567
6568 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
6569 {
6570         struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6571         int cs_db, cs_l;
6572
6573         kvm_x86_ops.get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
6574
6575         ctxt->gpa_available = false;
6576         ctxt->eflags = kvm_get_rflags(vcpu);
6577         ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
6578
6579         ctxt->eip = kvm_rip_read(vcpu);
6580         ctxt->mode = (!is_protmode(vcpu))               ? X86EMUL_MODE_REAL :
6581                      (ctxt->eflags & X86_EFLAGS_VM)     ? X86EMUL_MODE_VM86 :
6582                      (cs_l && is_long_mode(vcpu))       ? X86EMUL_MODE_PROT64 :
6583                      cs_db                              ? X86EMUL_MODE_PROT32 :
6584                                                           X86EMUL_MODE_PROT16;
6585         BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
6586         BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
6587         BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
6588
6589         init_decode_cache(ctxt);
6590         vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6591 }
6592
6593 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
6594 {
6595         struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6596         int ret;
6597
6598         init_emulate_ctxt(vcpu);
6599
6600         ctxt->op_bytes = 2;
6601         ctxt->ad_bytes = 2;
6602         ctxt->_eip = ctxt->eip + inc_eip;
6603         ret = emulate_int_real(ctxt, irq);
6604
6605         if (ret != X86EMUL_CONTINUE) {
6606                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6607         } else {
6608                 ctxt->eip = ctxt->_eip;
6609                 kvm_rip_write(vcpu, ctxt->eip);
6610                 kvm_set_rflags(vcpu, ctxt->eflags);
6611         }
6612 }
6613 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
6614
6615 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
6616 {
6617         ++vcpu->stat.insn_emulation_fail;
6618         trace_kvm_emulate_insn_failed(vcpu);
6619
6620         if (emulation_type & EMULTYPE_VMWARE_GP) {
6621                 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6622                 return 1;
6623         }
6624
6625         if (emulation_type & EMULTYPE_SKIP) {
6626                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6627                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6628                 vcpu->run->internal.ndata = 0;
6629                 return 0;
6630         }
6631
6632         kvm_queue_exception(vcpu, UD_VECTOR);
6633
6634         if (!is_guest_mode(vcpu) && kvm_x86_ops.get_cpl(vcpu) == 0) {
6635                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6636                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6637                 vcpu->run->internal.ndata = 0;
6638                 return 0;
6639         }
6640
6641         return 1;
6642 }
6643
6644 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6645                                   bool write_fault_to_shadow_pgtable,
6646                                   int emulation_type)
6647 {
6648         gpa_t gpa = cr2_or_gpa;
6649         kvm_pfn_t pfn;
6650
6651         if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
6652                 return false;
6653
6654         if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
6655             WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
6656                 return false;
6657
6658         if (!vcpu->arch.mmu->direct_map) {
6659                 /*
6660                  * Write permission should be allowed since only
6661                  * write access need to be emulated.
6662                  */
6663                 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
6664
6665                 /*
6666                  * If the mapping is invalid in guest, let cpu retry
6667                  * it to generate fault.
6668                  */
6669                 if (gpa == UNMAPPED_GVA)
6670                         return true;
6671         }
6672
6673         /*
6674          * Do not retry the unhandleable instruction if it faults on the
6675          * readonly host memory, otherwise it will goto a infinite loop:
6676          * retry instruction -> write #PF -> emulation fail -> retry
6677          * instruction -> ...
6678          */
6679         pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
6680
6681         /*
6682          * If the instruction failed on the error pfn, it can not be fixed,
6683          * report the error to userspace.
6684          */
6685         if (is_error_noslot_pfn(pfn))
6686                 return false;
6687
6688         kvm_release_pfn_clean(pfn);
6689
6690         /* The instructions are well-emulated on direct mmu. */
6691         if (vcpu->arch.mmu->direct_map) {
6692                 unsigned int indirect_shadow_pages;
6693
6694                 spin_lock(&vcpu->kvm->mmu_lock);
6695                 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
6696                 spin_unlock(&vcpu->kvm->mmu_lock);
6697
6698                 if (indirect_shadow_pages)
6699                         kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6700
6701                 return true;
6702         }
6703
6704         /*
6705          * if emulation was due to access to shadowed page table
6706          * and it failed try to unshadow page and re-enter the
6707          * guest to let CPU execute the instruction.
6708          */
6709         kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6710
6711         /*
6712          * If the access faults on its page table, it can not
6713          * be fixed by unprotecting shadow page and it should
6714          * be reported to userspace.
6715          */
6716         return !write_fault_to_shadow_pgtable;
6717 }
6718
6719 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
6720                               gpa_t cr2_or_gpa,  int emulation_type)
6721 {
6722         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
6723         unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
6724
6725         last_retry_eip = vcpu->arch.last_retry_eip;
6726         last_retry_addr = vcpu->arch.last_retry_addr;
6727
6728         /*
6729          * If the emulation is caused by #PF and it is non-page_table
6730          * writing instruction, it means the VM-EXIT is caused by shadow
6731          * page protected, we can zap the shadow page and retry this
6732          * instruction directly.
6733          *
6734          * Note: if the guest uses a non-page-table modifying instruction
6735          * on the PDE that points to the instruction, then we will unmap
6736          * the instruction and go to an infinite loop. So, we cache the
6737          * last retried eip and the last fault address, if we meet the eip
6738          * and the address again, we can break out of the potential infinite
6739          * loop.
6740          */
6741         vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
6742
6743         if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
6744                 return false;
6745
6746         if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
6747             WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
6748                 return false;
6749
6750         if (x86_page_table_writing_insn(ctxt))
6751                 return false;
6752
6753         if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
6754                 return false;
6755
6756         vcpu->arch.last_retry_eip = ctxt->eip;
6757         vcpu->arch.last_retry_addr = cr2_or_gpa;
6758
6759         if (!vcpu->arch.mmu->direct_map)
6760                 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
6761
6762         kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
6763
6764         return true;
6765 }
6766
6767 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
6768 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
6769
6770 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
6771 {
6772         if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
6773                 /* This is a good place to trace that we are exiting SMM.  */
6774                 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
6775
6776                 /* Process a latched INIT or SMI, if any.  */
6777                 kvm_make_request(KVM_REQ_EVENT, vcpu);
6778         }
6779
6780         kvm_mmu_reset_context(vcpu);
6781 }
6782
6783 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
6784                                 unsigned long *db)
6785 {
6786         u32 dr6 = 0;
6787         int i;
6788         u32 enable, rwlen;
6789
6790         enable = dr7;
6791         rwlen = dr7 >> 16;
6792         for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
6793                 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
6794                         dr6 |= (1 << i);
6795         return dr6;
6796 }
6797
6798 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
6799 {
6800         struct kvm_run *kvm_run = vcpu->run;
6801
6802         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
6803                 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
6804                 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
6805                 kvm_run->debug.arch.exception = DB_VECTOR;
6806                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6807                 return 0;
6808         }
6809         kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
6810         return 1;
6811 }
6812
6813 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
6814 {
6815         unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
6816         int r;
6817
6818         r = kvm_x86_ops.skip_emulated_instruction(vcpu);
6819         if (unlikely(!r))
6820                 return 0;
6821
6822         /*
6823          * rflags is the old, "raw" value of the flags.  The new value has
6824          * not been saved yet.
6825          *
6826          * This is correct even for TF set by the guest, because "the
6827          * processor will not generate this exception after the instruction
6828          * that sets the TF flag".
6829          */
6830         if (unlikely(rflags & X86_EFLAGS_TF))
6831                 r = kvm_vcpu_do_singlestep(vcpu);
6832         return r;
6833 }
6834 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
6835
6836 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
6837 {
6838         if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
6839             (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
6840                 struct kvm_run *kvm_run = vcpu->run;
6841                 unsigned long eip = kvm_get_linear_rip(vcpu);
6842                 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6843                                            vcpu->arch.guest_debug_dr7,
6844                                            vcpu->arch.eff_db);
6845
6846                 if (dr6 != 0) {
6847                         kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
6848                         kvm_run->debug.arch.pc = eip;
6849                         kvm_run->debug.arch.exception = DB_VECTOR;
6850                         kvm_run->exit_reason = KVM_EXIT_DEBUG;
6851                         *r = 0;
6852                         return true;
6853                 }
6854         }
6855
6856         if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
6857             !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
6858                 unsigned long eip = kvm_get_linear_rip(vcpu);
6859                 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
6860                                            vcpu->arch.dr7,
6861                                            vcpu->arch.db);
6862
6863                 if (dr6 != 0) {
6864                         kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
6865                         *r = 1;
6866                         return true;
6867                 }
6868         }
6869
6870         return false;
6871 }
6872
6873 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
6874 {
6875         switch (ctxt->opcode_len) {
6876         case 1:
6877                 switch (ctxt->b) {
6878                 case 0xe4:      /* IN */
6879                 case 0xe5:
6880                 case 0xec:
6881                 case 0xed:
6882                 case 0xe6:      /* OUT */
6883                 case 0xe7:
6884                 case 0xee:
6885                 case 0xef:
6886                 case 0x6c:      /* INS */
6887                 case 0x6d:
6888                 case 0x6e:      /* OUTS */
6889                 case 0x6f:
6890                         return true;
6891                 }
6892                 break;
6893         case 2:
6894                 switch (ctxt->b) {
6895                 case 0x33:      /* RDPMC */
6896                         return true;
6897                 }
6898                 break;
6899         }
6900
6901         return false;
6902 }
6903
6904 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6905                             int emulation_type, void *insn, int insn_len)
6906 {
6907         int r;
6908         struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
6909         bool writeback = true;
6910         bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
6911
6912         vcpu->arch.l1tf_flush_l1d = true;
6913
6914         /*
6915          * Clear write_fault_to_shadow_pgtable here to ensure it is
6916          * never reused.
6917          */
6918         vcpu->arch.write_fault_to_shadow_pgtable = false;
6919         kvm_clear_exception_queue(vcpu);
6920
6921         if (!(emulation_type & EMULTYPE_NO_DECODE)) {
6922                 init_emulate_ctxt(vcpu);
6923
6924                 /*
6925                  * We will reenter on the same instruction since
6926                  * we do not set complete_userspace_io.  This does not
6927                  * handle watchpoints yet, those would be handled in
6928                  * the emulate_ops.
6929                  */
6930                 if (!(emulation_type & EMULTYPE_SKIP) &&
6931                     kvm_vcpu_check_breakpoint(vcpu, &r))
6932                         return r;
6933
6934                 ctxt->interruptibility = 0;
6935                 ctxt->have_exception = false;
6936                 ctxt->exception.vector = -1;
6937                 ctxt->perm_ok = false;
6938
6939                 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
6940
6941                 r = x86_decode_insn(ctxt, insn, insn_len);
6942
6943                 trace_kvm_emulate_insn_start(vcpu);
6944                 ++vcpu->stat.insn_emulation;
6945                 if (r != EMULATION_OK)  {
6946                         if ((emulation_type & EMULTYPE_TRAP_UD) ||
6947                             (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
6948                                 kvm_queue_exception(vcpu, UD_VECTOR);
6949                                 return 1;
6950                         }
6951                         if (reexecute_instruction(vcpu, cr2_or_gpa,
6952                                                   write_fault_to_spt,
6953                                                   emulation_type))
6954                                 return 1;
6955                         if (ctxt->have_exception) {
6956                                 /*
6957                                  * #UD should result in just EMULATION_FAILED, and trap-like
6958                                  * exception should not be encountered during decode.
6959                                  */
6960                                 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
6961                                              exception_type(ctxt->exception.vector) == EXCPT_TRAP);
6962                                 inject_emulated_exception(vcpu);
6963                                 return 1;
6964                         }
6965                         return handle_emulation_failure(vcpu, emulation_type);
6966                 }
6967         }
6968
6969         if ((emulation_type & EMULTYPE_VMWARE_GP) &&
6970             !is_vmware_backdoor_opcode(ctxt)) {
6971                 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
6972                 return 1;
6973         }
6974
6975         /*
6976          * Note, EMULTYPE_SKIP is intended for use *only* by vendor callbacks
6977          * for kvm_skip_emulated_instruction().  The caller is responsible for
6978          * updating interruptibility state and injecting single-step #DBs.
6979          */
6980         if (emulation_type & EMULTYPE_SKIP) {
6981                 kvm_rip_write(vcpu, ctxt->_eip);
6982                 if (ctxt->eflags & X86_EFLAGS_RF)
6983                         kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
6984                 return 1;
6985         }
6986
6987         if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
6988                 return 1;
6989
6990         /* this is needed for vmware backdoor interface to work since it
6991            changes registers values  during IO operation */
6992         if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
6993                 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
6994                 emulator_invalidate_register_cache(ctxt);
6995         }
6996
6997 restart:
6998         if (emulation_type & EMULTYPE_PF) {
6999                 /* Save the faulting GPA (cr2) in the address field */
7000                 ctxt->exception.address = cr2_or_gpa;
7001
7002                 /* With shadow page tables, cr2 contains a GVA or nGPA. */
7003                 if (vcpu->arch.mmu->direct_map) {
7004                         ctxt->gpa_available = true;
7005                         ctxt->gpa_val = cr2_or_gpa;
7006                 }
7007         } else {
7008                 /* Sanitize the address out of an abundance of paranoia. */
7009                 ctxt->exception.address = 0;
7010         }
7011
7012         r = x86_emulate_insn(ctxt);
7013
7014         if (r == EMULATION_INTERCEPTED)
7015                 return 1;
7016
7017         if (r == EMULATION_FAILED) {
7018                 if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
7019                                         emulation_type))
7020                         return 1;
7021
7022                 return handle_emulation_failure(vcpu, emulation_type);
7023         }
7024
7025         if (ctxt->have_exception) {
7026                 r = 1;
7027                 if (inject_emulated_exception(vcpu))
7028                         return r;
7029         } else if (vcpu->arch.pio.count) {
7030                 if (!vcpu->arch.pio.in) {
7031                         /* FIXME: return into emulator if single-stepping.  */
7032                         vcpu->arch.pio.count = 0;
7033                 } else {
7034                         writeback = false;
7035                         vcpu->arch.complete_userspace_io = complete_emulated_pio;
7036                 }
7037                 r = 0;
7038         } else if (vcpu->mmio_needed) {
7039                 ++vcpu->stat.mmio_exits;
7040
7041                 if (!vcpu->mmio_is_write)
7042                         writeback = false;
7043                 r = 0;
7044                 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
7045         } else if (r == EMULATION_RESTART)
7046                 goto restart;
7047         else
7048                 r = 1;
7049
7050         if (writeback) {
7051                 unsigned long rflags = kvm_x86_ops.get_rflags(vcpu);
7052                 toggle_interruptibility(vcpu, ctxt->interruptibility);
7053                 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
7054                 if (!ctxt->have_exception ||
7055                     exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
7056                         kvm_rip_write(vcpu, ctxt->eip);
7057                         if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
7058                                 r = kvm_vcpu_do_singlestep(vcpu);
7059                         if (kvm_x86_ops.update_emulated_instruction)
7060                                 kvm_x86_ops.update_emulated_instruction(vcpu);
7061                         __kvm_set_rflags(vcpu, ctxt->eflags);
7062                 }
7063
7064                 /*
7065                  * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
7066                  * do nothing, and it will be requested again as soon as
7067                  * the shadow expires.  But we still need to check here,
7068                  * because POPF has no interrupt shadow.
7069                  */
7070                 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
7071                         kvm_make_request(KVM_REQ_EVENT, vcpu);
7072         } else
7073                 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
7074
7075         return r;
7076 }
7077
7078 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
7079 {
7080         return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
7081 }
7082 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
7083
7084 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
7085                                         void *insn, int insn_len)
7086 {
7087         return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
7088 }
7089 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
7090
7091 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
7092 {
7093         vcpu->arch.pio.count = 0;
7094         return 1;
7095 }
7096
7097 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
7098 {
7099         vcpu->arch.pio.count = 0;
7100
7101         if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
7102                 return 1;
7103
7104         return kvm_skip_emulated_instruction(vcpu);
7105 }
7106
7107 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
7108                             unsigned short port)
7109 {
7110         unsigned long val = kvm_rax_read(vcpu);
7111         int ret = emulator_pio_out(vcpu, size, port, &val, 1);
7112
7113         if (ret)
7114                 return ret;
7115
7116         /*
7117          * Workaround userspace that relies on old KVM behavior of %rip being
7118          * incremented prior to exiting to userspace to handle "OUT 0x7e".
7119          */
7120         if (port == 0x7e &&
7121             kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
7122                 vcpu->arch.complete_userspace_io =
7123                         complete_fast_pio_out_port_0x7e;
7124                 kvm_skip_emulated_instruction(vcpu);
7125         } else {
7126                 vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7127                 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
7128         }
7129         return 0;
7130 }
7131
7132 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
7133 {
7134         unsigned long val;
7135
7136         /* We should only ever be called with arch.pio.count equal to 1 */
7137         BUG_ON(vcpu->arch.pio.count != 1);
7138
7139         if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
7140                 vcpu->arch.pio.count = 0;
7141                 return 1;
7142         }
7143
7144         /* For size less than 4 we merge, else we zero extend */
7145         val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
7146
7147         /*
7148          * Since vcpu->arch.pio.count == 1 let emulator_pio_in perform
7149          * the copy and tracing
7150          */
7151         emulator_pio_in(vcpu, vcpu->arch.pio.size, vcpu->arch.pio.port, &val, 1);
7152         kvm_rax_write(vcpu, val);
7153
7154         return kvm_skip_emulated_instruction(vcpu);
7155 }
7156
7157 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
7158                            unsigned short port)
7159 {
7160         unsigned long val;
7161         int ret;
7162
7163         /* For size less than 4 we merge, else we zero extend */
7164         val = (size < 4) ? kvm_rax_read(vcpu) : 0;
7165
7166         ret = emulator_pio_in(vcpu, size, port, &val, 1);
7167         if (ret) {
7168                 kvm_rax_write(vcpu, val);
7169                 return ret;
7170         }
7171
7172         vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
7173         vcpu->arch.complete_userspace_io = complete_fast_pio_in;
7174
7175         return 0;
7176 }
7177
7178 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
7179 {
7180         int ret;
7181
7182         if (in)
7183                 ret = kvm_fast_pio_in(vcpu, size, port);
7184         else
7185                 ret = kvm_fast_pio_out(vcpu, size, port);
7186         return ret && kvm_skip_emulated_instruction(vcpu);
7187 }
7188 EXPORT_SYMBOL_GPL(kvm_fast_pio);
7189
7190 static int kvmclock_cpu_down_prep(unsigned int cpu)
7191 {
7192         __this_cpu_write(cpu_tsc_khz, 0);
7193         return 0;
7194 }
7195
7196 static void tsc_khz_changed(void *data)
7197 {
7198         struct cpufreq_freqs *freq = data;
7199         unsigned long khz = 0;
7200
7201         if (data)
7202                 khz = freq->new;
7203         else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7204                 khz = cpufreq_quick_get(raw_smp_processor_id());
7205         if (!khz)
7206                 khz = tsc_khz;
7207         __this_cpu_write(cpu_tsc_khz, khz);
7208 }
7209
7210 #ifdef CONFIG_X86_64
7211 static void kvm_hyperv_tsc_notifier(void)
7212 {
7213         struct kvm *kvm;
7214         struct kvm_vcpu *vcpu;
7215         int cpu;
7216
7217         mutex_lock(&kvm_lock);
7218         list_for_each_entry(kvm, &vm_list, vm_list)
7219                 kvm_make_mclock_inprogress_request(kvm);
7220
7221         hyperv_stop_tsc_emulation();
7222
7223         /* TSC frequency always matches when on Hyper-V */
7224         for_each_present_cpu(cpu)
7225                 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
7226         kvm_max_guest_tsc_khz = tsc_khz;
7227
7228         list_for_each_entry(kvm, &vm_list, vm_list) {
7229                 struct kvm_arch *ka = &kvm->arch;
7230
7231                 spin_lock(&ka->pvclock_gtod_sync_lock);
7232
7233                 pvclock_update_vm_gtod_copy(kvm);
7234
7235                 kvm_for_each_vcpu(cpu, vcpu, kvm)
7236                         kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7237
7238                 kvm_for_each_vcpu(cpu, vcpu, kvm)
7239                         kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
7240
7241                 spin_unlock(&ka->pvclock_gtod_sync_lock);
7242         }
7243         mutex_unlock(&kvm_lock);
7244 }
7245 #endif
7246
7247 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
7248 {
7249         struct kvm *kvm;
7250         struct kvm_vcpu *vcpu;
7251         int i, send_ipi = 0;
7252
7253         /*
7254          * We allow guests to temporarily run on slowing clocks,
7255          * provided we notify them after, or to run on accelerating
7256          * clocks, provided we notify them before.  Thus time never
7257          * goes backwards.
7258          *
7259          * However, we have a problem.  We can't atomically update
7260          * the frequency of a given CPU from this function; it is
7261          * merely a notifier, which can be called from any CPU.
7262          * Changing the TSC frequency at arbitrary points in time
7263          * requires a recomputation of local variables related to
7264          * the TSC for each VCPU.  We must flag these local variables
7265          * to be updated and be sure the update takes place with the
7266          * new frequency before any guests proceed.
7267          *
7268          * Unfortunately, the combination of hotplug CPU and frequency
7269          * change creates an intractable locking scenario; the order
7270          * of when these callouts happen is undefined with respect to
7271          * CPU hotplug, and they can race with each other.  As such,
7272          * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
7273          * undefined; you can actually have a CPU frequency change take
7274          * place in between the computation of X and the setting of the
7275          * variable.  To protect against this problem, all updates of
7276          * the per_cpu tsc_khz variable are done in an interrupt
7277          * protected IPI, and all callers wishing to update the value
7278          * must wait for a synchronous IPI to complete (which is trivial
7279          * if the caller is on the CPU already).  This establishes the
7280          * necessary total order on variable updates.
7281          *
7282          * Note that because a guest time update may take place
7283          * anytime after the setting of the VCPU's request bit, the
7284          * correct TSC value must be set before the request.  However,
7285          * to ensure the update actually makes it to any guest which
7286          * starts running in hardware virtualization between the set
7287          * and the acquisition of the spinlock, we must also ping the
7288          * CPU after setting the request bit.
7289          *
7290          */
7291
7292         smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7293
7294         mutex_lock(&kvm_lock);
7295         list_for_each_entry(kvm, &vm_list, vm_list) {
7296                 kvm_for_each_vcpu(i, vcpu, kvm) {
7297                         if (vcpu->cpu != cpu)
7298                                 continue;
7299                         kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
7300                         if (vcpu->cpu != raw_smp_processor_id())
7301                                 send_ipi = 1;
7302                 }
7303         }
7304         mutex_unlock(&kvm_lock);
7305
7306         if (freq->old < freq->new && send_ipi) {
7307                 /*
7308                  * We upscale the frequency.  Must make the guest
7309                  * doesn't see old kvmclock values while running with
7310                  * the new frequency, otherwise we risk the guest sees
7311                  * time go backwards.
7312                  *
7313                  * In case we update the frequency for another cpu
7314                  * (which might be in guest context) send an interrupt
7315                  * to kick the cpu out of guest context.  Next time
7316                  * guest context is entered kvmclock will be updated,
7317                  * so the guest will not see stale values.
7318                  */
7319                 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
7320         }
7321 }
7322
7323 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
7324                                      void *data)
7325 {
7326         struct cpufreq_freqs *freq = data;
7327         int cpu;
7328
7329         if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
7330                 return 0;
7331         if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
7332                 return 0;
7333
7334         for_each_cpu(cpu, freq->policy->cpus)
7335                 __kvmclock_cpufreq_notifier(freq, cpu);
7336
7337         return 0;
7338 }
7339
7340 static struct notifier_block kvmclock_cpufreq_notifier_block = {
7341         .notifier_call  = kvmclock_cpufreq_notifier
7342 };
7343
7344 static int kvmclock_cpu_online(unsigned int cpu)
7345 {
7346         tsc_khz_changed(NULL);
7347         return 0;
7348 }
7349
7350 static void kvm_timer_init(void)
7351 {
7352         max_tsc_khz = tsc_khz;
7353
7354         if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
7355 #ifdef CONFIG_CPU_FREQ
7356                 struct cpufreq_policy *policy;
7357                 int cpu;
7358
7359                 cpu = get_cpu();
7360                 policy = cpufreq_cpu_get(cpu);
7361                 if (policy) {
7362                         if (policy->cpuinfo.max_freq)
7363                                 max_tsc_khz = policy->cpuinfo.max_freq;
7364                         cpufreq_cpu_put(policy);
7365                 }
7366                 put_cpu();
7367 #endif
7368                 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
7369                                           CPUFREQ_TRANSITION_NOTIFIER);
7370         }
7371
7372         cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
7373                           kvmclock_cpu_online, kvmclock_cpu_down_prep);
7374 }
7375
7376 DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
7377 EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
7378
7379 int kvm_is_in_guest(void)
7380 {
7381         return __this_cpu_read(current_vcpu) != NULL;
7382 }
7383
7384 static int kvm_is_user_mode(void)
7385 {
7386         int user_mode = 3;
7387
7388         if (__this_cpu_read(current_vcpu))
7389                 user_mode = kvm_x86_ops.get_cpl(__this_cpu_read(current_vcpu));
7390
7391         return user_mode != 0;
7392 }
7393
7394 static unsigned long kvm_get_guest_ip(void)
7395 {
7396         unsigned long ip = 0;
7397
7398         if (__this_cpu_read(current_vcpu))
7399                 ip = kvm_rip_read(__this_cpu_read(current_vcpu));
7400
7401         return ip;
7402 }
7403
7404 static void kvm_handle_intel_pt_intr(void)
7405 {
7406         struct kvm_vcpu *vcpu = __this_cpu_read(current_vcpu);
7407
7408         kvm_make_request(KVM_REQ_PMI, vcpu);
7409         __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
7410                         (unsigned long *)&vcpu->arch.pmu.global_status);
7411 }
7412
7413 static struct perf_guest_info_callbacks kvm_guest_cbs = {
7414         .is_in_guest            = kvm_is_in_guest,
7415         .is_user_mode           = kvm_is_user_mode,
7416         .get_guest_ip           = kvm_get_guest_ip,
7417         .handle_intel_pt_intr   = kvm_handle_intel_pt_intr,
7418 };
7419
7420 #ifdef CONFIG_X86_64
7421 static void pvclock_gtod_update_fn(struct work_struct *work)
7422 {
7423         struct kvm *kvm;
7424
7425         struct kvm_vcpu *vcpu;
7426         int i;
7427
7428         mutex_lock(&kvm_lock);
7429         list_for_each_entry(kvm, &vm_list, vm_list)
7430                 kvm_for_each_vcpu(i, vcpu, kvm)
7431                         kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
7432         atomic_set(&kvm_guest_has_master_clock, 0);
7433         mutex_unlock(&kvm_lock);
7434 }
7435
7436 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
7437
7438 /*
7439  * Notification about pvclock gtod data update.
7440  */
7441 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
7442                                void *priv)
7443 {
7444         struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
7445         struct timekeeper *tk = priv;
7446
7447         update_pvclock_gtod(tk);
7448
7449         /* disable master clock if host does not trust, or does not
7450          * use, TSC based clocksource.
7451          */
7452         if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
7453             atomic_read(&kvm_guest_has_master_clock) != 0)
7454                 queue_work(system_long_wq, &pvclock_gtod_work);
7455
7456         return 0;
7457 }
7458
7459 static struct notifier_block pvclock_gtod_notifier = {
7460         .notifier_call = pvclock_gtod_notify,
7461 };
7462 #endif
7463
7464 int kvm_arch_init(void *opaque)
7465 {
7466         struct kvm_x86_init_ops *ops = opaque;
7467         int r;
7468
7469         if (kvm_x86_ops.hardware_enable) {
7470                 printk(KERN_ERR "kvm: already loaded the other module\n");
7471                 r = -EEXIST;
7472                 goto out;
7473         }
7474
7475         if (!ops->cpu_has_kvm_support()) {
7476                 pr_err_ratelimited("kvm: no hardware support\n");
7477                 r = -EOPNOTSUPP;
7478                 goto out;
7479         }
7480         if (ops->disabled_by_bios()) {
7481                 pr_err_ratelimited("kvm: disabled by bios\n");
7482                 r = -EOPNOTSUPP;
7483                 goto out;
7484         }
7485
7486         /*
7487          * KVM explicitly assumes that the guest has an FPU and
7488          * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
7489          * vCPU's FPU state as a fxregs_state struct.
7490          */
7491         if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
7492                 printk(KERN_ERR "kvm: inadequate fpu\n");
7493                 r = -EOPNOTSUPP;
7494                 goto out;
7495         }
7496
7497         r = -ENOMEM;
7498         x86_fpu_cache = kmem_cache_create("x86_fpu", sizeof(struct fpu),
7499                                           __alignof__(struct fpu), SLAB_ACCOUNT,
7500                                           NULL);
7501         if (!x86_fpu_cache) {
7502                 printk(KERN_ERR "kvm: failed to allocate cache for x86 fpu\n");
7503                 goto out;
7504         }
7505
7506         x86_emulator_cache = kvm_alloc_emulator_cache();
7507         if (!x86_emulator_cache) {
7508                 pr_err("kvm: failed to allocate cache for x86 emulator\n");
7509                 goto out_free_x86_fpu_cache;
7510         }
7511
7512         shared_msrs = alloc_percpu(struct kvm_shared_msrs);
7513         if (!shared_msrs) {
7514                 printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
7515                 goto out_free_x86_emulator_cache;
7516         }
7517
7518         r = kvm_mmu_module_init();
7519         if (r)
7520                 goto out_free_percpu;
7521
7522         kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
7523                         PT_DIRTY_MASK, PT64_NX_MASK, 0,
7524                         PT_PRESENT_MASK, 0, sme_me_mask);
7525         kvm_timer_init();
7526
7527         perf_register_guest_info_callbacks(&kvm_guest_cbs);
7528
7529         if (boot_cpu_has(X86_FEATURE_XSAVE)) {
7530                 host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
7531                 supported_xcr0 = host_xcr0 & KVM_SUPPORTED_XCR0;
7532         }
7533
7534         kvm_lapic_init();
7535         if (pi_inject_timer == -1)
7536                 pi_inject_timer = housekeeping_enabled(HK_FLAG_TIMER);
7537 #ifdef CONFIG_X86_64
7538         pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
7539
7540         if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7541                 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
7542 #endif
7543
7544         return 0;
7545
7546 out_free_percpu:
7547         free_percpu(shared_msrs);
7548 out_free_x86_emulator_cache:
7549         kmem_cache_destroy(x86_emulator_cache);
7550 out_free_x86_fpu_cache:
7551         kmem_cache_destroy(x86_fpu_cache);
7552 out:
7553         return r;
7554 }
7555
7556 void kvm_arch_exit(void)
7557 {
7558 #ifdef CONFIG_X86_64
7559         if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
7560                 clear_hv_tscchange_cb();
7561 #endif
7562         kvm_lapic_exit();
7563         perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
7564
7565         if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
7566                 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
7567                                             CPUFREQ_TRANSITION_NOTIFIER);
7568         cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
7569 #ifdef CONFIG_X86_64
7570         pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
7571 #endif
7572         kvm_x86_ops.hardware_enable = NULL;
7573         kvm_mmu_module_exit();
7574         free_percpu(shared_msrs);
7575         kmem_cache_destroy(x86_fpu_cache);
7576 }
7577
7578 int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
7579 {
7580         ++vcpu->stat.halt_exits;
7581         if (lapic_in_kernel(vcpu)) {
7582                 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
7583                 return 1;
7584         } else {
7585                 vcpu->run->exit_reason = KVM_EXIT_HLT;
7586                 return 0;
7587         }
7588 }
7589 EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
7590
7591 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
7592 {
7593         int ret = kvm_skip_emulated_instruction(vcpu);
7594         /*
7595          * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
7596          * KVM_EXIT_DEBUG here.
7597          */
7598         return kvm_vcpu_halt(vcpu) && ret;
7599 }
7600 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
7601
7602 #ifdef CONFIG_X86_64
7603 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
7604                                 unsigned long clock_type)
7605 {
7606         struct kvm_clock_pairing clock_pairing;
7607         struct timespec64 ts;
7608         u64 cycle;
7609         int ret;
7610
7611         if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
7612                 return -KVM_EOPNOTSUPP;
7613
7614         if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
7615                 return -KVM_EOPNOTSUPP;
7616
7617         clock_pairing.sec = ts.tv_sec;
7618         clock_pairing.nsec = ts.tv_nsec;
7619         clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
7620         clock_pairing.flags = 0;
7621         memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
7622
7623         ret = 0;
7624         if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
7625                             sizeof(struct kvm_clock_pairing)))
7626                 ret = -KVM_EFAULT;
7627
7628         return ret;
7629 }
7630 #endif
7631
7632 /*
7633  * kvm_pv_kick_cpu_op:  Kick a vcpu.
7634  *
7635  * @apicid - apicid of vcpu to be kicked.
7636  */
7637 static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
7638 {
7639         struct kvm_lapic_irq lapic_irq;
7640
7641         lapic_irq.shorthand = APIC_DEST_NOSHORT;
7642         lapic_irq.dest_mode = APIC_DEST_PHYSICAL;
7643         lapic_irq.level = 0;
7644         lapic_irq.dest_id = apicid;
7645         lapic_irq.msi_redir_hint = false;
7646
7647         lapic_irq.delivery_mode = APIC_DM_REMRD;
7648         kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
7649 }
7650
7651 bool kvm_apicv_activated(struct kvm *kvm)
7652 {
7653         return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
7654 }
7655 EXPORT_SYMBOL_GPL(kvm_apicv_activated);
7656
7657 void kvm_apicv_init(struct kvm *kvm, bool enable)
7658 {
7659         if (enable)
7660                 clear_bit(APICV_INHIBIT_REASON_DISABLE,
7661                           &kvm->arch.apicv_inhibit_reasons);
7662         else
7663                 set_bit(APICV_INHIBIT_REASON_DISABLE,
7664                         &kvm->arch.apicv_inhibit_reasons);
7665 }
7666 EXPORT_SYMBOL_GPL(kvm_apicv_init);
7667
7668 static void kvm_sched_yield(struct kvm *kvm, unsigned long dest_id)
7669 {
7670         struct kvm_vcpu *target = NULL;
7671         struct kvm_apic_map *map;
7672
7673         rcu_read_lock();
7674         map = rcu_dereference(kvm->arch.apic_map);
7675
7676         if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
7677                 target = map->phys_map[dest_id]->vcpu;
7678
7679         rcu_read_unlock();
7680
7681         if (target && READ_ONCE(target->ready))
7682                 kvm_vcpu_yield_to(target);
7683 }
7684
7685 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
7686 {
7687         unsigned long nr, a0, a1, a2, a3, ret;
7688         int op_64_bit;
7689
7690         if (kvm_hv_hypercall_enabled(vcpu->kvm))
7691                 return kvm_hv_hypercall(vcpu);
7692
7693         nr = kvm_rax_read(vcpu);
7694         a0 = kvm_rbx_read(vcpu);
7695         a1 = kvm_rcx_read(vcpu);
7696         a2 = kvm_rdx_read(vcpu);
7697         a3 = kvm_rsi_read(vcpu);
7698
7699         trace_kvm_hypercall(nr, a0, a1, a2, a3);
7700
7701         op_64_bit = is_64_bit_mode(vcpu);
7702         if (!op_64_bit) {
7703                 nr &= 0xFFFFFFFF;
7704                 a0 &= 0xFFFFFFFF;
7705                 a1 &= 0xFFFFFFFF;
7706                 a2 &= 0xFFFFFFFF;
7707                 a3 &= 0xFFFFFFFF;
7708         }
7709
7710         if (kvm_x86_ops.get_cpl(vcpu) != 0) {
7711                 ret = -KVM_EPERM;
7712                 goto out;
7713         }
7714
7715         switch (nr) {
7716         case KVM_HC_VAPIC_POLL_IRQ:
7717                 ret = 0;
7718                 break;
7719         case KVM_HC_KICK_CPU:
7720                 kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
7721                 kvm_sched_yield(vcpu->kvm, a1);
7722                 ret = 0;
7723                 break;
7724 #ifdef CONFIG_X86_64
7725         case KVM_HC_CLOCK_PAIRING:
7726                 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
7727                 break;
7728 #endif
7729         case KVM_HC_SEND_IPI:
7730                 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
7731                 break;
7732         case KVM_HC_SCHED_YIELD:
7733                 kvm_sched_yield(vcpu->kvm, a0);
7734                 ret = 0;
7735                 break;
7736         default:
7737                 ret = -KVM_ENOSYS;
7738                 break;
7739         }
7740 out:
7741         if (!op_64_bit)
7742                 ret = (u32)ret;
7743         kvm_rax_write(vcpu, ret);
7744
7745         ++vcpu->stat.hypercalls;
7746         return kvm_skip_emulated_instruction(vcpu);
7747 }
7748 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
7749
7750 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
7751 {
7752         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7753         char instruction[3];
7754         unsigned long rip = kvm_rip_read(vcpu);
7755
7756         kvm_x86_ops.patch_hypercall(vcpu, instruction);
7757
7758         return emulator_write_emulated(ctxt, rip, instruction, 3,
7759                 &ctxt->exception);
7760 }
7761
7762 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
7763 {
7764         return vcpu->run->request_interrupt_window &&
7765                 likely(!pic_in_kernel(vcpu->kvm));
7766 }
7767
7768 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
7769 {
7770         struct kvm_run *kvm_run = vcpu->run;
7771
7772         kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
7773         kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
7774         kvm_run->cr8 = kvm_get_cr8(vcpu);
7775         kvm_run->apic_base = kvm_get_apic_base(vcpu);
7776         kvm_run->ready_for_interrupt_injection =
7777                 pic_in_kernel(vcpu->kvm) ||
7778                 kvm_vcpu_ready_for_interrupt_injection(vcpu);
7779 }
7780
7781 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
7782 {
7783         int max_irr, tpr;
7784
7785         if (!kvm_x86_ops.update_cr8_intercept)
7786                 return;
7787
7788         if (!lapic_in_kernel(vcpu))
7789                 return;
7790
7791         if (vcpu->arch.apicv_active)
7792                 return;
7793
7794         if (!vcpu->arch.apic->vapic_addr)
7795                 max_irr = kvm_lapic_find_highest_irr(vcpu);
7796         else
7797                 max_irr = -1;
7798
7799         if (max_irr != -1)
7800                 max_irr >>= 4;
7801
7802         tpr = kvm_lapic_get_cr8(vcpu);
7803
7804         kvm_x86_ops.update_cr8_intercept(vcpu, tpr, max_irr);
7805 }
7806
7807 static void inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
7808 {
7809         int r;
7810         bool can_inject = true;
7811
7812         /* try to reinject previous events if any */
7813
7814         if (vcpu->arch.exception.injected) {
7815                 kvm_x86_ops.queue_exception(vcpu);
7816                 can_inject = false;
7817         }
7818         /*
7819          * Do not inject an NMI or interrupt if there is a pending
7820          * exception.  Exceptions and interrupts are recognized at
7821          * instruction boundaries, i.e. the start of an instruction.
7822          * Trap-like exceptions, e.g. #DB, have higher priority than
7823          * NMIs and interrupts, i.e. traps are recognized before an
7824          * NMI/interrupt that's pending on the same instruction.
7825          * Fault-like exceptions, e.g. #GP and #PF, are the lowest
7826          * priority, but are only generated (pended) during instruction
7827          * execution, i.e. a pending fault-like exception means the
7828          * fault occurred on the *previous* instruction and must be
7829          * serviced prior to recognizing any new events in order to
7830          * fully complete the previous instruction.
7831          */
7832         else if (!vcpu->arch.exception.pending) {
7833                 if (vcpu->arch.nmi_injected) {
7834                         kvm_x86_ops.set_nmi(vcpu);
7835                         can_inject = false;
7836                 } else if (vcpu->arch.interrupt.injected) {
7837                         kvm_x86_ops.set_irq(vcpu);
7838                         can_inject = false;
7839                 }
7840         }
7841
7842         WARN_ON_ONCE(vcpu->arch.exception.injected &&
7843                      vcpu->arch.exception.pending);
7844
7845         /*
7846          * Call check_nested_events() even if we reinjected a previous event
7847          * in order for caller to determine if it should require immediate-exit
7848          * from L2 to L1 due to pending L1 events which require exit
7849          * from L2 to L1.
7850          */
7851         if (is_guest_mode(vcpu)) {
7852                 r = kvm_x86_ops.nested_ops->check_events(vcpu);
7853                 if (r < 0)
7854                         goto busy;
7855         }
7856
7857         /* try to inject new event if pending */
7858         if (vcpu->arch.exception.pending) {
7859                 trace_kvm_inj_exception(vcpu->arch.exception.nr,
7860                                         vcpu->arch.exception.has_error_code,
7861                                         vcpu->arch.exception.error_code);
7862
7863                 vcpu->arch.exception.pending = false;
7864                 vcpu->arch.exception.injected = true;
7865
7866                 if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
7867                         __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
7868                                              X86_EFLAGS_RF);
7869
7870                 if (vcpu->arch.exception.nr == DB_VECTOR) {
7871                         kvm_deliver_exception_payload(vcpu);
7872                         if (vcpu->arch.dr7 & DR7_GD) {
7873                                 vcpu->arch.dr7 &= ~DR7_GD;
7874                                 kvm_update_dr7(vcpu);
7875                         }
7876                 }
7877
7878                 kvm_x86_ops.queue_exception(vcpu);
7879                 can_inject = false;
7880         }
7881
7882         /*
7883          * Finally, inject interrupt events.  If an event cannot be injected
7884          * due to architectural conditions (e.g. IF=0) a window-open exit
7885          * will re-request KVM_REQ_EVENT.  Sometimes however an event is pending
7886          * and can architecturally be injected, but we cannot do it right now:
7887          * an interrupt could have arrived just now and we have to inject it
7888          * as a vmexit, or there could already an event in the queue, which is
7889          * indicated by can_inject.  In that case we request an immediate exit
7890          * in order to make progress and get back here for another iteration.
7891          * The kvm_x86_ops hooks communicate this by returning -EBUSY.
7892          */
7893         if (vcpu->arch.smi_pending) {
7894                 r = can_inject ? kvm_x86_ops.smi_allowed(vcpu, true) : -EBUSY;
7895                 if (r < 0)
7896                         goto busy;
7897                 if (r) {
7898                         vcpu->arch.smi_pending = false;
7899                         ++vcpu->arch.smi_count;
7900                         enter_smm(vcpu);
7901                         can_inject = false;
7902                 } else
7903                         kvm_x86_ops.enable_smi_window(vcpu);
7904         }
7905
7906         if (vcpu->arch.nmi_pending) {
7907                 r = can_inject ? kvm_x86_ops.nmi_allowed(vcpu, true) : -EBUSY;
7908                 if (r < 0)
7909                         goto busy;
7910                 if (r) {
7911                         --vcpu->arch.nmi_pending;
7912                         vcpu->arch.nmi_injected = true;
7913                         kvm_x86_ops.set_nmi(vcpu);
7914                         can_inject = false;
7915                         WARN_ON(kvm_x86_ops.nmi_allowed(vcpu, true) < 0);
7916                 }
7917                 if (vcpu->arch.nmi_pending)
7918                         kvm_x86_ops.enable_nmi_window(vcpu);
7919         }
7920
7921         if (kvm_cpu_has_injectable_intr(vcpu)) {
7922                 r = can_inject ? kvm_x86_ops.interrupt_allowed(vcpu, true) : -EBUSY;
7923                 if (r < 0)
7924                         goto busy;
7925                 if (r) {
7926                         kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu), false);
7927                         kvm_x86_ops.set_irq(vcpu);
7928                         WARN_ON(kvm_x86_ops.interrupt_allowed(vcpu, true) < 0);
7929                 }
7930                 if (kvm_cpu_has_injectable_intr(vcpu))
7931                         kvm_x86_ops.enable_irq_window(vcpu);
7932         }
7933
7934         if (is_guest_mode(vcpu) &&
7935             kvm_x86_ops.nested_ops->hv_timer_pending &&
7936             kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
7937                 *req_immediate_exit = true;
7938
7939         WARN_ON(vcpu->arch.exception.pending);
7940         return;
7941
7942 busy:
7943         *req_immediate_exit = true;
7944         return;
7945 }
7946
7947 static void process_nmi(struct kvm_vcpu *vcpu)
7948 {
7949         unsigned limit = 2;
7950
7951         /*
7952          * x86 is limited to one NMI running, and one NMI pending after it.
7953          * If an NMI is already in progress, limit further NMIs to just one.
7954          * Otherwise, allow two (and we'll inject the first one immediately).
7955          */
7956         if (kvm_x86_ops.get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
7957                 limit = 1;
7958
7959         vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
7960         vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
7961         kvm_make_request(KVM_REQ_EVENT, vcpu);
7962 }
7963
7964 static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
7965 {
7966         u32 flags = 0;
7967         flags |= seg->g       << 23;
7968         flags |= seg->db      << 22;
7969         flags |= seg->l       << 21;
7970         flags |= seg->avl     << 20;
7971         flags |= seg->present << 15;
7972         flags |= seg->dpl     << 13;
7973         flags |= seg->s       << 12;
7974         flags |= seg->type    << 8;
7975         return flags;
7976 }
7977
7978 static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
7979 {
7980         struct kvm_segment seg;
7981         int offset;
7982
7983         kvm_get_segment(vcpu, &seg, n);
7984         put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
7985
7986         if (n < 3)
7987                 offset = 0x7f84 + n * 12;
7988         else
7989                 offset = 0x7f2c + (n - 3) * 12;
7990
7991         put_smstate(u32, buf, offset + 8, seg.base);
7992         put_smstate(u32, buf, offset + 4, seg.limit);
7993         put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
7994 }
7995
7996 #ifdef CONFIG_X86_64
7997 static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
7998 {
7999         struct kvm_segment seg;
8000         int offset;
8001         u16 flags;
8002
8003         kvm_get_segment(vcpu, &seg, n);
8004         offset = 0x7e00 + n * 16;
8005
8006         flags = enter_smm_get_segment_flags(&seg) >> 8;
8007         put_smstate(u16, buf, offset, seg.selector);
8008         put_smstate(u16, buf, offset + 2, flags);
8009         put_smstate(u32, buf, offset + 4, seg.limit);
8010         put_smstate(u64, buf, offset + 8, seg.base);
8011 }
8012 #endif
8013
8014 static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
8015 {
8016         struct desc_ptr dt;
8017         struct kvm_segment seg;
8018         unsigned long val;
8019         int i;
8020
8021         put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
8022         put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
8023         put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
8024         put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
8025
8026         for (i = 0; i < 8; i++)
8027                 put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
8028
8029         kvm_get_dr(vcpu, 6, &val);
8030         put_smstate(u32, buf, 0x7fcc, (u32)val);
8031         kvm_get_dr(vcpu, 7, &val);
8032         put_smstate(u32, buf, 0x7fc8, (u32)val);
8033
8034         kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
8035         put_smstate(u32, buf, 0x7fc4, seg.selector);
8036         put_smstate(u32, buf, 0x7f64, seg.base);
8037         put_smstate(u32, buf, 0x7f60, seg.limit);
8038         put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
8039
8040         kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
8041         put_smstate(u32, buf, 0x7fc0, seg.selector);
8042         put_smstate(u32, buf, 0x7f80, seg.base);
8043         put_smstate(u32, buf, 0x7f7c, seg.limit);
8044         put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
8045
8046         kvm_x86_ops.get_gdt(vcpu, &dt);
8047         put_smstate(u32, buf, 0x7f74, dt.address);
8048         put_smstate(u32, buf, 0x7f70, dt.size);
8049
8050         kvm_x86_ops.get_idt(vcpu, &dt);
8051         put_smstate(u32, buf, 0x7f58, dt.address);
8052         put_smstate(u32, buf, 0x7f54, dt.size);
8053
8054         for (i = 0; i < 6; i++)
8055                 enter_smm_save_seg_32(vcpu, buf, i);
8056
8057         put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
8058
8059         /* revision id */
8060         put_smstate(u32, buf, 0x7efc, 0x00020000);
8061         put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
8062 }
8063
8064 #ifdef CONFIG_X86_64
8065 static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
8066 {
8067         struct desc_ptr dt;
8068         struct kvm_segment seg;
8069         unsigned long val;
8070         int i;
8071
8072         for (i = 0; i < 16; i++)
8073                 put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
8074
8075         put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
8076         put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
8077
8078         kvm_get_dr(vcpu, 6, &val);
8079         put_smstate(u64, buf, 0x7f68, val);
8080         kvm_get_dr(vcpu, 7, &val);
8081         put_smstate(u64, buf, 0x7f60, val);
8082
8083         put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
8084         put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
8085         put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
8086
8087         put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
8088
8089         /* revision id */
8090         put_smstate(u32, buf, 0x7efc, 0x00020064);
8091
8092         put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
8093
8094         kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
8095         put_smstate(u16, buf, 0x7e90, seg.selector);
8096         put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
8097         put_smstate(u32, buf, 0x7e94, seg.limit);
8098         put_smstate(u64, buf, 0x7e98, seg.base);
8099
8100         kvm_x86_ops.get_idt(vcpu, &dt);
8101         put_smstate(u32, buf, 0x7e84, dt.size);
8102         put_smstate(u64, buf, 0x7e88, dt.address);
8103
8104         kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
8105         put_smstate(u16, buf, 0x7e70, seg.selector);
8106         put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
8107         put_smstate(u32, buf, 0x7e74, seg.limit);
8108         put_smstate(u64, buf, 0x7e78, seg.base);
8109
8110         kvm_x86_ops.get_gdt(vcpu, &dt);
8111         put_smstate(u32, buf, 0x7e64, dt.size);
8112         put_smstate(u64, buf, 0x7e68, dt.address);
8113
8114         for (i = 0; i < 6; i++)
8115                 enter_smm_save_seg_64(vcpu, buf, i);
8116 }
8117 #endif
8118
8119 static void enter_smm(struct kvm_vcpu *vcpu)
8120 {
8121         struct kvm_segment cs, ds;
8122         struct desc_ptr dt;
8123         char buf[512];
8124         u32 cr0;
8125
8126         trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
8127         memset(buf, 0, 512);
8128 #ifdef CONFIG_X86_64
8129         if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
8130                 enter_smm_save_state_64(vcpu, buf);
8131         else
8132 #endif
8133                 enter_smm_save_state_32(vcpu, buf);
8134
8135         /*
8136          * Give pre_enter_smm() a chance to make ISA-specific changes to the
8137          * vCPU state (e.g. leave guest mode) after we've saved the state into
8138          * the SMM state-save area.
8139          */
8140         kvm_x86_ops.pre_enter_smm(vcpu, buf);
8141
8142         vcpu->arch.hflags |= HF_SMM_MASK;
8143         kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
8144
8145         if (kvm_x86_ops.get_nmi_mask(vcpu))
8146                 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
8147         else
8148                 kvm_x86_ops.set_nmi_mask(vcpu, true);
8149
8150         kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
8151         kvm_rip_write(vcpu, 0x8000);
8152
8153         cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
8154         kvm_x86_ops.set_cr0(vcpu, cr0);
8155         vcpu->arch.cr0 = cr0;
8156
8157         kvm_x86_ops.set_cr4(vcpu, 0);
8158
8159         /* Undocumented: IDT limit is set to zero on entry to SMM.  */
8160         dt.address = dt.size = 0;
8161         kvm_x86_ops.set_idt(vcpu, &dt);
8162
8163         __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
8164
8165         cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
8166         cs.base = vcpu->arch.smbase;
8167
8168         ds.selector = 0;
8169         ds.base = 0;
8170
8171         cs.limit    = ds.limit = 0xffffffff;
8172         cs.type     = ds.type = 0x3;
8173         cs.dpl      = ds.dpl = 0;
8174         cs.db       = ds.db = 0;
8175         cs.s        = ds.s = 1;
8176         cs.l        = ds.l = 0;
8177         cs.g        = ds.g = 1;
8178         cs.avl      = ds.avl = 0;
8179         cs.present  = ds.present = 1;
8180         cs.unusable = ds.unusable = 0;
8181         cs.padding  = ds.padding = 0;
8182
8183         kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
8184         kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
8185         kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
8186         kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
8187         kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
8188         kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
8189
8190 #ifdef CONFIG_X86_64
8191         if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
8192                 kvm_x86_ops.set_efer(vcpu, 0);
8193 #endif
8194
8195         kvm_update_cpuid_runtime(vcpu);
8196         kvm_mmu_reset_context(vcpu);
8197 }
8198
8199 static void process_smi(struct kvm_vcpu *vcpu)
8200 {
8201         vcpu->arch.smi_pending = true;
8202         kvm_make_request(KVM_REQ_EVENT, vcpu);
8203 }
8204
8205 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
8206                                        unsigned long *vcpu_bitmap)
8207 {
8208         cpumask_var_t cpus;
8209
8210         zalloc_cpumask_var(&cpus, GFP_ATOMIC);
8211
8212         kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC,
8213                                     NULL, vcpu_bitmap, cpus);
8214
8215         free_cpumask_var(cpus);
8216 }
8217
8218 void kvm_make_scan_ioapic_request(struct kvm *kvm)
8219 {
8220         kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
8221 }
8222
8223 void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
8224 {
8225         if (!lapic_in_kernel(vcpu))
8226                 return;
8227
8228         vcpu->arch.apicv_active = kvm_apicv_activated(vcpu->kvm);
8229         kvm_apic_update_apicv(vcpu);
8230         kvm_x86_ops.refresh_apicv_exec_ctrl(vcpu);
8231 }
8232 EXPORT_SYMBOL_GPL(kvm_vcpu_update_apicv);
8233
8234 /*
8235  * NOTE: Do not hold any lock prior to calling this.
8236  *
8237  * In particular, kvm_request_apicv_update() expects kvm->srcu not to be
8238  * locked, because it calls __x86_set_memory_region() which does
8239  * synchronize_srcu(&kvm->srcu).
8240  */
8241 void kvm_request_apicv_update(struct kvm *kvm, bool activate, ulong bit)
8242 {
8243         struct kvm_vcpu *except;
8244         unsigned long old, new, expected;
8245
8246         if (!kvm_x86_ops.check_apicv_inhibit_reasons ||
8247             !kvm_x86_ops.check_apicv_inhibit_reasons(bit))
8248                 return;
8249
8250         old = READ_ONCE(kvm->arch.apicv_inhibit_reasons);
8251         do {
8252                 expected = new = old;
8253                 if (activate)
8254                         __clear_bit(bit, &new);
8255                 else
8256                         __set_bit(bit, &new);
8257                 if (new == old)
8258                         break;
8259                 old = cmpxchg(&kvm->arch.apicv_inhibit_reasons, expected, new);
8260         } while (old != expected);
8261
8262         if (!!old == !!new)
8263                 return;
8264
8265         trace_kvm_apicv_update_request(activate, bit);
8266         if (kvm_x86_ops.pre_update_apicv_exec_ctrl)
8267                 kvm_x86_ops.pre_update_apicv_exec_ctrl(kvm, activate);
8268
8269         /*
8270          * Sending request to update APICV for all other vcpus,
8271          * while update the calling vcpu immediately instead of
8272          * waiting for another #VMEXIT to handle the request.
8273          */
8274         except = kvm_get_running_vcpu();
8275         kvm_make_all_cpus_request_except(kvm, KVM_REQ_APICV_UPDATE,
8276                                          except);
8277         if (except)
8278                 kvm_vcpu_update_apicv(except);
8279 }
8280 EXPORT_SYMBOL_GPL(kvm_request_apicv_update);
8281
8282 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
8283 {
8284         if (!kvm_apic_present(vcpu))
8285                 return;
8286
8287         bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
8288
8289         if (irqchip_split(vcpu->kvm))
8290                 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
8291         else {
8292                 if (vcpu->arch.apicv_active)
8293                         kvm_x86_ops.sync_pir_to_irr(vcpu);
8294                 if (ioapic_in_kernel(vcpu->kvm))
8295                         kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
8296         }
8297
8298         if (is_guest_mode(vcpu))
8299                 vcpu->arch.load_eoi_exitmap_pending = true;
8300         else
8301                 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
8302 }
8303
8304 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
8305 {
8306         u64 eoi_exit_bitmap[4];
8307
8308         if (!kvm_apic_hw_enabled(vcpu->arch.apic))
8309                 return;
8310
8311         bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
8312                   vcpu_to_synic(vcpu)->vec_bitmap, 256);
8313         kvm_x86_ops.load_eoi_exitmap(vcpu, eoi_exit_bitmap);
8314 }
8315
8316 void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
8317                                             unsigned long start, unsigned long end)
8318 {
8319         unsigned long apic_address;
8320
8321         /*
8322          * The physical address of apic access page is stored in the VMCS.
8323          * Update it when it becomes invalid.
8324          */
8325         apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
8326         if (start <= apic_address && apic_address < end)
8327                 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
8328 }
8329
8330 void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
8331 {
8332         if (!lapic_in_kernel(vcpu))
8333                 return;
8334
8335         if (!kvm_x86_ops.set_apic_access_page_addr)
8336                 return;
8337
8338         kvm_x86_ops.set_apic_access_page_addr(vcpu);
8339 }
8340
8341 void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
8342 {
8343         smp_send_reschedule(vcpu->cpu);
8344 }
8345 EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
8346
8347 /*
8348  * Returns 1 to let vcpu_run() continue the guest execution loop without
8349  * exiting to the userspace.  Otherwise, the value will be returned to the
8350  * userspace.
8351  */
8352 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
8353 {
8354         int r;
8355         bool req_int_win =
8356                 dm_request_for_irq_injection(vcpu) &&
8357                 kvm_cpu_accept_dm_intr(vcpu);
8358         fastpath_t exit_fastpath;
8359
8360         bool req_immediate_exit = false;
8361
8362         if (kvm_request_pending(vcpu)) {
8363                 if (kvm_check_request(KVM_REQ_GET_VMCS12_PAGES, vcpu)) {
8364                         if (unlikely(!kvm_x86_ops.nested_ops->get_vmcs12_pages(vcpu))) {
8365                                 r = 0;
8366                                 goto out;
8367                         }
8368                 }
8369                 if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
8370                         kvm_mmu_unload(vcpu);
8371                 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
8372                         __kvm_migrate_timers(vcpu);
8373                 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
8374                         kvm_gen_update_masterclock(vcpu->kvm);
8375                 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
8376                         kvm_gen_kvmclock_update(vcpu);
8377                 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
8378                         r = kvm_guest_time_update(vcpu);
8379                         if (unlikely(r))
8380                                 goto out;
8381                 }
8382                 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
8383                         kvm_mmu_sync_roots(vcpu);
8384                 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
8385                         kvm_mmu_load_pgd(vcpu);
8386                 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) {
8387                         kvm_vcpu_flush_tlb_all(vcpu);
8388
8389                         /* Flushing all ASIDs flushes the current ASID... */
8390                         kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
8391                 }
8392                 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
8393                         kvm_vcpu_flush_tlb_current(vcpu);
8394                 if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu))
8395                         kvm_vcpu_flush_tlb_guest(vcpu);
8396
8397                 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
8398                         vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
8399                         r = 0;
8400                         goto out;
8401                 }
8402                 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
8403                         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
8404                         vcpu->mmio_needed = 0;
8405                         r = 0;
8406                         goto out;
8407                 }
8408                 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
8409                         /* Page is swapped out. Do synthetic halt */
8410                         vcpu->arch.apf.halted = true;
8411                         r = 1;
8412                         goto out;
8413                 }
8414                 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
8415                         record_steal_time(vcpu);
8416                 if (kvm_check_request(KVM_REQ_SMI, vcpu))
8417                         process_smi(vcpu);
8418                 if (kvm_check_request(KVM_REQ_NMI, vcpu))
8419                         process_nmi(vcpu);
8420                 if (kvm_check_request(KVM_REQ_PMU, vcpu))
8421                         kvm_pmu_handle_event(vcpu);
8422                 if (kvm_check_request(KVM_REQ_PMI, vcpu))
8423                         kvm_pmu_deliver_pmi(vcpu);
8424                 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
8425                         BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
8426                         if (test_bit(vcpu->arch.pending_ioapic_eoi,
8427                                      vcpu->arch.ioapic_handled_vectors)) {
8428                                 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
8429                                 vcpu->run->eoi.vector =
8430                                                 vcpu->arch.pending_ioapic_eoi;
8431                                 r = 0;
8432                                 goto out;
8433                         }
8434                 }
8435                 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
8436                         vcpu_scan_ioapic(vcpu);
8437                 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
8438                         vcpu_load_eoi_exitmap(vcpu);
8439                 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
8440                         kvm_vcpu_reload_apic_access_page(vcpu);
8441                 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
8442                         vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8443                         vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
8444                         r = 0;
8445                         goto out;
8446                 }
8447                 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
8448                         vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
8449                         vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
8450                         r = 0;
8451                         goto out;
8452                 }
8453                 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
8454                         vcpu->run->exit_reason = KVM_EXIT_HYPERV;
8455                         vcpu->run->hyperv = vcpu->arch.hyperv.exit;
8456                         r = 0;
8457                         goto out;
8458                 }
8459
8460                 /*
8461                  * KVM_REQ_HV_STIMER has to be processed after
8462                  * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
8463                  * depend on the guest clock being up-to-date
8464                  */
8465                 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
8466                         kvm_hv_process_stimers(vcpu);
8467                 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
8468                         kvm_vcpu_update_apicv(vcpu);
8469                 if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
8470                         kvm_check_async_pf_completion(vcpu);
8471         }
8472
8473         if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
8474                 ++vcpu->stat.req_event;
8475                 kvm_apic_accept_events(vcpu);
8476                 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
8477                         r = 1;
8478                         goto out;
8479                 }
8480
8481                 inject_pending_event(vcpu, &req_immediate_exit);
8482                 if (req_int_win)
8483                         kvm_x86_ops.enable_irq_window(vcpu);
8484
8485                 if (kvm_lapic_enabled(vcpu)) {
8486                         update_cr8_intercept(vcpu);
8487                         kvm_lapic_sync_to_vapic(vcpu);
8488                 }
8489         }
8490
8491         r = kvm_mmu_reload(vcpu);
8492         if (unlikely(r)) {
8493                 goto cancel_injection;
8494         }
8495
8496         preempt_disable();
8497
8498         kvm_x86_ops.prepare_guest_switch(vcpu);
8499
8500         /*
8501          * Disable IRQs before setting IN_GUEST_MODE.  Posted interrupt
8502          * IPI are then delayed after guest entry, which ensures that they
8503          * result in virtual interrupt delivery.
8504          */
8505         local_irq_disable();
8506         vcpu->mode = IN_GUEST_MODE;
8507
8508         srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8509
8510         /*
8511          * 1) We should set ->mode before checking ->requests.  Please see
8512          * the comment in kvm_vcpu_exiting_guest_mode().
8513          *
8514          * 2) For APICv, we should set ->mode before checking PID.ON. This
8515          * pairs with the memory barrier implicit in pi_test_and_set_on
8516          * (see vmx_deliver_posted_interrupt).
8517          *
8518          * 3) This also orders the write to mode from any reads to the page
8519          * tables done while the VCPU is running.  Please see the comment
8520          * in kvm_flush_remote_tlbs.
8521          */
8522         smp_mb__after_srcu_read_unlock();
8523
8524         /*
8525          * This handles the case where a posted interrupt was
8526          * notified with kvm_vcpu_kick.
8527          */
8528         if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
8529                 kvm_x86_ops.sync_pir_to_irr(vcpu);
8530
8531         if (kvm_vcpu_exit_request(vcpu)) {
8532                 vcpu->mode = OUTSIDE_GUEST_MODE;
8533                 smp_wmb();
8534                 local_irq_enable();
8535                 preempt_enable();
8536                 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8537                 r = 1;
8538                 goto cancel_injection;
8539         }
8540
8541         if (req_immediate_exit) {
8542                 kvm_make_request(KVM_REQ_EVENT, vcpu);
8543                 kvm_x86_ops.request_immediate_exit(vcpu);
8544         }
8545
8546         trace_kvm_entry(vcpu->vcpu_id);
8547
8548         fpregs_assert_state_consistent();
8549         if (test_thread_flag(TIF_NEED_FPU_LOAD))
8550                 switch_fpu_return();
8551
8552         if (unlikely(vcpu->arch.switch_db_regs)) {
8553                 set_debugreg(0, 7);
8554                 set_debugreg(vcpu->arch.eff_db[0], 0);
8555                 set_debugreg(vcpu->arch.eff_db[1], 1);
8556                 set_debugreg(vcpu->arch.eff_db[2], 2);
8557                 set_debugreg(vcpu->arch.eff_db[3], 3);
8558                 set_debugreg(vcpu->arch.dr6, 6);
8559                 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8560         }
8561
8562         exit_fastpath = kvm_x86_ops.run(vcpu);
8563
8564         /*
8565          * Do this here before restoring debug registers on the host.  And
8566          * since we do this before handling the vmexit, a DR access vmexit
8567          * can (a) read the correct value of the debug registers, (b) set
8568          * KVM_DEBUGREG_WONT_EXIT again.
8569          */
8570         if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
8571                 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
8572                 kvm_x86_ops.sync_dirty_debug_regs(vcpu);
8573                 kvm_update_dr0123(vcpu);
8574                 kvm_update_dr7(vcpu);
8575                 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
8576         }
8577
8578         /*
8579          * If the guest has used debug registers, at least dr7
8580          * will be disabled while returning to the host.
8581          * If we don't have active breakpoints in the host, we don't
8582          * care about the messed up debug address registers. But if
8583          * we have some of them active, restore the old state.
8584          */
8585         if (hw_breakpoint_active())
8586                 hw_breakpoint_restore();
8587
8588         vcpu->arch.last_vmentry_cpu = vcpu->cpu;
8589         vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
8590
8591         vcpu->mode = OUTSIDE_GUEST_MODE;
8592         smp_wmb();
8593
8594         kvm_x86_ops.handle_exit_irqoff(vcpu);
8595
8596         /*
8597          * Consume any pending interrupts, including the possible source of
8598          * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
8599          * An instruction is required after local_irq_enable() to fully unblock
8600          * interrupts on processors that implement an interrupt shadow, the
8601          * stat.exits increment will do nicely.
8602          */
8603         kvm_before_interrupt(vcpu);
8604         local_irq_enable();
8605         ++vcpu->stat.exits;
8606         local_irq_disable();
8607         kvm_after_interrupt(vcpu);
8608
8609         if (lapic_in_kernel(vcpu)) {
8610                 s64 delta = vcpu->arch.apic->lapic_timer.advance_expire_delta;
8611                 if (delta != S64_MIN) {
8612                         trace_kvm_wait_lapic_expire(vcpu->vcpu_id, delta);
8613                         vcpu->arch.apic->lapic_timer.advance_expire_delta = S64_MIN;
8614                 }
8615         }
8616
8617         local_irq_enable();
8618         preempt_enable();
8619
8620         vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8621
8622         /*
8623          * Profile KVM exit RIPs:
8624          */
8625         if (unlikely(prof_on == KVM_PROFILING)) {
8626                 unsigned long rip = kvm_rip_read(vcpu);
8627                 profile_hit(KVM_PROFILING, (void *)rip);
8628         }
8629
8630         if (unlikely(vcpu->arch.tsc_always_catchup))
8631                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
8632
8633         if (vcpu->arch.apic_attention)
8634                 kvm_lapic_sync_from_vapic(vcpu);
8635
8636         r = kvm_x86_ops.handle_exit(vcpu, exit_fastpath);
8637         return r;
8638
8639 cancel_injection:
8640         if (req_immediate_exit)
8641                 kvm_make_request(KVM_REQ_EVENT, vcpu);
8642         kvm_x86_ops.cancel_injection(vcpu);
8643         if (unlikely(vcpu->arch.apic_attention))
8644                 kvm_lapic_sync_from_vapic(vcpu);
8645 out:
8646         return r;
8647 }
8648
8649 static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
8650 {
8651         if (!kvm_arch_vcpu_runnable(vcpu) &&
8652             (!kvm_x86_ops.pre_block || kvm_x86_ops.pre_block(vcpu) == 0)) {
8653                 srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8654                 kvm_vcpu_block(vcpu);
8655                 vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8656
8657                 if (kvm_x86_ops.post_block)
8658                         kvm_x86_ops.post_block(vcpu);
8659
8660                 if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
8661                         return 1;
8662         }
8663
8664         kvm_apic_accept_events(vcpu);
8665         switch(vcpu->arch.mp_state) {
8666         case KVM_MP_STATE_HALTED:
8667                 vcpu->arch.pv.pv_unhalted = false;
8668                 vcpu->arch.mp_state =
8669                         KVM_MP_STATE_RUNNABLE;
8670                 fallthrough;
8671         case KVM_MP_STATE_RUNNABLE:
8672                 vcpu->arch.apf.halted = false;
8673                 break;
8674         case KVM_MP_STATE_INIT_RECEIVED:
8675                 break;
8676         default:
8677                 return -EINTR;
8678         }
8679         return 1;
8680 }
8681
8682 static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
8683 {
8684         if (is_guest_mode(vcpu))
8685                 kvm_x86_ops.nested_ops->check_events(vcpu);
8686
8687         return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
8688                 !vcpu->arch.apf.halted);
8689 }
8690
8691 static int vcpu_run(struct kvm_vcpu *vcpu)
8692 {
8693         int r;
8694         struct kvm *kvm = vcpu->kvm;
8695
8696         vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8697         vcpu->arch.l1tf_flush_l1d = true;
8698
8699         for (;;) {
8700                 if (kvm_vcpu_running(vcpu)) {
8701                         r = vcpu_enter_guest(vcpu);
8702                 } else {
8703                         r = vcpu_block(kvm, vcpu);
8704                 }
8705
8706                 if (r <= 0)
8707                         break;
8708
8709                 kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
8710                 if (kvm_cpu_has_pending_timer(vcpu))
8711                         kvm_inject_pending_timer_irqs(vcpu);
8712
8713                 if (dm_request_for_irq_injection(vcpu) &&
8714                         kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
8715                         r = 0;
8716                         vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
8717                         ++vcpu->stat.request_irq_exits;
8718                         break;
8719                 }
8720
8721                 if (__xfer_to_guest_mode_work_pending()) {
8722                         srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8723                         r = xfer_to_guest_mode_handle_work(vcpu);
8724                         if (r)
8725                                 return r;
8726                         vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
8727                 }
8728         }
8729
8730         srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
8731
8732         return r;
8733 }
8734
8735 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
8736 {
8737         int r;
8738
8739         vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
8740         r = kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
8741         srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
8742         return r;
8743 }
8744
8745 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
8746 {
8747         BUG_ON(!vcpu->arch.pio.count);
8748
8749         return complete_emulated_io(vcpu);
8750 }
8751
8752 /*
8753  * Implements the following, as a state machine:
8754  *
8755  * read:
8756  *   for each fragment
8757  *     for each mmio piece in the fragment
8758  *       write gpa, len
8759  *       exit
8760  *       copy data
8761  *   execute insn
8762  *
8763  * write:
8764  *   for each fragment
8765  *     for each mmio piece in the fragment
8766  *       write gpa, len
8767  *       copy data
8768  *       exit
8769  */
8770 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
8771 {
8772         struct kvm_run *run = vcpu->run;
8773         struct kvm_mmio_fragment *frag;
8774         unsigned len;
8775
8776         BUG_ON(!vcpu->mmio_needed);
8777
8778         /* Complete previous fragment */
8779         frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
8780         len = min(8u, frag->len);
8781         if (!vcpu->mmio_is_write)
8782                 memcpy(frag->data, run->mmio.data, len);
8783
8784         if (frag->len <= 8) {
8785                 /* Switch to the next fragment. */
8786                 frag++;
8787                 vcpu->mmio_cur_fragment++;
8788         } else {
8789                 /* Go forward to the next mmio piece. */
8790                 frag->data += len;
8791                 frag->gpa += len;
8792                 frag->len -= len;
8793         }
8794
8795         if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
8796                 vcpu->mmio_needed = 0;
8797
8798                 /* FIXME: return into emulator if single-stepping.  */
8799                 if (vcpu->mmio_is_write)
8800                         return 1;
8801                 vcpu->mmio_read_completed = 1;
8802                 return complete_emulated_io(vcpu);
8803         }
8804
8805         run->exit_reason = KVM_EXIT_MMIO;
8806         run->mmio.phys_addr = frag->gpa;
8807         if (vcpu->mmio_is_write)
8808                 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
8809         run->mmio.len = min(8u, frag->len);
8810         run->mmio.is_write = vcpu->mmio_is_write;
8811         vcpu->arch.complete_userspace_io = complete_emulated_mmio;
8812         return 0;
8813 }
8814
8815 static void kvm_save_current_fpu(struct fpu *fpu)
8816 {
8817         /*
8818          * If the target FPU state is not resident in the CPU registers, just
8819          * memcpy() from current, else save CPU state directly to the target.
8820          */
8821         if (test_thread_flag(TIF_NEED_FPU_LOAD))
8822                 memcpy(&fpu->state, &current->thread.fpu.state,
8823                        fpu_kernel_xstate_size);
8824         else
8825                 copy_fpregs_to_fpstate(fpu);
8826 }
8827
8828 /* Swap (qemu) user FPU context for the guest FPU context. */
8829 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
8830 {
8831         fpregs_lock();
8832
8833         kvm_save_current_fpu(vcpu->arch.user_fpu);
8834
8835         /* PKRU is separately restored in kvm_x86_ops.run.  */
8836         __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu->state,
8837                                 ~XFEATURE_MASK_PKRU);
8838
8839         fpregs_mark_activate();
8840         fpregs_unlock();
8841
8842         trace_kvm_fpu(1);
8843 }
8844
8845 /* When vcpu_run ends, restore user space FPU context. */
8846 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
8847 {
8848         fpregs_lock();
8849
8850         kvm_save_current_fpu(vcpu->arch.guest_fpu);
8851
8852         copy_kernel_to_fpregs(&vcpu->arch.user_fpu->state);
8853
8854         fpregs_mark_activate();
8855         fpregs_unlock();
8856
8857         ++vcpu->stat.fpu_reload;
8858         trace_kvm_fpu(0);
8859 }
8860
8861 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
8862 {
8863         struct kvm_run *kvm_run = vcpu->run;
8864         int r;
8865
8866         vcpu_load(vcpu);
8867         kvm_sigset_activate(vcpu);
8868         kvm_load_guest_fpu(vcpu);
8869
8870         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
8871                 if (kvm_run->immediate_exit) {
8872                         r = -EINTR;
8873                         goto out;
8874                 }
8875                 kvm_vcpu_block(vcpu);
8876                 kvm_apic_accept_events(vcpu);
8877                 kvm_clear_request(KVM_REQ_UNHALT, vcpu);
8878                 r = -EAGAIN;
8879                 if (signal_pending(current)) {
8880                         r = -EINTR;
8881                         kvm_run->exit_reason = KVM_EXIT_INTR;
8882                         ++vcpu->stat.signal_exits;
8883                 }
8884                 goto out;
8885         }
8886
8887         if (kvm_run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
8888                 r = -EINVAL;
8889                 goto out;
8890         }
8891
8892         if (kvm_run->kvm_dirty_regs) {
8893                 r = sync_regs(vcpu);
8894                 if (r != 0)
8895                         goto out;
8896         }
8897
8898         /* re-sync apic's tpr */
8899         if (!lapic_in_kernel(vcpu)) {
8900                 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
8901                         r = -EINVAL;
8902                         goto out;
8903                 }
8904         }
8905
8906         if (unlikely(vcpu->arch.complete_userspace_io)) {
8907                 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
8908                 vcpu->arch.complete_userspace_io = NULL;
8909                 r = cui(vcpu);
8910                 if (r <= 0)
8911                         goto out;
8912         } else
8913                 WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
8914
8915         if (kvm_run->immediate_exit)
8916                 r = -EINTR;
8917         else
8918                 r = vcpu_run(vcpu);
8919
8920 out:
8921         kvm_put_guest_fpu(vcpu);
8922         if (kvm_run->kvm_valid_regs)
8923                 store_regs(vcpu);
8924         post_kvm_run_save(vcpu);
8925         kvm_sigset_deactivate(vcpu);
8926
8927         vcpu_put(vcpu);
8928         return r;
8929 }
8930
8931 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8932 {
8933         if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
8934                 /*
8935                  * We are here if userspace calls get_regs() in the middle of
8936                  * instruction emulation. Registers state needs to be copied
8937                  * back from emulation context to vcpu. Userspace shouldn't do
8938                  * that usually, but some bad designed PV devices (vmware
8939                  * backdoor interface) need this to work
8940                  */
8941                 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
8942                 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8943         }
8944         regs->rax = kvm_rax_read(vcpu);
8945         regs->rbx = kvm_rbx_read(vcpu);
8946         regs->rcx = kvm_rcx_read(vcpu);
8947         regs->rdx = kvm_rdx_read(vcpu);
8948         regs->rsi = kvm_rsi_read(vcpu);
8949         regs->rdi = kvm_rdi_read(vcpu);
8950         regs->rsp = kvm_rsp_read(vcpu);
8951         regs->rbp = kvm_rbp_read(vcpu);
8952 #ifdef CONFIG_X86_64
8953         regs->r8 = kvm_r8_read(vcpu);
8954         regs->r9 = kvm_r9_read(vcpu);
8955         regs->r10 = kvm_r10_read(vcpu);
8956         regs->r11 = kvm_r11_read(vcpu);
8957         regs->r12 = kvm_r12_read(vcpu);
8958         regs->r13 = kvm_r13_read(vcpu);
8959         regs->r14 = kvm_r14_read(vcpu);
8960         regs->r15 = kvm_r15_read(vcpu);
8961 #endif
8962
8963         regs->rip = kvm_rip_read(vcpu);
8964         regs->rflags = kvm_get_rflags(vcpu);
8965 }
8966
8967 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8968 {
8969         vcpu_load(vcpu);
8970         __get_regs(vcpu, regs);
8971         vcpu_put(vcpu);
8972         return 0;
8973 }
8974
8975 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
8976 {
8977         vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
8978         vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
8979
8980         kvm_rax_write(vcpu, regs->rax);
8981         kvm_rbx_write(vcpu, regs->rbx);
8982         kvm_rcx_write(vcpu, regs->rcx);
8983         kvm_rdx_write(vcpu, regs->rdx);
8984         kvm_rsi_write(vcpu, regs->rsi);
8985         kvm_rdi_write(vcpu, regs->rdi);
8986         kvm_rsp_write(vcpu, regs->rsp);
8987         kvm_rbp_write(vcpu, regs->rbp);
8988 #ifdef CONFIG_X86_64
8989         kvm_r8_write(vcpu, regs->r8);
8990         kvm_r9_write(vcpu, regs->r9);
8991         kvm_r10_write(vcpu, regs->r10);
8992         kvm_r11_write(vcpu, regs->r11);
8993         kvm_r12_write(vcpu, regs->r12);
8994         kvm_r13_write(vcpu, regs->r13);
8995         kvm_r14_write(vcpu, regs->r14);
8996         kvm_r15_write(vcpu, regs->r15);
8997 #endif
8998
8999         kvm_rip_write(vcpu, regs->rip);
9000         kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
9001
9002         vcpu->arch.exception.pending = false;
9003
9004         kvm_make_request(KVM_REQ_EVENT, vcpu);
9005 }
9006
9007 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
9008 {
9009         vcpu_load(vcpu);
9010         __set_regs(vcpu, regs);
9011         vcpu_put(vcpu);
9012         return 0;
9013 }
9014
9015 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
9016 {
9017         struct kvm_segment cs;
9018
9019         kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
9020         *db = cs.db;
9021         *l = cs.l;
9022 }
9023 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
9024
9025 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9026 {
9027         struct desc_ptr dt;
9028
9029         kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9030         kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9031         kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9032         kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9033         kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9034         kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
9035
9036         kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9037         kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
9038
9039         kvm_x86_ops.get_idt(vcpu, &dt);
9040         sregs->idt.limit = dt.size;
9041         sregs->idt.base = dt.address;
9042         kvm_x86_ops.get_gdt(vcpu, &dt);
9043         sregs->gdt.limit = dt.size;
9044         sregs->gdt.base = dt.address;
9045
9046         sregs->cr0 = kvm_read_cr0(vcpu);
9047         sregs->cr2 = vcpu->arch.cr2;
9048         sregs->cr3 = kvm_read_cr3(vcpu);
9049         sregs->cr4 = kvm_read_cr4(vcpu);
9050         sregs->cr8 = kvm_get_cr8(vcpu);
9051         sregs->efer = vcpu->arch.efer;
9052         sregs->apic_base = kvm_get_apic_base(vcpu);
9053
9054         memset(sregs->interrupt_bitmap, 0, sizeof(sregs->interrupt_bitmap));
9055
9056         if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
9057                 set_bit(vcpu->arch.interrupt.nr,
9058                         (unsigned long *)sregs->interrupt_bitmap);
9059 }
9060
9061 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
9062                                   struct kvm_sregs *sregs)
9063 {
9064         vcpu_load(vcpu);
9065         __get_sregs(vcpu, sregs);
9066         vcpu_put(vcpu);
9067         return 0;
9068 }
9069
9070 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
9071                                     struct kvm_mp_state *mp_state)
9072 {
9073         vcpu_load(vcpu);
9074         if (kvm_mpx_supported())
9075                 kvm_load_guest_fpu(vcpu);
9076
9077         kvm_apic_accept_events(vcpu);
9078         if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
9079                                         vcpu->arch.pv.pv_unhalted)
9080                 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
9081         else
9082                 mp_state->mp_state = vcpu->arch.mp_state;
9083
9084         if (kvm_mpx_supported())
9085                 kvm_put_guest_fpu(vcpu);
9086         vcpu_put(vcpu);
9087         return 0;
9088 }
9089
9090 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
9091                                     struct kvm_mp_state *mp_state)
9092 {
9093         int ret = -EINVAL;
9094
9095         vcpu_load(vcpu);
9096
9097         if (!lapic_in_kernel(vcpu) &&
9098             mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
9099                 goto out;
9100
9101         /*
9102          * KVM_MP_STATE_INIT_RECEIVED means the processor is in
9103          * INIT state; latched init should be reported using
9104          * KVM_SET_VCPU_EVENTS, so reject it here.
9105          */
9106         if ((kvm_vcpu_latch_init(vcpu) || vcpu->arch.smi_pending) &&
9107             (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
9108              mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
9109                 goto out;
9110
9111         if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
9112                 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
9113                 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
9114         } else
9115                 vcpu->arch.mp_state = mp_state->mp_state;
9116         kvm_make_request(KVM_REQ_EVENT, vcpu);
9117
9118         ret = 0;
9119 out:
9120         vcpu_put(vcpu);
9121         return ret;
9122 }
9123
9124 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
9125                     int reason, bool has_error_code, u32 error_code)
9126 {
9127         struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9128         int ret;
9129
9130         init_emulate_ctxt(vcpu);
9131
9132         ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
9133                                    has_error_code, error_code);
9134         if (ret) {
9135                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9136                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
9137                 vcpu->run->internal.ndata = 0;
9138                 return 0;
9139         }
9140
9141         kvm_rip_write(vcpu, ctxt->eip);
9142         kvm_set_rflags(vcpu, ctxt->eflags);
9143         return 1;
9144 }
9145 EXPORT_SYMBOL_GPL(kvm_task_switch);
9146
9147 static int kvm_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9148 {
9149         if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
9150                 /*
9151                  * When EFER.LME and CR0.PG are set, the processor is in
9152                  * 64-bit mode (though maybe in a 32-bit code segment).
9153                  * CR4.PAE and EFER.LMA must be set.
9154                  */
9155                 if (!(sregs->cr4 & X86_CR4_PAE)
9156                     || !(sregs->efer & EFER_LMA))
9157                         return -EINVAL;
9158         } else {
9159                 /*
9160                  * Not in 64-bit mode: EFER.LMA is clear and the code
9161                  * segment cannot be 64-bit.
9162                  */
9163                 if (sregs->efer & EFER_LMA || sregs->cs.l)
9164                         return -EINVAL;
9165         }
9166
9167         return kvm_valid_cr4(vcpu, sregs->cr4);
9168 }
9169
9170 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
9171 {
9172         struct msr_data apic_base_msr;
9173         int mmu_reset_needed = 0;
9174         int cpuid_update_needed = 0;
9175         int pending_vec, max_bits, idx;
9176         struct desc_ptr dt;
9177         int ret = -EINVAL;
9178
9179         if (kvm_valid_sregs(vcpu, sregs))
9180                 goto out;
9181
9182         apic_base_msr.data = sregs->apic_base;
9183         apic_base_msr.host_initiated = true;
9184         if (kvm_set_apic_base(vcpu, &apic_base_msr))
9185                 goto out;
9186
9187         dt.size = sregs->idt.limit;
9188         dt.address = sregs->idt.base;
9189         kvm_x86_ops.set_idt(vcpu, &dt);
9190         dt.size = sregs->gdt.limit;
9191         dt.address = sregs->gdt.base;
9192         kvm_x86_ops.set_gdt(vcpu, &dt);
9193
9194         vcpu->arch.cr2 = sregs->cr2;
9195         mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
9196         vcpu->arch.cr3 = sregs->cr3;
9197         kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
9198
9199         kvm_set_cr8(vcpu, sregs->cr8);
9200
9201         mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
9202         kvm_x86_ops.set_efer(vcpu, sregs->efer);
9203
9204         mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
9205         kvm_x86_ops.set_cr0(vcpu, sregs->cr0);
9206         vcpu->arch.cr0 = sregs->cr0;
9207
9208         mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
9209         cpuid_update_needed |= ((kvm_read_cr4(vcpu) ^ sregs->cr4) &
9210                                 (X86_CR4_OSXSAVE | X86_CR4_PKE));
9211         kvm_x86_ops.set_cr4(vcpu, sregs->cr4);
9212         if (cpuid_update_needed)
9213                 kvm_update_cpuid_runtime(vcpu);
9214
9215         idx = srcu_read_lock(&vcpu->kvm->srcu);
9216         if (is_pae_paging(vcpu)) {
9217                 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
9218                 mmu_reset_needed = 1;
9219         }
9220         srcu_read_unlock(&vcpu->kvm->srcu, idx);
9221
9222         if (mmu_reset_needed)
9223                 kvm_mmu_reset_context(vcpu);
9224
9225         max_bits = KVM_NR_INTERRUPTS;
9226         pending_vec = find_first_bit(
9227                 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
9228         if (pending_vec < max_bits) {
9229                 kvm_queue_interrupt(vcpu, pending_vec, false);
9230                 pr_debug("Set back pending irq %d\n", pending_vec);
9231         }
9232
9233         kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
9234         kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
9235         kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
9236         kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
9237         kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
9238         kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
9239
9240         kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
9241         kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
9242
9243         update_cr8_intercept(vcpu);
9244
9245         /* Older userspace won't unhalt the vcpu on reset. */
9246         if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
9247             sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
9248             !is_protmode(vcpu))
9249                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9250
9251         kvm_make_request(KVM_REQ_EVENT, vcpu);
9252
9253         ret = 0;
9254 out:
9255         return ret;
9256 }
9257
9258 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
9259                                   struct kvm_sregs *sregs)
9260 {
9261         int ret;
9262
9263         vcpu_load(vcpu);
9264         ret = __set_sregs(vcpu, sregs);
9265         vcpu_put(vcpu);
9266         return ret;
9267 }
9268
9269 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
9270                                         struct kvm_guest_debug *dbg)
9271 {
9272         unsigned long rflags;
9273         int i, r;
9274
9275         vcpu_load(vcpu);
9276
9277         if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
9278                 r = -EBUSY;
9279                 if (vcpu->arch.exception.pending)
9280                         goto out;
9281                 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
9282                         kvm_queue_exception(vcpu, DB_VECTOR);
9283                 else
9284                         kvm_queue_exception(vcpu, BP_VECTOR);
9285         }
9286
9287         /*
9288          * Read rflags as long as potentially injected trace flags are still
9289          * filtered out.
9290          */
9291         rflags = kvm_get_rflags(vcpu);
9292
9293         vcpu->guest_debug = dbg->control;
9294         if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
9295                 vcpu->guest_debug = 0;
9296
9297         if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
9298                 for (i = 0; i < KVM_NR_DB_REGS; ++i)
9299                         vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
9300                 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
9301         } else {
9302                 for (i = 0; i < KVM_NR_DB_REGS; i++)
9303                         vcpu->arch.eff_db[i] = vcpu->arch.db[i];
9304         }
9305         kvm_update_dr7(vcpu);
9306
9307         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9308                 vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
9309                         get_segment_base(vcpu, VCPU_SREG_CS);
9310
9311         /*
9312          * Trigger an rflags update that will inject or remove the trace
9313          * flags.
9314          */
9315         kvm_set_rflags(vcpu, rflags);
9316
9317         kvm_x86_ops.update_exception_bitmap(vcpu);
9318
9319         r = 0;
9320
9321 out:
9322         vcpu_put(vcpu);
9323         return r;
9324 }
9325
9326 /*
9327  * Translate a guest virtual address to a guest physical address.
9328  */
9329 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
9330                                     struct kvm_translation *tr)
9331 {
9332         unsigned long vaddr = tr->linear_address;
9333         gpa_t gpa;
9334         int idx;
9335
9336         vcpu_load(vcpu);
9337
9338         idx = srcu_read_lock(&vcpu->kvm->srcu);
9339         gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
9340         srcu_read_unlock(&vcpu->kvm->srcu, idx);
9341         tr->physical_address = gpa;
9342         tr->valid = gpa != UNMAPPED_GVA;
9343         tr->writeable = 1;
9344         tr->usermode = 0;
9345
9346         vcpu_put(vcpu);
9347         return 0;
9348 }
9349
9350 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
9351 {
9352         struct fxregs_state *fxsave;
9353
9354         vcpu_load(vcpu);
9355
9356         fxsave = &vcpu->arch.guest_fpu->state.fxsave;
9357         memcpy(fpu->fpr, fxsave->st_space, 128);
9358         fpu->fcw = fxsave->cwd;
9359         fpu->fsw = fxsave->swd;
9360         fpu->ftwx = fxsave->twd;
9361         fpu->last_opcode = fxsave->fop;
9362         fpu->last_ip = fxsave->rip;
9363         fpu->last_dp = fxsave->rdp;
9364         memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
9365
9366         vcpu_put(vcpu);
9367         return 0;
9368 }
9369
9370 int kvm_arch_vcpu_ioctl_set_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
9378         memcpy(fxsave->st_space, fpu->fpr, 128);
9379         fxsave->cwd = fpu->fcw;
9380         fxsave->swd = fpu->fsw;
9381         fxsave->twd = fpu->ftwx;
9382         fxsave->fop = fpu->last_opcode;
9383         fxsave->rip = fpu->last_ip;
9384         fxsave->rdp = fpu->last_dp;
9385         memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
9386
9387         vcpu_put(vcpu);
9388         return 0;
9389 }
9390
9391 static void store_regs(struct kvm_vcpu *vcpu)
9392 {
9393         BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
9394
9395         if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
9396                 __get_regs(vcpu, &vcpu->run->s.regs.regs);
9397
9398         if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
9399                 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
9400
9401         if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
9402                 kvm_vcpu_ioctl_x86_get_vcpu_events(
9403                                 vcpu, &vcpu->run->s.regs.events);
9404 }
9405
9406 static int sync_regs(struct kvm_vcpu *vcpu)
9407 {
9408         if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
9409                 return -EINVAL;
9410
9411         if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
9412                 __set_regs(vcpu, &vcpu->run->s.regs.regs);
9413                 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
9414         }
9415         if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
9416                 if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
9417                         return -EINVAL;
9418                 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
9419         }
9420         if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
9421                 if (kvm_vcpu_ioctl_x86_set_vcpu_events(
9422                                 vcpu, &vcpu->run->s.regs.events))
9423                         return -EINVAL;
9424                 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
9425         }
9426
9427         return 0;
9428 }
9429
9430 static void fx_init(struct kvm_vcpu *vcpu)
9431 {
9432         fpstate_init(&vcpu->arch.guest_fpu->state);
9433         if (boot_cpu_has(X86_FEATURE_XSAVES))
9434                 vcpu->arch.guest_fpu->state.xsave.header.xcomp_bv =
9435                         host_xcr0 | XSTATE_COMPACTION_ENABLED;
9436
9437         /*
9438          * Ensure guest xcr0 is valid for loading
9439          */
9440         vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9441
9442         vcpu->arch.cr0 |= X86_CR0_ET;
9443 }
9444
9445 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
9446 {
9447         if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
9448                 pr_warn_once("kvm: SMP vm created on host with unstable TSC; "
9449                              "guest TSC will not be reliable\n");
9450
9451         return 0;
9452 }
9453
9454 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
9455 {
9456         struct page *page;
9457         int r;
9458
9459         if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
9460                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
9461         else
9462                 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
9463
9464         kvm_set_tsc_khz(vcpu, max_tsc_khz);
9465
9466         r = kvm_mmu_create(vcpu);
9467         if (r < 0)
9468                 return r;
9469
9470         if (irqchip_in_kernel(vcpu->kvm)) {
9471                 r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
9472                 if (r < 0)
9473                         goto fail_mmu_destroy;
9474                 if (kvm_apicv_activated(vcpu->kvm))
9475                         vcpu->arch.apicv_active = true;
9476         } else
9477                 static_key_slow_inc(&kvm_no_apic_vcpu);
9478
9479         r = -ENOMEM;
9480
9481         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
9482         if (!page)
9483                 goto fail_free_lapic;
9484         vcpu->arch.pio_data = page_address(page);
9485
9486         vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
9487                                        GFP_KERNEL_ACCOUNT);
9488         if (!vcpu->arch.mce_banks)
9489                 goto fail_free_pio_data;
9490         vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
9491
9492         if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
9493                                 GFP_KERNEL_ACCOUNT))
9494                 goto fail_free_mce_banks;
9495
9496         if (!alloc_emulate_ctxt(vcpu))
9497                 goto free_wbinvd_dirty_mask;
9498
9499         vcpu->arch.user_fpu = kmem_cache_zalloc(x86_fpu_cache,
9500                                                 GFP_KERNEL_ACCOUNT);
9501         if (!vcpu->arch.user_fpu) {
9502                 pr_err("kvm: failed to allocate userspace's fpu\n");
9503                 goto free_emulate_ctxt;
9504         }
9505
9506         vcpu->arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
9507                                                  GFP_KERNEL_ACCOUNT);
9508         if (!vcpu->arch.guest_fpu) {
9509                 pr_err("kvm: failed to allocate vcpu's fpu\n");
9510                 goto free_user_fpu;
9511         }
9512         fx_init(vcpu);
9513
9514         vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
9515
9516         vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
9517
9518         kvm_async_pf_hash_reset(vcpu);
9519         kvm_pmu_init(vcpu);
9520
9521         vcpu->arch.pending_external_vector = -1;
9522         vcpu->arch.preempted_in_kernel = false;
9523
9524         kvm_hv_vcpu_init(vcpu);
9525
9526         r = kvm_x86_ops.vcpu_create(vcpu);
9527         if (r)
9528                 goto free_guest_fpu;
9529
9530         vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
9531         vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
9532         kvm_vcpu_mtrr_init(vcpu);
9533         vcpu_load(vcpu);
9534         kvm_vcpu_reset(vcpu, false);
9535         kvm_init_mmu(vcpu, false);
9536         vcpu_put(vcpu);
9537         return 0;
9538
9539 free_guest_fpu:
9540         kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
9541 free_user_fpu:
9542         kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
9543 free_emulate_ctxt:
9544         kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
9545 free_wbinvd_dirty_mask:
9546         free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9547 fail_free_mce_banks:
9548         kfree(vcpu->arch.mce_banks);
9549 fail_free_pio_data:
9550         free_page((unsigned long)vcpu->arch.pio_data);
9551 fail_free_lapic:
9552         kvm_free_lapic(vcpu);
9553 fail_mmu_destroy:
9554         kvm_mmu_destroy(vcpu);
9555         return r;
9556 }
9557
9558 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
9559 {
9560         struct msr_data msr;
9561         struct kvm *kvm = vcpu->kvm;
9562
9563         kvm_hv_vcpu_postcreate(vcpu);
9564
9565         if (mutex_lock_killable(&vcpu->mutex))
9566                 return;
9567         vcpu_load(vcpu);
9568         msr.data = 0x0;
9569         msr.index = MSR_IA32_TSC;
9570         msr.host_initiated = true;
9571         kvm_write_tsc(vcpu, &msr);
9572         vcpu_put(vcpu);
9573
9574         /* poll control enabled by default */
9575         vcpu->arch.msr_kvm_poll_control = 1;
9576
9577         mutex_unlock(&vcpu->mutex);
9578
9579         if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
9580                 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
9581                                                 KVMCLOCK_SYNC_PERIOD);
9582 }
9583
9584 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
9585 {
9586         struct gfn_to_pfn_cache *cache = &vcpu->arch.st.cache;
9587         int idx;
9588
9589         kvm_release_pfn(cache->pfn, cache->dirty, cache);
9590
9591         kvmclock_reset(vcpu);
9592
9593         kvm_x86_ops.vcpu_free(vcpu);
9594
9595         kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
9596         free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
9597         kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
9598         kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
9599
9600         kvm_hv_vcpu_uninit(vcpu);
9601         kvm_pmu_destroy(vcpu);
9602         kfree(vcpu->arch.mce_banks);
9603         kvm_free_lapic(vcpu);
9604         idx = srcu_read_lock(&vcpu->kvm->srcu);
9605         kvm_mmu_destroy(vcpu);
9606         srcu_read_unlock(&vcpu->kvm->srcu, idx);
9607         free_page((unsigned long)vcpu->arch.pio_data);
9608         if (!lapic_in_kernel(vcpu))
9609                 static_key_slow_dec(&kvm_no_apic_vcpu);
9610 }
9611
9612 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
9613 {
9614         kvm_lapic_reset(vcpu, init_event);
9615
9616         vcpu->arch.hflags = 0;
9617
9618         vcpu->arch.smi_pending = 0;
9619         vcpu->arch.smi_count = 0;
9620         atomic_set(&vcpu->arch.nmi_queued, 0);
9621         vcpu->arch.nmi_pending = 0;
9622         vcpu->arch.nmi_injected = false;
9623         kvm_clear_interrupt_queue(vcpu);
9624         kvm_clear_exception_queue(vcpu);
9625
9626         memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
9627         kvm_update_dr0123(vcpu);
9628         vcpu->arch.dr6 = DR6_INIT;
9629         vcpu->arch.dr7 = DR7_FIXED_1;
9630         kvm_update_dr7(vcpu);
9631
9632         vcpu->arch.cr2 = 0;
9633
9634         kvm_make_request(KVM_REQ_EVENT, vcpu);
9635         vcpu->arch.apf.msr_en_val = 0;
9636         vcpu->arch.apf.msr_int_val = 0;
9637         vcpu->arch.st.msr_val = 0;
9638
9639         kvmclock_reset(vcpu);
9640
9641         kvm_clear_async_pf_completion_queue(vcpu);
9642         kvm_async_pf_hash_reset(vcpu);
9643         vcpu->arch.apf.halted = false;
9644
9645         if (kvm_mpx_supported()) {
9646                 void *mpx_state_buffer;
9647
9648                 /*
9649                  * To avoid have the INIT path from kvm_apic_has_events() that be
9650                  * called with loaded FPU and does not let userspace fix the state.
9651                  */
9652                 if (init_event)
9653                         kvm_put_guest_fpu(vcpu);
9654                 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9655                                         XFEATURE_BNDREGS);
9656                 if (mpx_state_buffer)
9657                         memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
9658                 mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu->state.xsave,
9659                                         XFEATURE_BNDCSR);
9660                 if (mpx_state_buffer)
9661                         memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
9662                 if (init_event)
9663                         kvm_load_guest_fpu(vcpu);
9664         }
9665
9666         if (!init_event) {
9667                 kvm_pmu_reset(vcpu);
9668                 vcpu->arch.smbase = 0x30000;
9669
9670                 vcpu->arch.msr_misc_features_enables = 0;
9671
9672                 vcpu->arch.xcr0 = XFEATURE_MASK_FP;
9673         }
9674
9675         memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
9676         vcpu->arch.regs_avail = ~0;
9677         vcpu->arch.regs_dirty = ~0;
9678
9679         vcpu->arch.ia32_xss = 0;
9680
9681         kvm_x86_ops.vcpu_reset(vcpu, init_event);
9682 }
9683
9684 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
9685 {
9686         struct kvm_segment cs;
9687
9688         kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
9689         cs.selector = vector << 8;
9690         cs.base = vector << 12;
9691         kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
9692         kvm_rip_write(vcpu, 0);
9693 }
9694
9695 int kvm_arch_hardware_enable(void)
9696 {
9697         struct kvm *kvm;
9698         struct kvm_vcpu *vcpu;
9699         int i;
9700         int ret;
9701         u64 local_tsc;
9702         u64 max_tsc = 0;
9703         bool stable, backwards_tsc = false;
9704
9705         kvm_shared_msr_cpu_online();
9706         ret = kvm_x86_ops.hardware_enable();
9707         if (ret != 0)
9708                 return ret;
9709
9710         local_tsc = rdtsc();
9711         stable = !kvm_check_tsc_unstable();
9712         list_for_each_entry(kvm, &vm_list, vm_list) {
9713                 kvm_for_each_vcpu(i, vcpu, kvm) {
9714                         if (!stable && vcpu->cpu == smp_processor_id())
9715                                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9716                         if (stable && vcpu->arch.last_host_tsc > local_tsc) {
9717                                 backwards_tsc = true;
9718                                 if (vcpu->arch.last_host_tsc > max_tsc)
9719                                         max_tsc = vcpu->arch.last_host_tsc;
9720                         }
9721                 }
9722         }
9723
9724         /*
9725          * Sometimes, even reliable TSCs go backwards.  This happens on
9726          * platforms that reset TSC during suspend or hibernate actions, but
9727          * maintain synchronization.  We must compensate.  Fortunately, we can
9728          * detect that condition here, which happens early in CPU bringup,
9729          * before any KVM threads can be running.  Unfortunately, we can't
9730          * bring the TSCs fully up to date with real time, as we aren't yet far
9731          * enough into CPU bringup that we know how much real time has actually
9732          * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
9733          * variables that haven't been updated yet.
9734          *
9735          * So we simply find the maximum observed TSC above, then record the
9736          * adjustment to TSC in each VCPU.  When the VCPU later gets loaded,
9737          * the adjustment will be applied.  Note that we accumulate
9738          * adjustments, in case multiple suspend cycles happen before some VCPU
9739          * gets a chance to run again.  In the event that no KVM threads get a
9740          * chance to run, we will miss the entire elapsed period, as we'll have
9741          * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
9742          * loose cycle time.  This isn't too big a deal, since the loss will be
9743          * uniform across all VCPUs (not to mention the scenario is extremely
9744          * unlikely). It is possible that a second hibernate recovery happens
9745          * much faster than a first, causing the observed TSC here to be
9746          * smaller; this would require additional padding adjustment, which is
9747          * why we set last_host_tsc to the local tsc observed here.
9748          *
9749          * N.B. - this code below runs only on platforms with reliable TSC,
9750          * as that is the only way backwards_tsc is set above.  Also note
9751          * that this runs for ALL vcpus, which is not a bug; all VCPUs should
9752          * have the same delta_cyc adjustment applied if backwards_tsc
9753          * is detected.  Note further, this adjustment is only done once,
9754          * as we reset last_host_tsc on all VCPUs to stop this from being
9755          * called multiple times (one for each physical CPU bringup).
9756          *
9757          * Platforms with unreliable TSCs don't have to deal with this, they
9758          * will be compensated by the logic in vcpu_load, which sets the TSC to
9759          * catchup mode.  This will catchup all VCPUs to real time, but cannot
9760          * guarantee that they stay in perfect synchronization.
9761          */
9762         if (backwards_tsc) {
9763                 u64 delta_cyc = max_tsc - local_tsc;
9764                 list_for_each_entry(kvm, &vm_list, vm_list) {
9765                         kvm->arch.backwards_tsc_observed = true;
9766                         kvm_for_each_vcpu(i, vcpu, kvm) {
9767                                 vcpu->arch.tsc_offset_adjustment += delta_cyc;
9768                                 vcpu->arch.last_host_tsc = local_tsc;
9769                                 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9770                         }
9771
9772                         /*
9773                          * We have to disable TSC offset matching.. if you were
9774                          * booting a VM while issuing an S4 host suspend....
9775                          * you may have some problem.  Solving this issue is
9776                          * left as an exercise to the reader.
9777                          */
9778                         kvm->arch.last_tsc_nsec = 0;
9779                         kvm->arch.last_tsc_write = 0;
9780                 }
9781
9782         }
9783         return 0;
9784 }
9785
9786 void kvm_arch_hardware_disable(void)
9787 {
9788         kvm_x86_ops.hardware_disable();
9789         drop_user_return_notifiers();
9790 }
9791
9792 int kvm_arch_hardware_setup(void *opaque)
9793 {
9794         struct kvm_x86_init_ops *ops = opaque;
9795         int r;
9796
9797         rdmsrl_safe(MSR_EFER, &host_efer);
9798
9799         if (boot_cpu_has(X86_FEATURE_XSAVES))
9800                 rdmsrl(MSR_IA32_XSS, host_xss);
9801
9802         r = ops->hardware_setup();
9803         if (r != 0)
9804                 return r;
9805
9806         memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
9807
9808         if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
9809                 supported_xss = 0;
9810
9811 #define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
9812         cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
9813 #undef __kvm_cpu_cap_has
9814
9815         if (kvm_has_tsc_control) {
9816                 /*
9817                  * Make sure the user can only configure tsc_khz values that
9818                  * fit into a signed integer.
9819                  * A min value is not calculated because it will always
9820                  * be 1 on all machines.
9821                  */
9822                 u64 max = min(0x7fffffffULL,
9823                               __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
9824                 kvm_max_guest_tsc_khz = max;
9825
9826                 kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
9827         }
9828
9829         kvm_init_msr_list();
9830         return 0;
9831 }
9832
9833 void kvm_arch_hardware_unsetup(void)
9834 {
9835         kvm_x86_ops.hardware_unsetup();
9836 }
9837
9838 int kvm_arch_check_processor_compat(void *opaque)
9839 {
9840         struct cpuinfo_x86 *c = &cpu_data(smp_processor_id());
9841         struct kvm_x86_init_ops *ops = opaque;
9842
9843         WARN_ON(!irqs_disabled());
9844
9845         if (__cr4_reserved_bits(cpu_has, c) !=
9846             __cr4_reserved_bits(cpu_has, &boot_cpu_data))
9847                 return -EIO;
9848
9849         return ops->check_processor_compatibility();
9850 }
9851
9852 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
9853 {
9854         return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
9855 }
9856 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
9857
9858 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
9859 {
9860         return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
9861 }
9862
9863 struct static_key kvm_no_apic_vcpu __read_mostly;
9864 EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
9865
9866 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
9867 {
9868         struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
9869
9870         vcpu->arch.l1tf_flush_l1d = true;
9871         if (pmu->version && unlikely(pmu->event_count)) {
9872                 pmu->need_cleanup = true;
9873                 kvm_make_request(KVM_REQ_PMU, vcpu);
9874         }
9875         kvm_x86_ops.sched_in(vcpu, cpu);
9876 }
9877
9878 void kvm_arch_free_vm(struct kvm *kvm)
9879 {
9880         kfree(kvm->arch.hyperv.hv_pa_pg);
9881         vfree(kvm);
9882 }
9883
9884
9885 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
9886 {
9887         if (type)
9888                 return -EINVAL;
9889
9890         INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
9891         INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
9892         INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
9893         INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
9894         INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
9895         atomic_set(&kvm->arch.noncoherent_dma_count, 0);
9896
9897         /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
9898         set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
9899         /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
9900         set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
9901                 &kvm->arch.irq_sources_bitmap);
9902
9903         raw_spin_lock_init(&kvm->arch.tsc_write_lock);
9904         mutex_init(&kvm->arch.apic_map_lock);
9905         spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
9906
9907         kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
9908         pvclock_update_vm_gtod_copy(kvm);
9909
9910         kvm->arch.guest_can_read_msr_platform_info = true;
9911
9912         INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
9913         INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
9914
9915         kvm_hv_init_vm(kvm);
9916         kvm_page_track_init(kvm);
9917         kvm_mmu_init_vm(kvm);
9918
9919         return kvm_x86_ops.vm_init(kvm);
9920 }
9921
9922 int kvm_arch_post_init_vm(struct kvm *kvm)
9923 {
9924         return kvm_mmu_post_init_vm(kvm);
9925 }
9926
9927 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
9928 {
9929         vcpu_load(vcpu);
9930         kvm_mmu_unload(vcpu);
9931         vcpu_put(vcpu);
9932 }
9933
9934 static void kvm_free_vcpus(struct kvm *kvm)
9935 {
9936         unsigned int i;
9937         struct kvm_vcpu *vcpu;
9938
9939         /*
9940          * Unpin any mmu pages first.
9941          */
9942         kvm_for_each_vcpu(i, vcpu, kvm) {
9943                 kvm_clear_async_pf_completion_queue(vcpu);
9944                 kvm_unload_vcpu_mmu(vcpu);
9945         }
9946         kvm_for_each_vcpu(i, vcpu, kvm)
9947                 kvm_vcpu_destroy(vcpu);
9948
9949         mutex_lock(&kvm->lock);
9950         for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
9951                 kvm->vcpus[i] = NULL;
9952
9953         atomic_set(&kvm->online_vcpus, 0);
9954         mutex_unlock(&kvm->lock);
9955 }
9956
9957 void kvm_arch_sync_events(struct kvm *kvm)
9958 {
9959         cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
9960         cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
9961         kvm_free_pit(kvm);
9962 }
9963
9964 int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
9965 {
9966         int i, r;
9967         unsigned long hva, old_npages;
9968         struct kvm_memslots *slots = kvm_memslots(kvm);
9969         struct kvm_memory_slot *slot;
9970
9971         /* Called with kvm->slots_lock held.  */
9972         if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
9973                 return -EINVAL;
9974
9975         slot = id_to_memslot(slots, id);
9976         if (size) {
9977                 if (slot && slot->npages)
9978                         return -EEXIST;
9979
9980                 /*
9981                  * MAP_SHARED to prevent internal slot pages from being moved
9982                  * by fork()/COW.
9983                  */
9984                 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
9985                               MAP_SHARED | MAP_ANONYMOUS, 0);
9986                 if (IS_ERR((void *)hva))
9987                         return PTR_ERR((void *)hva);
9988         } else {
9989                 if (!slot || !slot->npages)
9990                         return 0;
9991
9992                 old_npages = slot->npages;
9993                 hva = 0;
9994         }
9995
9996         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
9997                 struct kvm_userspace_memory_region m;
9998
9999                 m.slot = id | (i << 16);
10000                 m.flags = 0;
10001                 m.guest_phys_addr = gpa;
10002                 m.userspace_addr = hva;
10003                 m.memory_size = size;
10004                 r = __kvm_set_memory_region(kvm, &m);
10005                 if (r < 0)
10006                         return r;
10007         }
10008
10009         if (!size)
10010                 vm_munmap(hva, old_npages * PAGE_SIZE);
10011
10012         return 0;
10013 }
10014 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
10015
10016 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
10017 {
10018         kvm_mmu_pre_destroy_vm(kvm);
10019 }
10020
10021 void kvm_arch_destroy_vm(struct kvm *kvm)
10022 {
10023         if (current->mm == kvm->mm) {
10024                 /*
10025                  * Free memory regions allocated on behalf of userspace,
10026                  * unless the the memory map has changed due to process exit
10027                  * or fd copying.
10028                  */
10029                 mutex_lock(&kvm->slots_lock);
10030                 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
10031                                         0, 0);
10032                 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
10033                                         0, 0);
10034                 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
10035                 mutex_unlock(&kvm->slots_lock);
10036         }
10037         if (kvm_x86_ops.vm_destroy)
10038                 kvm_x86_ops.vm_destroy(kvm);
10039         kvm_pic_destroy(kvm);
10040         kvm_ioapic_destroy(kvm);
10041         kvm_free_vcpus(kvm);
10042         kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
10043         kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
10044         kvm_mmu_uninit_vm(kvm);
10045         kvm_page_track_cleanup(kvm);
10046         kvm_hv_destroy_vm(kvm);
10047 }
10048
10049 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
10050 {
10051         int i;
10052
10053         for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10054                 kvfree(slot->arch.rmap[i]);
10055                 slot->arch.rmap[i] = NULL;
10056
10057                 if (i == 0)
10058                         continue;
10059
10060                 kvfree(slot->arch.lpage_info[i - 1]);
10061                 slot->arch.lpage_info[i - 1] = NULL;
10062         }
10063
10064         kvm_page_track_free_memslot(slot);
10065 }
10066
10067 static int kvm_alloc_memslot_metadata(struct kvm_memory_slot *slot,
10068                                       unsigned long npages)
10069 {
10070         int i;
10071
10072         /*
10073          * Clear out the previous array pointers for the KVM_MR_MOVE case.  The
10074          * old arrays will be freed by __kvm_set_memory_region() if installing
10075          * the new memslot is successful.
10076          */
10077         memset(&slot->arch, 0, sizeof(slot->arch));
10078
10079         for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10080                 struct kvm_lpage_info *linfo;
10081                 unsigned long ugfn;
10082                 int lpages;
10083                 int level = i + 1;
10084
10085                 lpages = gfn_to_index(slot->base_gfn + npages - 1,
10086                                       slot->base_gfn, level) + 1;
10087
10088                 slot->arch.rmap[i] =
10089                         kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
10090                                  GFP_KERNEL_ACCOUNT);
10091                 if (!slot->arch.rmap[i])
10092                         goto out_free;
10093                 if (i == 0)
10094                         continue;
10095
10096                 linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
10097                 if (!linfo)
10098                         goto out_free;
10099
10100                 slot->arch.lpage_info[i - 1] = linfo;
10101
10102                 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
10103                         linfo[0].disallow_lpage = 1;
10104                 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
10105                         linfo[lpages - 1].disallow_lpage = 1;
10106                 ugfn = slot->userspace_addr >> PAGE_SHIFT;
10107                 /*
10108                  * If the gfn and userspace address are not aligned wrt each
10109                  * other, disable large page support for this slot.
10110                  */
10111                 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
10112                         unsigned long j;
10113
10114                         for (j = 0; j < lpages; ++j)
10115                                 linfo[j].disallow_lpage = 1;
10116                 }
10117         }
10118
10119         if (kvm_page_track_create_memslot(slot, npages))
10120                 goto out_free;
10121
10122         return 0;
10123
10124 out_free:
10125         for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
10126                 kvfree(slot->arch.rmap[i]);
10127                 slot->arch.rmap[i] = NULL;
10128                 if (i == 0)
10129                         continue;
10130
10131                 kvfree(slot->arch.lpage_info[i - 1]);
10132                 slot->arch.lpage_info[i - 1] = NULL;
10133         }
10134         return -ENOMEM;
10135 }
10136
10137 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
10138 {
10139         struct kvm_vcpu *vcpu;
10140         int i;
10141
10142         /*
10143          * memslots->generation has been incremented.
10144          * mmio generation may have reached its maximum value.
10145          */
10146         kvm_mmu_invalidate_mmio_sptes(kvm, gen);
10147
10148         /* Force re-initialization of steal_time cache */
10149         kvm_for_each_vcpu(i, vcpu, kvm)
10150                 kvm_vcpu_kick(vcpu);
10151 }
10152
10153 int kvm_arch_prepare_memory_region(struct kvm *kvm,
10154                                 struct kvm_memory_slot *memslot,
10155                                 const struct kvm_userspace_memory_region *mem,
10156                                 enum kvm_mr_change change)
10157 {
10158         if (change == KVM_MR_CREATE || change == KVM_MR_MOVE)
10159                 return kvm_alloc_memslot_metadata(memslot,
10160                                                   mem->memory_size >> PAGE_SHIFT);
10161         return 0;
10162 }
10163
10164 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
10165                                      struct kvm_memory_slot *old,
10166                                      struct kvm_memory_slot *new,
10167                                      enum kvm_mr_change change)
10168 {
10169         /*
10170          * Nothing to do for RO slots or CREATE/MOVE/DELETE of a slot.
10171          * See comments below.
10172          */
10173         if ((change != KVM_MR_FLAGS_ONLY) || (new->flags & KVM_MEM_READONLY))
10174                 return;
10175
10176         /*
10177          * Dirty logging tracks sptes in 4k granularity, meaning that large
10178          * sptes have to be split.  If live migration is successful, the guest
10179          * in the source machine will be destroyed and large sptes will be
10180          * created in the destination. However, if the guest continues to run
10181          * in the source machine (for example if live migration fails), small
10182          * sptes will remain around and cause bad performance.
10183          *
10184          * Scan sptes if dirty logging has been stopped, dropping those
10185          * which can be collapsed into a single large-page spte.  Later
10186          * page faults will create the large-page sptes.
10187          *
10188          * There is no need to do this in any of the following cases:
10189          * CREATE:      No dirty mappings will already exist.
10190          * MOVE/DELETE: The old mappings will already have been cleaned up by
10191          *              kvm_arch_flush_shadow_memslot()
10192          */
10193         if ((old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
10194             !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
10195                 kvm_mmu_zap_collapsible_sptes(kvm, new);
10196
10197         /*
10198          * Enable or disable dirty logging for the slot.
10199          *
10200          * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of the old
10201          * slot have been zapped so no dirty logging updates are needed for
10202          * the old slot.
10203          * For KVM_MR_CREATE and KVM_MR_MOVE, once the new slot is visible
10204          * any mappings that might be created in it will consume the
10205          * properties of the new slot and do not need to be updated here.
10206          *
10207          * When PML is enabled, the kvm_x86_ops dirty logging hooks are
10208          * called to enable/disable dirty logging.
10209          *
10210          * When disabling dirty logging with PML enabled, the D-bit is set
10211          * for sptes in the slot in order to prevent unnecessary GPA
10212          * logging in the PML buffer (and potential PML buffer full VMEXIT).
10213          * This guarantees leaving PML enabled for the guest's lifetime
10214          * won't have any additional overhead from PML when the guest is
10215          * running with dirty logging disabled.
10216          *
10217          * When enabling dirty logging, large sptes are write-protected
10218          * so they can be split on first write.  New large sptes cannot
10219          * be created for this slot until the end of the logging.
10220          * See the comments in fast_page_fault().
10221          * For small sptes, nothing is done if the dirty log is in the
10222          * initial-all-set state.  Otherwise, depending on whether pml
10223          * is enabled the D-bit or the W-bit will be cleared.
10224          */
10225         if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
10226                 if (kvm_x86_ops.slot_enable_log_dirty) {
10227                         kvm_x86_ops.slot_enable_log_dirty(kvm, new);
10228                 } else {
10229                         int level =
10230                                 kvm_dirty_log_manual_protect_and_init_set(kvm) ?
10231                                 PG_LEVEL_2M : PG_LEVEL_4K;
10232
10233                         /*
10234                          * If we're with initial-all-set, we don't need
10235                          * to write protect any small page because
10236                          * they're reported as dirty already.  However
10237                          * we still need to write-protect huge pages
10238                          * so that the page split can happen lazily on
10239                          * the first write to the huge page.
10240                          */
10241                         kvm_mmu_slot_remove_write_access(kvm, new, level);
10242                 }
10243         } else {
10244                 if (kvm_x86_ops.slot_disable_log_dirty)
10245                         kvm_x86_ops.slot_disable_log_dirty(kvm, new);
10246         }
10247 }
10248
10249 void kvm_arch_commit_memory_region(struct kvm *kvm,
10250                                 const struct kvm_userspace_memory_region *mem,
10251                                 struct kvm_memory_slot *old,
10252                                 const struct kvm_memory_slot *new,
10253                                 enum kvm_mr_change change)
10254 {
10255         if (!kvm->arch.n_requested_mmu_pages)
10256                 kvm_mmu_change_mmu_pages(kvm,
10257                                 kvm_mmu_calculate_default_mmu_pages(kvm));
10258
10259         /*
10260          * FIXME: const-ify all uses of struct kvm_memory_slot.
10261          */
10262         kvm_mmu_slot_apply_flags(kvm, old, (struct kvm_memory_slot *) new, change);
10263
10264         /* Free the arrays associated with the old memslot. */
10265         if (change == KVM_MR_MOVE)
10266                 kvm_arch_free_memslot(kvm, old);
10267 }
10268
10269 void kvm_arch_flush_shadow_all(struct kvm *kvm)
10270 {
10271         kvm_mmu_zap_all(kvm);
10272 }
10273
10274 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
10275                                    struct kvm_memory_slot *slot)
10276 {
10277         kvm_page_track_flush_slot(kvm, slot);
10278 }
10279
10280 static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
10281 {
10282         return (is_guest_mode(vcpu) &&
10283                         kvm_x86_ops.guest_apic_has_interrupt &&
10284                         kvm_x86_ops.guest_apic_has_interrupt(vcpu));
10285 }
10286
10287 static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
10288 {
10289         if (!list_empty_careful(&vcpu->async_pf.done))
10290                 return true;
10291
10292         if (kvm_apic_has_events(vcpu))
10293                 return true;
10294
10295         if (vcpu->arch.pv.pv_unhalted)
10296                 return true;
10297
10298         if (vcpu->arch.exception.pending)
10299                 return true;
10300
10301         if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
10302             (vcpu->arch.nmi_pending &&
10303              kvm_x86_ops.nmi_allowed(vcpu, false)))
10304                 return true;
10305
10306         if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
10307             (vcpu->arch.smi_pending &&
10308              kvm_x86_ops.smi_allowed(vcpu, false)))
10309                 return true;
10310
10311         if (kvm_arch_interrupt_allowed(vcpu) &&
10312             (kvm_cpu_has_interrupt(vcpu) ||
10313             kvm_guest_apic_has_interrupt(vcpu)))
10314                 return true;
10315
10316         if (kvm_hv_has_stimer_pending(vcpu))
10317                 return true;
10318
10319         if (is_guest_mode(vcpu) &&
10320             kvm_x86_ops.nested_ops->hv_timer_pending &&
10321             kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
10322                 return true;
10323
10324         return false;
10325 }
10326
10327 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
10328 {
10329         return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
10330 }
10331
10332 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
10333 {
10334         if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
10335                 return true;
10336
10337         if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
10338                 kvm_test_request(KVM_REQ_SMI, vcpu) ||
10339                  kvm_test_request(KVM_REQ_EVENT, vcpu))
10340                 return true;
10341
10342         if (vcpu->arch.apicv_active && kvm_x86_ops.dy_apicv_has_pending_interrupt(vcpu))
10343                 return true;
10344
10345         return false;
10346 }
10347
10348 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
10349 {
10350         return vcpu->arch.preempted_in_kernel;
10351 }
10352
10353 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
10354 {
10355         return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
10356 }
10357
10358 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
10359 {
10360         return kvm_x86_ops.interrupt_allowed(vcpu, false);
10361 }
10362
10363 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
10364 {
10365         if (is_64_bit_mode(vcpu))
10366                 return kvm_rip_read(vcpu);
10367         return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
10368                      kvm_rip_read(vcpu));
10369 }
10370 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
10371
10372 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
10373 {
10374         return kvm_get_linear_rip(vcpu) == linear_rip;
10375 }
10376 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
10377
10378 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
10379 {
10380         unsigned long rflags;
10381
10382         rflags = kvm_x86_ops.get_rflags(vcpu);
10383         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
10384                 rflags &= ~X86_EFLAGS_TF;
10385         return rflags;
10386 }
10387 EXPORT_SYMBOL_GPL(kvm_get_rflags);
10388
10389 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
10390 {
10391         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
10392             kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
10393                 rflags |= X86_EFLAGS_TF;
10394         kvm_x86_ops.set_rflags(vcpu, rflags);
10395 }
10396
10397 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
10398 {
10399         __kvm_set_rflags(vcpu, rflags);
10400         kvm_make_request(KVM_REQ_EVENT, vcpu);
10401 }
10402 EXPORT_SYMBOL_GPL(kvm_set_rflags);
10403
10404 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
10405 {
10406         int r;
10407
10408         if ((vcpu->arch.mmu->direct_map != work->arch.direct_map) ||
10409               work->wakeup_all)
10410                 return;
10411
10412         r = kvm_mmu_reload(vcpu);
10413         if (unlikely(r))
10414                 return;
10415
10416         if (!vcpu->arch.mmu->direct_map &&
10417               work->arch.cr3 != vcpu->arch.mmu->get_guest_pgd(vcpu))
10418                 return;
10419
10420         kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true);
10421 }
10422
10423 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
10424 {
10425         BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
10426
10427         return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
10428 }
10429
10430 static inline u32 kvm_async_pf_next_probe(u32 key)
10431 {
10432         return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
10433 }
10434
10435 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10436 {
10437         u32 key = kvm_async_pf_hash_fn(gfn);
10438
10439         while (vcpu->arch.apf.gfns[key] != ~0)
10440                 key = kvm_async_pf_next_probe(key);
10441
10442         vcpu->arch.apf.gfns[key] = gfn;
10443 }
10444
10445 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
10446 {
10447         int i;
10448         u32 key = kvm_async_pf_hash_fn(gfn);
10449
10450         for (i = 0; i < ASYNC_PF_PER_VCPU &&
10451                      (vcpu->arch.apf.gfns[key] != gfn &&
10452                       vcpu->arch.apf.gfns[key] != ~0); i++)
10453                 key = kvm_async_pf_next_probe(key);
10454
10455         return key;
10456 }
10457
10458 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10459 {
10460         return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
10461 }
10462
10463 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
10464 {
10465         u32 i, j, k;
10466
10467         i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
10468
10469         if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
10470                 return;
10471
10472         while (true) {
10473                 vcpu->arch.apf.gfns[i] = ~0;
10474                 do {
10475                         j = kvm_async_pf_next_probe(j);
10476                         if (vcpu->arch.apf.gfns[j] == ~0)
10477                                 return;
10478                         k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
10479                         /*
10480                          * k lies cyclically in ]i,j]
10481                          * |    i.k.j |
10482                          * |....j i.k.| or  |.k..j i...|
10483                          */
10484                 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
10485                 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
10486                 i = j;
10487         }
10488 }
10489
10490 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
10491 {
10492         u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
10493
10494         return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
10495                                       sizeof(reason));
10496 }
10497
10498 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
10499 {
10500         unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
10501
10502         return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
10503                                              &token, offset, sizeof(token));
10504 }
10505
10506 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
10507 {
10508         unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
10509         u32 val;
10510
10511         if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
10512                                          &val, offset, sizeof(val)))
10513                 return false;
10514
10515         return !val;
10516 }
10517
10518 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
10519 {
10520         if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
10521                 return false;
10522
10523         if (!kvm_pv_async_pf_enabled(vcpu) ||
10524             (vcpu->arch.apf.send_user_only && kvm_x86_ops.get_cpl(vcpu) == 0))
10525                 return false;
10526
10527         return true;
10528 }
10529
10530 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
10531 {
10532         if (unlikely(!lapic_in_kernel(vcpu) ||
10533                      kvm_event_needs_reinjection(vcpu) ||
10534                      vcpu->arch.exception.pending))
10535                 return false;
10536
10537         if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
10538                 return false;
10539
10540         /*
10541          * If interrupts are off we cannot even use an artificial
10542          * halt state.
10543          */
10544         return kvm_arch_interrupt_allowed(vcpu);
10545 }
10546
10547 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
10548                                      struct kvm_async_pf *work)
10549 {
10550         struct x86_exception fault;
10551
10552         trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
10553         kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
10554
10555         if (kvm_can_deliver_async_pf(vcpu) &&
10556             !apf_put_user_notpresent(vcpu)) {
10557                 fault.vector = PF_VECTOR;
10558                 fault.error_code_valid = true;
10559                 fault.error_code = 0;
10560                 fault.nested_page_fault = false;
10561                 fault.address = work->arch.token;
10562                 fault.async_page_fault = true;
10563                 kvm_inject_page_fault(vcpu, &fault);
10564                 return true;
10565         } else {
10566                 /*
10567                  * It is not possible to deliver a paravirtualized asynchronous
10568                  * page fault, but putting the guest in an artificial halt state
10569                  * can be beneficial nevertheless: if an interrupt arrives, we
10570                  * can deliver it timely and perhaps the guest will schedule
10571                  * another process.  When the instruction that triggered a page
10572                  * fault is retried, hopefully the page will be ready in the host.
10573                  */
10574                 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
10575                 return false;
10576         }
10577 }
10578
10579 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
10580                                  struct kvm_async_pf *work)
10581 {
10582         struct kvm_lapic_irq irq = {
10583                 .delivery_mode = APIC_DM_FIXED,
10584                 .vector = vcpu->arch.apf.vec
10585         };
10586
10587         if (work->wakeup_all)
10588                 work->arch.token = ~0; /* broadcast wakeup */
10589         else
10590                 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
10591         trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
10592
10593         if ((work->wakeup_all || work->notpresent_injected) &&
10594             kvm_pv_async_pf_enabled(vcpu) &&
10595             !apf_put_user_ready(vcpu, work->arch.token)) {
10596                 vcpu->arch.apf.pageready_pending = true;
10597                 kvm_apic_set_irq(vcpu, &irq, NULL);
10598         }
10599
10600         vcpu->arch.apf.halted = false;
10601         vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
10602 }
10603
10604 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
10605 {
10606         kvm_make_request(KVM_REQ_APF_READY, vcpu);
10607         if (!vcpu->arch.apf.pageready_pending)
10608                 kvm_vcpu_kick(vcpu);
10609 }
10610
10611 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
10612 {
10613         if (!kvm_pv_async_pf_enabled(vcpu))
10614                 return true;
10615         else
10616                 return apf_pageready_slot_free(vcpu);
10617 }
10618
10619 void kvm_arch_start_assignment(struct kvm *kvm)
10620 {
10621         atomic_inc(&kvm->arch.assigned_device_count);
10622 }
10623 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
10624
10625 void kvm_arch_end_assignment(struct kvm *kvm)
10626 {
10627         atomic_dec(&kvm->arch.assigned_device_count);
10628 }
10629 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
10630
10631 bool kvm_arch_has_assigned_device(struct kvm *kvm)
10632 {
10633         return atomic_read(&kvm->arch.assigned_device_count);
10634 }
10635 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
10636
10637 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
10638 {
10639         atomic_inc(&kvm->arch.noncoherent_dma_count);
10640 }
10641 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
10642
10643 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
10644 {
10645         atomic_dec(&kvm->arch.noncoherent_dma_count);
10646 }
10647 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
10648
10649 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
10650 {
10651         return atomic_read(&kvm->arch.noncoherent_dma_count);
10652 }
10653 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
10654
10655 bool kvm_arch_has_irq_bypass(void)
10656 {
10657         return true;
10658 }
10659
10660 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
10661                                       struct irq_bypass_producer *prod)
10662 {
10663         struct kvm_kernel_irqfd *irqfd =
10664                 container_of(cons, struct kvm_kernel_irqfd, consumer);
10665         int ret;
10666
10667         irqfd->producer = prod;
10668         kvm_arch_start_assignment(irqfd->kvm);
10669         ret = kvm_x86_ops.update_pi_irte(irqfd->kvm,
10670                                          prod->irq, irqfd->gsi, 1);
10671
10672         if (ret)
10673                 kvm_arch_end_assignment(irqfd->kvm);
10674
10675         return ret;
10676 }
10677
10678 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
10679                                       struct irq_bypass_producer *prod)
10680 {
10681         int ret;
10682         struct kvm_kernel_irqfd *irqfd =
10683                 container_of(cons, struct kvm_kernel_irqfd, consumer);
10684
10685         WARN_ON(irqfd->producer != prod);
10686         irqfd->producer = NULL;
10687
10688         /*
10689          * When producer of consumer is unregistered, we change back to
10690          * remapped mode, so we can re-use the current implementation
10691          * when the irq is masked/disabled or the consumer side (KVM
10692          * int this case doesn't want to receive the interrupts.
10693         */
10694         ret = kvm_x86_ops.update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
10695         if (ret)
10696                 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
10697                        " fails: %d\n", irqfd->consumer.token, ret);
10698
10699         kvm_arch_end_assignment(irqfd->kvm);
10700 }
10701
10702 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
10703                                    uint32_t guest_irq, bool set)
10704 {
10705         return kvm_x86_ops.update_pi_irte(kvm, host_irq, guest_irq, set);
10706 }
10707
10708 bool kvm_vector_hashing_enabled(void)
10709 {
10710         return vector_hashing;
10711 }
10712
10713 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
10714 {
10715         return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
10716 }
10717 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
10718
10719
10720 int kvm_spec_ctrl_test_value(u64 value)
10721 {
10722         /*
10723          * test that setting IA32_SPEC_CTRL to given value
10724          * is allowed by the host processor
10725          */
10726
10727         u64 saved_value;
10728         unsigned long flags;
10729         int ret = 0;
10730
10731         local_irq_save(flags);
10732
10733         if (rdmsrl_safe(MSR_IA32_SPEC_CTRL, &saved_value))
10734                 ret = 1;
10735         else if (wrmsrl_safe(MSR_IA32_SPEC_CTRL, value))
10736                 ret = 1;
10737         else
10738                 wrmsrl(MSR_IA32_SPEC_CTRL, saved_value);
10739
10740         local_irq_restore(flags);
10741
10742         return ret;
10743 }
10744 EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
10745
10746 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
10747 {
10748         struct x86_exception fault;
10749         u32 access = error_code &
10750                 (PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
10751
10752         if (!(error_code & PFERR_PRESENT_MASK) ||
10753             vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, &fault) != UNMAPPED_GVA) {
10754                 /*
10755                  * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
10756                  * tables probably do not match the TLB.  Just proceed
10757                  * with the error code that the processor gave.
10758                  */
10759                 fault.vector = PF_VECTOR;
10760                 fault.error_code_valid = true;
10761                 fault.error_code = error_code;
10762                 fault.nested_page_fault = false;
10763                 fault.address = gva;
10764         }
10765         vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
10766 }
10767 EXPORT_SYMBOL_GPL(kvm_fixup_and_inject_pf_error);
10768
10769 /*
10770  * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
10771  * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
10772  * indicates whether exit to userspace is needed.
10773  */
10774 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
10775                               struct x86_exception *e)
10776 {
10777         if (r == X86EMUL_PROPAGATE_FAULT) {
10778                 kvm_inject_emulated_page_fault(vcpu, e);
10779                 return 1;
10780         }
10781
10782         /*
10783          * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
10784          * while handling a VMX instruction KVM could've handled the request
10785          * correctly by exiting to userspace and performing I/O but there
10786          * doesn't seem to be a real use-case behind such requests, just return
10787          * KVM_EXIT_INTERNAL_ERROR for now.
10788          */
10789         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
10790         vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
10791         vcpu->run->internal.ndata = 0;
10792
10793         return 0;
10794 }
10795 EXPORT_SYMBOL_GPL(kvm_handle_memory_failure);
10796
10797 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
10798 {
10799         bool pcid_enabled;
10800         struct x86_exception e;
10801         unsigned i;
10802         unsigned long roots_to_free = 0;
10803         struct {
10804                 u64 pcid;
10805                 u64 gla;
10806         } operand;
10807         int r;
10808
10809         r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
10810         if (r != X86EMUL_CONTINUE)
10811                 return kvm_handle_memory_failure(vcpu, r, &e);
10812
10813         if (operand.pcid >> 12 != 0) {
10814                 kvm_inject_gp(vcpu, 0);
10815                 return 1;
10816         }
10817
10818         pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
10819
10820         switch (type) {
10821         case INVPCID_TYPE_INDIV_ADDR:
10822                 if ((!pcid_enabled && (operand.pcid != 0)) ||
10823                     is_noncanonical_address(operand.gla, vcpu)) {
10824                         kvm_inject_gp(vcpu, 0);
10825                         return 1;
10826                 }
10827                 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
10828                 return kvm_skip_emulated_instruction(vcpu);
10829
10830         case INVPCID_TYPE_SINGLE_CTXT:
10831                 if (!pcid_enabled && (operand.pcid != 0)) {
10832                         kvm_inject_gp(vcpu, 0);
10833                         return 1;
10834                 }
10835
10836                 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
10837                         kvm_mmu_sync_roots(vcpu);
10838                         kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
10839                 }
10840
10841                 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
10842                         if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].pgd)
10843                             == operand.pcid)
10844                                 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
10845
10846                 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
10847                 /*
10848                  * If neither the current cr3 nor any of the prev_roots use the
10849                  * given PCID, then nothing needs to be done here because a
10850                  * resync will happen anyway before switching to any other CR3.
10851                  */
10852
10853                 return kvm_skip_emulated_instruction(vcpu);
10854
10855         case INVPCID_TYPE_ALL_NON_GLOBAL:
10856                 /*
10857                  * Currently, KVM doesn't mark global entries in the shadow
10858                  * page tables, so a non-global flush just degenerates to a
10859                  * global flush. If needed, we could optimize this later by
10860                  * keeping track of global entries in shadow page tables.
10861                  */
10862
10863                 fallthrough;
10864         case INVPCID_TYPE_ALL_INCL_GLOBAL:
10865                 kvm_mmu_unload(vcpu);
10866                 return kvm_skip_emulated_instruction(vcpu);
10867
10868         default:
10869                 BUG(); /* We have already checked above that type <= 3 */
10870         }
10871 }
10872 EXPORT_SYMBOL_GPL(kvm_handle_invpcid);
10873
10874 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
10875 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
10876 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
10877 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
10878 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
10879 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
10880 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
10881 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
10882 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
10883 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
10884 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
10885 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
10886 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
10887 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
10888 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
10889 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
10890 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
10891 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
10892 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
10893 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
10894 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
10895 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_update_request);