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