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