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