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