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