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