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