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