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