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