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