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