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