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