~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/arch/x86/kvm/x86.c

Version: ~ [ linux-6.6-rc1 ] ~ [ linux-6.5.2 ] ~ [ linux-6.4.15 ] ~ [ linux-6.3.13 ] ~ [ linux-6.2.16 ] ~ [ linux-6.1.52 ] ~ [ linux-6.0.19 ] ~ [ linux-5.19.17 ] ~ [ linux-5.18.19 ] ~ [ linux-5.17.15 ] ~ [ linux-5.16.20 ] ~ [ linux-5.15.131 ] ~ [ linux-5.14.21 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.194 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.256 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.294 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.325 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.337 ] ~ [ linux-4.4.302 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.9 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  1 /*
  2  * Kernel-based Virtual Machine driver for Linux
  3  *
  4  * derived from drivers/kvm/kvm_main.c
  5  *
  6  * Copyright (C) 2006 Qumranet, Inc.
  7  * Copyright (C) 2008 Qumranet, Inc.
  8  * Copyright IBM Corporation, 2008
  9  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
 10  *
 11  * Authors:
 12  *   Avi Kivity   <avi@qumranet.com>
 13  *   Yaniv Kamay  <yaniv@qumranet.com>
 14  *   Amit Shah    <amit.shah@qumranet.com>
 15  *   Ben-Ami Yassour <benami@il.ibm.com>
 16  *
 17  * This work is licensed under the terms of the GNU GPL, version 2.  See
 18  * the COPYING file in the top-level directory.
 19  *
 20  */
 21 
 22 #include <linux/kvm_host.h>
 23 #include "irq.h"
 24 #include "mmu.h"
 25 #include "i8254.h"
 26 #include "tss.h"
 27 #include "kvm_cache_regs.h"
 28 #include "x86.h"
 29 #include "cpuid.h"
 30 #include "pmu.h"
 31 #include "hyperv.h"
 32 
 33 #include <linux/clocksource.h>
 34 #include <linux/interrupt.h>
 35 #include <linux/kvm.h>
 36 #include <linux/fs.h>
 37 #include <linux/vmalloc.h>
 38 #include <linux/export.h>
 39 #include <linux/moduleparam.h>
 40 #include <linux/mman.h>
 41 #include <linux/highmem.h>
 42 #include <linux/iommu.h>
 43 #include <linux/intel-iommu.h>
 44 #include <linux/cpufreq.h>
 45 #include <linux/user-return-notifier.h>
 46 #include <linux/srcu.h>
 47 #include <linux/slab.h>
 48 #include <linux/perf_event.h>
 49 #include <linux/uaccess.h>
 50 #include <linux/hash.h>
 51 #include <linux/pci.h>
 52 #include <linux/timekeeper_internal.h>
 53 #include <linux/pvclock_gtod.h>
 54 #include <linux/kvm_irqfd.h>
 55 #include <linux/irqbypass.h>
 56 #include <linux/sched/stat.h>
 57 #include <linux/mem_encrypt.h>
 58 
 59 #include <trace/events/kvm.h>
 60 
 61 #include <asm/debugreg.h>
 62 #include <asm/msr.h>
 63 #include <asm/desc.h>
 64 #include <asm/mce.h>
 65 #include <linux/kernel_stat.h>
 66 #include <asm/fpu/internal.h> /* Ugh! */
 67 #include <asm/pvclock.h>
 68 #include <asm/div64.h>
 69 #include <asm/irq_remapping.h>
 70 
 71 #define CREATE_TRACE_POINTS
 72 #include "trace.h"
 73 
 74 #define MAX_IO_MSRS 256
 75 #define KVM_MAX_MCE_BANKS 32
 76 u64 __read_mostly kvm_mce_cap_supported = MCG_CTL_P | MCG_SER_P;
 77 EXPORT_SYMBOL_GPL(kvm_mce_cap_supported);
 78 
 79 #define emul_to_vcpu(ctxt) \
 80         container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
 81 
 82 /* EFER defaults:
 83  * - enable syscall per default because its emulated by KVM
 84  * - enable LME and LMA per default on 64 bit KVM
 85  */
 86 #ifdef CONFIG_X86_64
 87 static
 88 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
 89 #else
 90 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
 91 #endif
 92 
 93 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
 94 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
 95 
 96 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
 97                                     KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
 98 
 99 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
100 static void process_nmi(struct kvm_vcpu *vcpu);
101 static void enter_smm(struct kvm_vcpu *vcpu);
102 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
103 
104 struct kvm_x86_ops *kvm_x86_ops __read_mostly;
105 EXPORT_SYMBOL_GPL(kvm_x86_ops);
106 
107 static bool __read_mostly ignore_msrs = 0;
108 module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
109 
110 static bool __read_mostly report_ignored_msrs = true;
111 module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
112 
113 unsigned int min_timer_period_us = 500;
114 module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
115 
116 static bool __read_mostly kvmclock_periodic_sync = true;
117 module_param(kvmclock_periodic_sync, bool, S_IRUGO);
118 
119 bool __read_mostly kvm_has_tsc_control;
120 EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
121 u32  __read_mostly kvm_max_guest_tsc_khz;
122 EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
123 u8   __read_mostly kvm_tsc_scaling_ratio_frac_bits;
124 EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
125 u64  __read_mostly kvm_max_tsc_scaling_ratio;
126 EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
127 u64 __read_mostly kvm_default_tsc_scaling_ratio;
128 EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
129 
130 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
131 static u32 __read_mostly tsc_tolerance_ppm = 250;
132 module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
133 
134 /* lapic timer advance (tscdeadline mode only) in nanoseconds */
135 unsigned int __read_mostly lapic_timer_advance_ns = 0;
136 module_param(lapic_timer_advance_ns, uint, S_IRUGO | S_IWUSR);
137 
138 static bool __read_mostly vector_hashing = true;
139 module_param(vector_hashing, bool, S_IRUGO);
140 
141 #define KVM_NR_SHARED_MSRS 16
142 
143 struct kvm_shared_msrs_global {
144         int nr;
145         u32 msrs[KVM_NR_SHARED_MSRS];
146 };
147 
148 struct kvm_shared_msrs {
149         struct user_return_notifier urn;
150         bool registered;
151         struct kvm_shared_msr_values {
152                 u64 host;
153                 u64 curr;
154         } values[KVM_NR_SHARED_MSRS];
155 };
156 
157 static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
158 static struct kvm_shared_msrs __percpu *shared_msrs;
159 
160 struct kvm_stats_debugfs_item debugfs_entries[] = {
161         { "pf_fixed", VCPU_STAT(pf_fixed) },
162         { "pf_guest", VCPU_STAT(pf_guest) },
163         { "tlb_flush", VCPU_STAT(tlb_flush) },
164         { "invlpg", VCPU_STAT(invlpg) },
165         { "exits", VCPU_STAT(exits) },
166         { "io_exits", VCPU_STAT(io_exits) },
167         { "mmio_exits", VCPU_STAT(mmio_exits) },
168         { "signal_exits", VCPU_STAT(signal_exits) },
169         { "irq_window", VCPU_STAT(irq_window_exits) },
170         { "nmi_window", VCPU_STAT(nmi_window_exits) },
171         { "halt_exits", VCPU_STAT(halt_exits) },
172         { "halt_successful_poll", VCPU_STAT(halt_successful_poll) },
173         { "halt_attempted_poll", VCPU_STAT(halt_attempted_poll) },
174         { "halt_poll_invalid", VCPU_STAT(halt_poll_invalid) },
175         { "halt_wakeup", VCPU_STAT(halt_wakeup) },
176         { "hypercalls", VCPU_STAT(hypercalls) },
177         { "request_irq", VCPU_STAT(request_irq_exits) },
178         { "irq_exits", VCPU_STAT(irq_exits) },
179         { "host_state_reload", VCPU_STAT(host_state_reload) },
180         { "efer_reload", VCPU_STAT(efer_reload) },
181         { "fpu_reload", VCPU_STAT(fpu_reload) },
182         { "insn_emulation", VCPU_STAT(insn_emulation) },
183         { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
184         { "irq_injections", VCPU_STAT(irq_injections) },
185         { "nmi_injections", VCPU_STAT(nmi_injections) },
186         { "req_event", VCPU_STAT(req_event) },
187         { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
188         { "mmu_pte_write", VM_STAT(mmu_pte_write) },
189         { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
190         { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
191         { "mmu_flooded", VM_STAT(mmu_flooded) },
192         { "mmu_recycled", VM_STAT(mmu_recycled) },
193         { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
194         { "mmu_unsync", VM_STAT(mmu_unsync) },
195         { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
196         { "largepages", VM_STAT(lpages) },
197         { "max_mmu_page_hash_collisions",
198                 VM_STAT(max_mmu_page_hash_collisions) },
199         { NULL }
200 };
201 
202 u64 __read_mostly host_xcr0;
203 
204 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
205 
206 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
207 {
208         int i;
209         for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
210                 vcpu->arch.apf.gfns[i] = ~0;
211 }
212 
213 static void kvm_on_user_return(struct user_return_notifier *urn)
214 {
215         unsigned slot;
216         struct kvm_shared_msrs *locals
217                 = container_of(urn, struct kvm_shared_msrs, urn);
218         struct kvm_shared_msr_values *values;
219         unsigned long flags;
220 
221         /*
222          * Disabling irqs at this point since the following code could be
223          * interrupted and executed through kvm_arch_hardware_disable()
224          */
225         local_irq_save(flags);
226         if (locals->registered) {
227                 locals->registered = false;
228                 user_return_notifier_unregister(urn);
229         }
230         local_irq_restore(flags);
231         for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
232                 values = &locals->values[slot];
233                 if (values->host != values->curr) {
234                         wrmsrl(shared_msrs_global.msrs[slot], values->host);
235                         values->curr = values->host;
236                 }
237         }
238 }
239 
240 static void shared_msr_update(unsigned slot, u32 msr)
241 {
242         u64 value;
243         unsigned int cpu = smp_processor_id();
244         struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
245 
246         /* only read, and nobody should modify it at this time,
247          * so don't need lock */
248         if (slot >= shared_msrs_global.nr) {
249                 printk(KERN_ERR "kvm: invalid MSR slot!");
250                 return;
251         }
252         rdmsrl_safe(msr, &value);
253         smsr->values[slot].host = value;
254         smsr->values[slot].curr = value;
255 }
256 
257 void kvm_define_shared_msr(unsigned slot, u32 msr)
258 {
259         BUG_ON(slot >= KVM_NR_SHARED_MSRS);
260         shared_msrs_global.msrs[slot] = msr;
261         if (slot >= shared_msrs_global.nr)
262                 shared_msrs_global.nr = slot + 1;
263 }
264 EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
265 
266 static void kvm_shared_msr_cpu_online(void)
267 {
268         unsigned i;
269 
270         for (i = 0; i < shared_msrs_global.nr; ++i)
271                 shared_msr_update(i, shared_msrs_global.msrs[i]);
272 }
273 
274 int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
275 {
276         unsigned int cpu = smp_processor_id();
277         struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
278         int err;
279 
280         if (((value ^ smsr->values[slot].curr) & mask) == 0)
281                 return 0;
282         smsr->values[slot].curr = value;
283         err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
284         if (err)
285                 return 1;
286 
287         if (!smsr->registered) {
288                 smsr->urn.on_user_return = kvm_on_user_return;
289                 user_return_notifier_register(&smsr->urn);
290                 smsr->registered = true;
291         }
292         return 0;
293 }
294 EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
295 
296 static void drop_user_return_notifiers(void)
297 {
298         unsigned int cpu = smp_processor_id();
299         struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
300 
301         if (smsr->registered)
302                 kvm_on_user_return(&smsr->urn);
303 }
304 
305 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
306 {
307         return vcpu->arch.apic_base;
308 }
309 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
310 
311 int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
312 {
313         u64 old_state = vcpu->arch.apic_base &
314                 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
315         u64 new_state = msr_info->data &
316                 (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE);
317         u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) | 0x2ff |
318                 (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
319 
320         if ((msr_info->data & reserved_bits) || new_state == X2APIC_ENABLE)
321                 return 1;
322         if (!msr_info->host_initiated &&
323             ((new_state == MSR_IA32_APICBASE_ENABLE &&
324               old_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) ||
325              (new_state == (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE) &&
326               old_state == 0)))
327                 return 1;
328 
329         kvm_lapic_set_base(vcpu, msr_info->data);
330         return 0;
331 }
332 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
333 
334 asmlinkage __visible void kvm_spurious_fault(void)
335 {
336         /* Fault while not rebooting.  We want the trace. */
337         BUG();
338 }
339 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
340 
341 #define EXCPT_BENIGN            0
342 #define EXCPT_CONTRIBUTORY      1
343 #define EXCPT_PF                2
344 
345 static int exception_class(int vector)
346 {
347         switch (vector) {
348         case PF_VECTOR:
349                 return EXCPT_PF;
350         case DE_VECTOR:
351         case TS_VECTOR:
352         case NP_VECTOR:
353         case SS_VECTOR:
354         case GP_VECTOR:
355                 return EXCPT_CONTRIBUTORY;
356         default:
357                 break;
358         }
359         return EXCPT_BENIGN;
360 }
361 
362 #define EXCPT_FAULT             0
363 #define EXCPT_TRAP              1
364 #define EXCPT_ABORT             2
365 #define EXCPT_INTERRUPT         3
366 
367 static int exception_type(int vector)
368 {
369         unsigned int mask;
370 
371         if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
372                 return EXCPT_INTERRUPT;
373 
374         mask = 1 << vector;
375 
376         /* #DB is trap, as instruction watchpoints are handled elsewhere */
377         if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
378                 return EXCPT_TRAP;
379 
380         if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
381                 return EXCPT_ABORT;
382 
383         /* Reserved exceptions will result in fault */
384         return EXCPT_FAULT;
385 }
386 
387 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
388                 unsigned nr, bool has_error, u32 error_code,
389                 bool reinject)
390 {
391         u32 prev_nr;
392         int class1, class2;
393 
394         kvm_make_request(KVM_REQ_EVENT, vcpu);
395 
396         if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
397         queue:
398                 if (has_error && !is_protmode(vcpu))
399                         has_error = false;
400                 if (reinject) {
401                         /*
402                          * On vmentry, vcpu->arch.exception.pending is only
403                          * true if an event injection was blocked by
404                          * nested_run_pending.  In that case, however,
405                          * vcpu_enter_guest requests an immediate exit,
406                          * and the guest shouldn't proceed far enough to
407                          * need reinjection.
408                          */
409                         WARN_ON_ONCE(vcpu->arch.exception.pending);
410                         vcpu->arch.exception.injected = true;
411                 } else {
412                         vcpu->arch.exception.pending = true;
413                         vcpu->arch.exception.injected = false;
414                 }
415                 vcpu->arch.exception.has_error_code = has_error;
416                 vcpu->arch.exception.nr = nr;
417                 vcpu->arch.exception.error_code = error_code;
418                 return;
419         }
420 
421         /* to check exception */
422         prev_nr = vcpu->arch.exception.nr;
423         if (prev_nr == DF_VECTOR) {
424                 /* triple fault -> shutdown */
425                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
426                 return;
427         }
428         class1 = exception_class(prev_nr);
429         class2 = exception_class(nr);
430         if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
431                 || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
432                 /*
433                  * Generate double fault per SDM Table 5-5.  Set
434                  * exception.pending = true so that the double fault
435                  * can trigger a nested vmexit.
436                  */
437                 vcpu->arch.exception.pending = true;
438                 vcpu->arch.exception.injected = false;
439                 vcpu->arch.exception.has_error_code = true;
440                 vcpu->arch.exception.nr = DF_VECTOR;
441                 vcpu->arch.exception.error_code = 0;
442         } else
443                 /* replace previous exception with a new one in a hope
444                    that instruction re-execution will regenerate lost
445                    exception */
446                 goto queue;
447 }
448 
449 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
450 {
451         kvm_multiple_exception(vcpu, nr, false, 0, false);
452 }
453 EXPORT_SYMBOL_GPL(kvm_queue_exception);
454 
455 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
456 {
457         kvm_multiple_exception(vcpu, nr, false, 0, true);
458 }
459 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
460 
461 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
462 {
463         if (err)
464                 kvm_inject_gp(vcpu, 0);
465         else
466                 return kvm_skip_emulated_instruction(vcpu);
467 
468         return 1;
469 }
470 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
471 
472 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
473 {
474         ++vcpu->stat.pf_guest;
475         vcpu->arch.exception.nested_apf =
476                 is_guest_mode(vcpu) && fault->async_page_fault;
477         if (vcpu->arch.exception.nested_apf)
478                 vcpu->arch.apf.nested_apf_token = fault->address;
479         else
480                 vcpu->arch.cr2 = fault->address;
481         kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
482 }
483 EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
484 
485 static bool kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
486 {
487         if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
488                 vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
489         else
490                 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
491 
492         return fault->nested_page_fault;
493 }
494 
495 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
496 {
497         atomic_inc(&vcpu->arch.nmi_queued);
498         kvm_make_request(KVM_REQ_NMI, vcpu);
499 }
500 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
501 
502 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
503 {
504         kvm_multiple_exception(vcpu, nr, true, error_code, false);
505 }
506 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
507 
508 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
509 {
510         kvm_multiple_exception(vcpu, nr, true, error_code, true);
511 }
512 EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
513 
514 /*
515  * Checks if cpl <= required_cpl; if true, return true.  Otherwise queue
516  * a #GP and return false.
517  */
518 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
519 {
520         if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
521                 return true;
522         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
523         return false;
524 }
525 EXPORT_SYMBOL_GPL(kvm_require_cpl);
526 
527 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
528 {
529         if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
530                 return true;
531 
532         kvm_queue_exception(vcpu, UD_VECTOR);
533         return false;
534 }
535 EXPORT_SYMBOL_GPL(kvm_require_dr);
536 
537 /*
538  * This function will be used to read from the physical memory of the currently
539  * running guest. The difference to kvm_vcpu_read_guest_page is that this function
540  * can read from guest physical or from the guest's guest physical memory.
541  */
542 int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
543                             gfn_t ngfn, void *data, int offset, int len,
544                             u32 access)
545 {
546         struct x86_exception exception;
547         gfn_t real_gfn;
548         gpa_t ngpa;
549 
550         ngpa     = gfn_to_gpa(ngfn);
551         real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
552         if (real_gfn == UNMAPPED_GVA)
553                 return -EFAULT;
554 
555         real_gfn = gpa_to_gfn(real_gfn);
556 
557         return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
558 }
559 EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
560 
561 static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
562                                void *data, int offset, int len, u32 access)
563 {
564         return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
565                                        data, offset, len, access);
566 }
567 
568 /*
569  * Load the pae pdptrs.  Return true is they are all valid.
570  */
571 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
572 {
573         gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
574         unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
575         int i;
576         int ret;
577         u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
578 
579         ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
580                                       offset * sizeof(u64), sizeof(pdpte),
581                                       PFERR_USER_MASK|PFERR_WRITE_MASK);
582         if (ret < 0) {
583                 ret = 0;
584                 goto out;
585         }
586         for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
587                 if ((pdpte[i] & PT_PRESENT_MASK) &&
588                     (pdpte[i] &
589                      vcpu->arch.mmu.guest_rsvd_check.rsvd_bits_mask[0][2])) {
590                         ret = 0;
591                         goto out;
592                 }
593         }
594         ret = 1;
595 
596         memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
597         __set_bit(VCPU_EXREG_PDPTR,
598                   (unsigned long *)&vcpu->arch.regs_avail);
599         __set_bit(VCPU_EXREG_PDPTR,
600                   (unsigned long *)&vcpu->arch.regs_dirty);
601 out:
602 
603         return ret;
604 }
605 EXPORT_SYMBOL_GPL(load_pdptrs);
606 
607 bool pdptrs_changed(struct kvm_vcpu *vcpu)
608 {
609         u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
610         bool changed = true;
611         int offset;
612         gfn_t gfn;
613         int r;
614 
615         if (is_long_mode(vcpu) || !is_pae(vcpu))
616                 return false;
617 
618         if (!test_bit(VCPU_EXREG_PDPTR,
619                       (unsigned long *)&vcpu->arch.regs_avail))
620                 return true;
621 
622         gfn = (kvm_read_cr3(vcpu) & 0xffffffe0ul) >> PAGE_SHIFT;
623         offset = (kvm_read_cr3(vcpu) & 0xffffffe0ul) & (PAGE_SIZE - 1);
624         r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
625                                        PFERR_USER_MASK | PFERR_WRITE_MASK);
626         if (r < 0)
627                 goto out;
628         changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
629 out:
630 
631         return changed;
632 }
633 EXPORT_SYMBOL_GPL(pdptrs_changed);
634 
635 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
636 {
637         unsigned long old_cr0 = kvm_read_cr0(vcpu);
638         unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
639 
640         cr0 |= X86_CR0_ET;
641 
642 #ifdef CONFIG_X86_64
643         if (cr0 & 0xffffffff00000000UL)
644                 return 1;
645 #endif
646 
647         cr0 &= ~CR0_RESERVED_BITS;
648 
649         if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
650                 return 1;
651 
652         if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
653                 return 1;
654 
655         if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
656 #ifdef CONFIG_X86_64
657                 if ((vcpu->arch.efer & EFER_LME)) {
658                         int cs_db, cs_l;
659 
660                         if (!is_pae(vcpu))
661                                 return 1;
662                         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
663                         if (cs_l)
664                                 return 1;
665                 } else
666 #endif
667                 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
668                                                  kvm_read_cr3(vcpu)))
669                         return 1;
670         }
671 
672         if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
673                 return 1;
674 
675         kvm_x86_ops->set_cr0(vcpu, cr0);
676 
677         if ((cr0 ^ old_cr0) & X86_CR0_PG) {
678                 kvm_clear_async_pf_completion_queue(vcpu);
679                 kvm_async_pf_hash_reset(vcpu);
680         }
681 
682         if ((cr0 ^ old_cr0) & update_bits)
683                 kvm_mmu_reset_context(vcpu);
684 
685         if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
686             kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
687             !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
688                 kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
689 
690         return 0;
691 }
692 EXPORT_SYMBOL_GPL(kvm_set_cr0);
693 
694 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
695 {
696         (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
697 }
698 EXPORT_SYMBOL_GPL(kvm_lmsw);
699 
700 static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
701 {
702         if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
703                         !vcpu->guest_xcr0_loaded) {
704                 /* kvm_set_xcr() also depends on this */
705                 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
706                 vcpu->guest_xcr0_loaded = 1;
707         }
708 }
709 
710 static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
711 {
712         if (vcpu->guest_xcr0_loaded) {
713                 if (vcpu->arch.xcr0 != host_xcr0)
714                         xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
715                 vcpu->guest_xcr0_loaded = 0;
716         }
717 }
718 
719 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
720 {
721         u64 xcr0 = xcr;
722         u64 old_xcr0 = vcpu->arch.xcr0;
723         u64 valid_bits;
724 
725         /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now  */
726         if (index != XCR_XFEATURE_ENABLED_MASK)
727                 return 1;
728         if (!(xcr0 & XFEATURE_MASK_FP))
729                 return 1;
730         if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
731                 return 1;
732 
733         /*
734          * Do not allow the guest to set bits that we do not support
735          * saving.  However, xcr0 bit 0 is always set, even if the
736          * emulated CPU does not support XSAVE (see fx_init).
737          */
738         valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
739         if (xcr0 & ~valid_bits)
740                 return 1;
741 
742         if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
743             (!(xcr0 & XFEATURE_MASK_BNDCSR)))
744                 return 1;
745 
746         if (xcr0 & XFEATURE_MASK_AVX512) {
747                 if (!(xcr0 & XFEATURE_MASK_YMM))
748                         return 1;
749                 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
750                         return 1;
751         }
752         vcpu->arch.xcr0 = xcr0;
753 
754         if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
755                 kvm_update_cpuid(vcpu);
756         return 0;
757 }
758 
759 int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
760 {
761         if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
762             __kvm_set_xcr(vcpu, index, xcr)) {
763                 kvm_inject_gp(vcpu, 0);
764                 return 1;
765         }
766         return 0;
767 }
768 EXPORT_SYMBOL_GPL(kvm_set_xcr);
769 
770 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
771 {
772         unsigned long old_cr4 = kvm_read_cr4(vcpu);
773         unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
774                                    X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE;
775 
776         if (cr4 & CR4_RESERVED_BITS)
777                 return 1;
778 
779         if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) && (cr4 & X86_CR4_OSXSAVE))
780                 return 1;
781 
782         if (!guest_cpuid_has(vcpu, X86_FEATURE_SMEP) && (cr4 & X86_CR4_SMEP))
783                 return 1;
784 
785         if (!guest_cpuid_has(vcpu, X86_FEATURE_SMAP) && (cr4 & X86_CR4_SMAP))
786                 return 1;
787 
788         if (!guest_cpuid_has(vcpu, X86_FEATURE_FSGSBASE) && (cr4 & X86_CR4_FSGSBASE))
789                 return 1;
790 
791         if (!guest_cpuid_has(vcpu, X86_FEATURE_PKU) && (cr4 & X86_CR4_PKE))
792                 return 1;
793 
794         if (!guest_cpuid_has(vcpu, X86_FEATURE_LA57) && (cr4 & X86_CR4_LA57))
795                 return 1;
796 
797         if (is_long_mode(vcpu)) {
798                 if (!(cr4 & X86_CR4_PAE))
799                         return 1;
800         } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
801                    && ((cr4 ^ old_cr4) & pdptr_bits)
802                    && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
803                                    kvm_read_cr3(vcpu)))
804                 return 1;
805 
806         if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
807                 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
808                         return 1;
809 
810                 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
811                 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
812                         return 1;
813         }
814 
815         if (kvm_x86_ops->set_cr4(vcpu, cr4))
816                 return 1;
817 
818         if (((cr4 ^ old_cr4) & pdptr_bits) ||
819             (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
820                 kvm_mmu_reset_context(vcpu);
821 
822         if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
823                 kvm_update_cpuid(vcpu);
824 
825         return 0;
826 }
827 EXPORT_SYMBOL_GPL(kvm_set_cr4);
828 
829 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
830 {
831 #ifdef CONFIG_X86_64
832         cr3 &= ~CR3_PCID_INVD;
833 #endif
834 
835         if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
836                 kvm_mmu_sync_roots(vcpu);
837                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
838                 return 0;
839         }
840 
841         if (is_long_mode(vcpu) &&
842             (cr3 & rsvd_bits(cpuid_maxphyaddr(vcpu), 62)))
843                 return 1;
844         else if (is_pae(vcpu) && is_paging(vcpu) &&
845                    !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
846                 return 1;
847 
848         vcpu->arch.cr3 = cr3;
849         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
850         kvm_mmu_new_cr3(vcpu);
851         return 0;
852 }
853 EXPORT_SYMBOL_GPL(kvm_set_cr3);
854 
855 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
856 {
857         if (cr8 & CR8_RESERVED_BITS)
858                 return 1;
859         if (lapic_in_kernel(vcpu))
860                 kvm_lapic_set_tpr(vcpu, cr8);
861         else
862                 vcpu->arch.cr8 = cr8;
863         return 0;
864 }
865 EXPORT_SYMBOL_GPL(kvm_set_cr8);
866 
867 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
868 {
869         if (lapic_in_kernel(vcpu))
870                 return kvm_lapic_get_cr8(vcpu);
871         else
872                 return vcpu->arch.cr8;
873 }
874 EXPORT_SYMBOL_GPL(kvm_get_cr8);
875 
876 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
877 {
878         int i;
879 
880         if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
881                 for (i = 0; i < KVM_NR_DB_REGS; i++)
882                         vcpu->arch.eff_db[i] = vcpu->arch.db[i];
883                 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
884         }
885 }
886 
887 static void kvm_update_dr6(struct kvm_vcpu *vcpu)
888 {
889         if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
890                 kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
891 }
892 
893 static void kvm_update_dr7(struct kvm_vcpu *vcpu)
894 {
895         unsigned long dr7;
896 
897         if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
898                 dr7 = vcpu->arch.guest_debug_dr7;
899         else
900                 dr7 = vcpu->arch.dr7;
901         kvm_x86_ops->set_dr7(vcpu, dr7);
902         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
903         if (dr7 & DR7_BP_EN_MASK)
904                 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
905 }
906 
907 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
908 {
909         u64 fixed = DR6_FIXED_1;
910 
911         if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
912                 fixed |= DR6_RTM;
913         return fixed;
914 }
915 
916 static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
917 {
918         switch (dr) {
919         case 0 ... 3:
920                 vcpu->arch.db[dr] = val;
921                 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
922                         vcpu->arch.eff_db[dr] = val;
923                 break;
924         case 4:
925                 /* fall through */
926         case 6:
927                 if (val & 0xffffffff00000000ULL)
928                         return -1; /* #GP */
929                 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
930                 kvm_update_dr6(vcpu);
931                 break;
932         case 5:
933                 /* fall through */
934         default: /* 7 */
935                 if (val & 0xffffffff00000000ULL)
936                         return -1; /* #GP */
937                 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
938                 kvm_update_dr7(vcpu);
939                 break;
940         }
941 
942         return 0;
943 }
944 
945 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
946 {
947         if (__kvm_set_dr(vcpu, dr, val)) {
948                 kvm_inject_gp(vcpu, 0);
949                 return 1;
950         }
951         return 0;
952 }
953 EXPORT_SYMBOL_GPL(kvm_set_dr);
954 
955 int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
956 {
957         switch (dr) {
958         case 0 ... 3:
959                 *val = vcpu->arch.db[dr];
960                 break;
961         case 4:
962                 /* fall through */
963         case 6:
964                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
965                         *val = vcpu->arch.dr6;
966                 else
967                         *val = kvm_x86_ops->get_dr6(vcpu);
968                 break;
969         case 5:
970                 /* fall through */
971         default: /* 7 */
972                 *val = vcpu->arch.dr7;
973                 break;
974         }
975         return 0;
976 }
977 EXPORT_SYMBOL_GPL(kvm_get_dr);
978 
979 bool kvm_rdpmc(struct kvm_vcpu *vcpu)
980 {
981         u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
982         u64 data;
983         int err;
984 
985         err = kvm_pmu_rdpmc(vcpu, ecx, &data);
986         if (err)
987                 return err;
988         kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
989         kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
990         return err;
991 }
992 EXPORT_SYMBOL_GPL(kvm_rdpmc);
993 
994 /*
995  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
996  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
997  *
998  * This list is modified at module load time to reflect the
999  * capabilities of the host cpu. This capabilities test skips MSRs that are
1000  * kvm-specific. Those are put in emulated_msrs; filtering of emulated_msrs
1001  * may depend on host virtualization features rather than host cpu features.
1002  */
1003 
1004 static u32 msrs_to_save[] = {
1005         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
1006         MSR_STAR,
1007 #ifdef CONFIG_X86_64
1008         MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
1009 #endif
1010         MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
1011         MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
1012         MSR_IA32_SPEC_CTRL, MSR_IA32_ARCH_CAPABILITIES
1013 };
1014 
1015 static unsigned num_msrs_to_save;
1016 
1017 static u32 emulated_msrs[] = {
1018         MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
1019         MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
1020         HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
1021         HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
1022         HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
1023         HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
1024         HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
1025         HV_X64_MSR_RESET,
1026         HV_X64_MSR_VP_INDEX,
1027         HV_X64_MSR_VP_RUNTIME,
1028         HV_X64_MSR_SCONTROL,
1029         HV_X64_MSR_STIMER0_CONFIG,
1030         HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
1031         MSR_KVM_PV_EOI_EN,
1032 
1033         MSR_IA32_TSC_ADJUST,
1034         MSR_IA32_TSCDEADLINE,
1035         MSR_IA32_MISC_ENABLE,
1036         MSR_IA32_MCG_STATUS,
1037         MSR_IA32_MCG_CTL,
1038         MSR_IA32_MCG_EXT_CTL,
1039         MSR_IA32_SMBASE,
1040         MSR_PLATFORM_INFO,
1041         MSR_MISC_FEATURES_ENABLES,
1042 };
1043 
1044 static unsigned num_emulated_msrs;
1045 
1046 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1047 {
1048         if (efer & efer_reserved_bits)
1049                 return false;
1050 
1051         if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
1052                         return false;
1053 
1054         if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
1055                         return false;
1056 
1057         return true;
1058 }
1059 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1060 
1061 static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
1062 {
1063         u64 old_efer = vcpu->arch.efer;
1064 
1065         if (!kvm_valid_efer(vcpu, efer))
1066                 return 1;
1067 
1068         if (is_paging(vcpu)
1069             && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1070                 return 1;
1071 
1072         efer &= ~EFER_LMA;
1073         efer |= vcpu->arch.efer & EFER_LMA;
1074 
1075         kvm_x86_ops->set_efer(vcpu, efer);
1076 
1077         /* Update reserved bits */
1078         if ((efer ^ old_efer) & EFER_NX)
1079                 kvm_mmu_reset_context(vcpu);
1080 
1081         return 0;
1082 }
1083 
1084 void kvm_enable_efer_bits(u64 mask)
1085 {
1086        efer_reserved_bits &= ~mask;
1087 }
1088 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1089 
1090 /*
1091  * Writes msr value into into the appropriate "register".
1092  * Returns 0 on success, non-0 otherwise.
1093  * Assumes vcpu_load() was already called.
1094  */
1095 int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
1096 {
1097         switch (msr->index) {
1098         case MSR_FS_BASE:
1099         case MSR_GS_BASE:
1100         case MSR_KERNEL_GS_BASE:
1101         case MSR_CSTAR:
1102         case MSR_LSTAR:
1103                 if (is_noncanonical_address(msr->data, vcpu))
1104                         return 1;
1105                 break;
1106         case MSR_IA32_SYSENTER_EIP:
1107         case MSR_IA32_SYSENTER_ESP:
1108                 /*
1109                  * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1110                  * non-canonical address is written on Intel but not on
1111                  * AMD (which ignores the top 32-bits, because it does
1112                  * not implement 64-bit SYSENTER).
1113                  *
1114                  * 64-bit code should hence be able to write a non-canonical
1115                  * value on AMD.  Making the address canonical ensures that
1116                  * vmentry does not fail on Intel after writing a non-canonical
1117                  * value, and that something deterministic happens if the guest
1118                  * invokes 64-bit SYSENTER.
1119                  */
1120                 msr->data = get_canonical(msr->data, vcpu_virt_addr_bits(vcpu));
1121         }
1122         return kvm_x86_ops->set_msr(vcpu, msr);
1123 }
1124 EXPORT_SYMBOL_GPL(kvm_set_msr);
1125 
1126 /*
1127  * Adapt set_msr() to msr_io()'s calling convention
1128  */
1129 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1130 {
1131         struct msr_data msr;
1132         int r;
1133 
1134         msr.index = index;
1135         msr.host_initiated = true;
1136         r = kvm_get_msr(vcpu, &msr);
1137         if (r)
1138                 return r;
1139 
1140         *data = msr.data;
1141         return 0;
1142 }
1143 
1144 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1145 {
1146         struct msr_data msr;
1147 
1148         msr.data = *data;
1149         msr.index = index;
1150         msr.host_initiated = true;
1151         return kvm_set_msr(vcpu, &msr);
1152 }
1153 
1154 #ifdef CONFIG_X86_64
1155 struct pvclock_gtod_data {
1156         seqcount_t      seq;
1157 
1158         struct { /* extract of a clocksource struct */
1159                 int vclock_mode;
1160                 u64     cycle_last;
1161                 u64     mask;
1162                 u32     mult;
1163                 u32     shift;
1164         } clock;
1165 
1166         u64             boot_ns;
1167         u64             nsec_base;
1168         u64             wall_time_sec;
1169 };
1170 
1171 static struct pvclock_gtod_data pvclock_gtod_data;
1172 
1173 static void update_pvclock_gtod(struct timekeeper *tk)
1174 {
1175         struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
1176         u64 boot_ns;
1177 
1178         boot_ns = ktime_to_ns(ktime_add(tk->tkr_mono.base, tk->offs_boot));
1179 
1180         write_seqcount_begin(&vdata->seq);
1181 
1182         /* copy pvclock gtod data */
1183         vdata->clock.vclock_mode        = tk->tkr_mono.clock->archdata.vclock_mode;
1184         vdata->clock.cycle_last         = tk->tkr_mono.cycle_last;
1185         vdata->clock.mask               = tk->tkr_mono.mask;
1186         vdata->clock.mult               = tk->tkr_mono.mult;
1187         vdata->clock.shift              = tk->tkr_mono.shift;
1188 
1189         vdata->boot_ns                  = boot_ns;
1190         vdata->nsec_base                = tk->tkr_mono.xtime_nsec;
1191 
1192         vdata->wall_time_sec            = tk->xtime_sec;
1193 
1194         write_seqcount_end(&vdata->seq);
1195 }
1196 #endif
1197 
1198 void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
1199 {
1200         /*
1201          * Note: KVM_REQ_PENDING_TIMER is implicitly checked in
1202          * vcpu_enter_guest.  This function is only called from
1203          * the physical CPU that is running vcpu.
1204          */
1205         kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
1206 }
1207 
1208 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
1209 {
1210         int version;
1211         int r;
1212         struct pvclock_wall_clock wc;
1213         struct timespec64 boot;
1214 
1215         if (!wall_clock)
1216                 return;
1217 
1218         r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
1219         if (r)
1220                 return;
1221 
1222         if (version & 1)
1223                 ++version;  /* first time write, random junk */
1224 
1225         ++version;
1226 
1227         if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
1228                 return;
1229 
1230         /*
1231          * The guest calculates current wall clock time by adding
1232          * system time (updated by kvm_guest_time_update below) to the
1233          * wall clock specified here.  guest system time equals host
1234          * system time for us, thus we must fill in host boot time here.
1235          */
1236         getboottime64(&boot);
1237 
1238         if (kvm->arch.kvmclock_offset) {
1239                 struct timespec64 ts = ns_to_timespec64(kvm->arch.kvmclock_offset);
1240                 boot = timespec64_sub(boot, ts);
1241         }
1242         wc.sec = (u32)boot.tv_sec; /* overflow in 2106 guest time */
1243         wc.nsec = boot.tv_nsec;
1244         wc.version = version;
1245 
1246         kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
1247 
1248         version++;
1249         kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
1250 }
1251 
1252 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
1253 {
1254         do_shl32_div32(dividend, divisor);
1255         return dividend;
1256 }
1257 
1258 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
1259                                s8 *pshift, u32 *pmultiplier)
1260 {
1261         uint64_t scaled64;
1262         int32_t  shift = 0;
1263         uint64_t tps64;
1264         uint32_t tps32;
1265 
1266         tps64 = base_hz;
1267         scaled64 = scaled_hz;
1268         while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
1269                 tps64 >>= 1;
1270                 shift--;
1271         }
1272 
1273         tps32 = (uint32_t)tps64;
1274         while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
1275                 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
1276                         scaled64 >>= 1;
1277                 else
1278                         tps32 <<= 1;
1279                 shift++;
1280         }
1281 
1282         *pshift = shift;
1283         *pmultiplier = div_frac(scaled64, tps32);
1284 
1285         pr_debug("%s: base_hz %llu => %llu, shift %d, mul %u\n",
1286                  __func__, base_hz, scaled_hz, shift, *pmultiplier);
1287 }
1288 
1289 #ifdef CONFIG_X86_64
1290 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
1291 #endif
1292 
1293 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
1294 static unsigned long max_tsc_khz;
1295 
1296 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
1297 {
1298         u64 v = (u64)khz * (1000000 + ppm);
1299         do_div(v, 1000000);
1300         return v;
1301 }
1302 
1303 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1304 {
1305         u64 ratio;
1306 
1307         /* Guest TSC same frequency as host TSC? */
1308         if (!scale) {
1309                 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1310                 return 0;
1311         }
1312 
1313         /* TSC scaling supported? */
1314         if (!kvm_has_tsc_control) {
1315                 if (user_tsc_khz > tsc_khz) {
1316                         vcpu->arch.tsc_catchup = 1;
1317                         vcpu->arch.tsc_always_catchup = 1;
1318                         return 0;
1319                 } else {
1320                         WARN(1, "user requested TSC rate below hardware speed\n");
1321                         return -1;
1322                 }
1323         }
1324 
1325         /* TSC scaling required  - calculate ratio */
1326         ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
1327                                 user_tsc_khz, tsc_khz);
1328 
1329         if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
1330                 WARN_ONCE(1, "Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
1331                           user_tsc_khz);
1332                 return -1;
1333         }
1334 
1335         vcpu->arch.tsc_scaling_ratio = ratio;
1336         return 0;
1337 }
1338 
1339 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1340 {
1341         u32 thresh_lo, thresh_hi;
1342         int use_scaling = 0;
1343 
1344         /* tsc_khz can be zero if TSC calibration fails */
1345         if (user_tsc_khz == 0) {
1346                 /* set tsc_scaling_ratio to a safe value */
1347                 vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
1348                 return -1;
1349         }
1350 
1351         /* Compute a scale to convert nanoseconds in TSC cycles */
1352         kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
1353                            &vcpu->arch.virtual_tsc_shift,
1354                            &vcpu->arch.virtual_tsc_mult);
1355         vcpu->arch.virtual_tsc_khz = user_tsc_khz;
1356 
1357         /*
1358          * Compute the variation in TSC rate which is acceptable
1359          * within the range of tolerance and decide if the
1360          * rate being applied is within that bounds of the hardware
1361          * rate.  If so, no scaling or compensation need be done.
1362          */
1363         thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
1364         thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
1365         if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
1366                 pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
1367                 use_scaling = 1;
1368         }
1369         return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
1370 }
1371 
1372 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
1373 {
1374         u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
1375                                       vcpu->arch.virtual_tsc_mult,
1376                                       vcpu->arch.virtual_tsc_shift);
1377         tsc += vcpu->arch.this_tsc_write;
1378         return tsc;
1379 }
1380 
1381 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
1382 {
1383 #ifdef CONFIG_X86_64
1384         bool vcpus_matched;
1385         struct kvm_arch *ka = &vcpu->kvm->arch;
1386         struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1387 
1388         vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1389                          atomic_read(&vcpu->kvm->online_vcpus));
1390 
1391         /*
1392          * Once the masterclock is enabled, always perform request in
1393          * order to update it.
1394          *
1395          * In order to enable masterclock, the host clocksource must be TSC
1396          * and the vcpus need to have matched TSCs.  When that happens,
1397          * perform request to enable masterclock.
1398          */
1399         if (ka->use_master_clock ||
1400             (gtod->clock.vclock_mode == VCLOCK_TSC && vcpus_matched))
1401                 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1402 
1403         trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
1404                             atomic_read(&vcpu->kvm->online_vcpus),
1405                             ka->use_master_clock, gtod->clock.vclock_mode);
1406 #endif
1407 }
1408 
1409 static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
1410 {
1411         u64 curr_offset = vcpu->arch.tsc_offset;
1412         vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
1413 }
1414 
1415 /*
1416  * Multiply tsc by a fixed point number represented by ratio.
1417  *
1418  * The most significant 64-N bits (mult) of ratio represent the
1419  * integral part of the fixed point number; the remaining N bits
1420  * (frac) represent the fractional part, ie. ratio represents a fixed
1421  * point number (mult + frac * 2^(-N)).
1422  *
1423  * N equals to kvm_tsc_scaling_ratio_frac_bits.
1424  */
1425 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
1426 {
1427         return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
1428 }
1429 
1430 u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
1431 {
1432         u64 _tsc = tsc;
1433         u64 ratio = vcpu->arch.tsc_scaling_ratio;
1434 
1435         if (ratio != kvm_default_tsc_scaling_ratio)
1436                 _tsc = __scale_tsc(ratio, tsc);
1437 
1438         return _tsc;
1439 }
1440 EXPORT_SYMBOL_GPL(kvm_scale_tsc);
1441 
1442 static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1443 {
1444         u64 tsc;
1445 
1446         tsc = kvm_scale_tsc(vcpu, rdtsc());
1447 
1448         return target_tsc - tsc;
1449 }
1450 
1451 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
1452 {
1453         return vcpu->arch.tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
1454 }
1455 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
1456 
1457 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1458 {
1459         kvm_x86_ops->write_tsc_offset(vcpu, offset);
1460         vcpu->arch.tsc_offset = offset;
1461 }
1462 
1463 void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
1464 {
1465         struct kvm *kvm = vcpu->kvm;
1466         u64 offset, ns, elapsed;
1467         unsigned long flags;
1468         bool matched;
1469         bool already_matched;
1470         u64 data = msr->data;
1471         bool synchronizing = false;
1472 
1473         raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
1474         offset = kvm_compute_tsc_offset(vcpu, data);
1475         ns = ktime_get_boot_ns();
1476         elapsed = ns - kvm->arch.last_tsc_nsec;
1477 
1478         if (vcpu->arch.virtual_tsc_khz) {
1479                 if (data == 0 && msr->host_initiated) {
1480                         /*
1481                          * detection of vcpu initialization -- need to sync
1482                          * with other vCPUs. This particularly helps to keep
1483                          * kvm_clock stable after CPU hotplug
1484                          */
1485                         synchronizing = true;
1486                 } else {
1487                         u64 tsc_exp = kvm->arch.last_tsc_write +
1488                                                 nsec_to_cycles(vcpu, elapsed);
1489                         u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
1490                         /*
1491                          * Special case: TSC write with a small delta (1 second)
1492                          * of virtual cycle time against real time is
1493                          * interpreted as an attempt to synchronize the CPU.
1494                          */
1495                         synchronizing = data < tsc_exp + tsc_hz &&
1496                                         data + tsc_hz > tsc_exp;
1497                 }
1498         }
1499 
1500         /*
1501          * For a reliable TSC, we can match TSC offsets, and for an unstable
1502          * TSC, we add elapsed time in this computation.  We could let the
1503          * compensation code attempt to catch up if we fall behind, but
1504          * it's better to try to match offsets from the beginning.
1505          */
1506         if (synchronizing &&
1507             vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
1508                 if (!check_tsc_unstable()) {
1509                         offset = kvm->arch.cur_tsc_offset;
1510                         pr_debug("kvm: matched tsc offset for %llu\n", data);
1511                 } else {
1512                         u64 delta = nsec_to_cycles(vcpu, elapsed);
1513                         data += delta;
1514                         offset = kvm_compute_tsc_offset(vcpu, data);
1515                         pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
1516                 }
1517                 matched = true;
1518                 already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
1519         } else {
1520                 /*
1521                  * We split periods of matched TSC writes into generations.
1522                  * For each generation, we track the original measured
1523                  * nanosecond time, offset, and write, so if TSCs are in
1524                  * sync, we can match exact offset, and if not, we can match
1525                  * exact software computation in compute_guest_tsc()
1526                  *
1527                  * These values are tracked in kvm->arch.cur_xxx variables.
1528                  */
1529                 kvm->arch.cur_tsc_generation++;
1530                 kvm->arch.cur_tsc_nsec = ns;
1531                 kvm->arch.cur_tsc_write = data;
1532                 kvm->arch.cur_tsc_offset = offset;
1533                 matched = false;
1534                 pr_debug("kvm: new tsc generation %llu, clock %llu\n",
1535                          kvm->arch.cur_tsc_generation, data);
1536         }
1537 
1538         /*
1539          * We also track th most recent recorded KHZ, write and time to
1540          * allow the matching interval to be extended at each write.
1541          */
1542         kvm->arch.last_tsc_nsec = ns;
1543         kvm->arch.last_tsc_write = data;
1544         kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
1545 
1546         vcpu->arch.last_guest_tsc = data;
1547 
1548         /* Keep track of which generation this VCPU has synchronized to */
1549         vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
1550         vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
1551         vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
1552 
1553         if (!msr->host_initiated && guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST))
1554                 update_ia32_tsc_adjust_msr(vcpu, offset);
1555 
1556         kvm_vcpu_write_tsc_offset(vcpu, offset);
1557         raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
1558 
1559         spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
1560         if (!matched) {
1561                 kvm->arch.nr_vcpus_matched_tsc = 0;
1562         } else if (!already_matched) {
1563                 kvm->arch.nr_vcpus_matched_tsc++;
1564         }
1565 
1566         kvm_track_tsc_matching(vcpu);
1567         spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
1568 }
1569 
1570 EXPORT_SYMBOL_GPL(kvm_write_tsc);
1571 
1572 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
1573                                            s64 adjustment)
1574 {
1575         kvm_vcpu_write_tsc_offset(vcpu, vcpu->arch.tsc_offset + adjustment);
1576 }
1577 
1578 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
1579 {
1580         if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
1581                 WARN_ON(adjustment < 0);
1582         adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
1583         adjust_tsc_offset_guest(vcpu, adjustment);
1584 }
1585 
1586 #ifdef CONFIG_X86_64
1587 
1588 static u64 read_tsc(void)
1589 {
1590         u64 ret = (u64)rdtsc_ordered();
1591         u64 last = pvclock_gtod_data.clock.cycle_last;
1592 
1593         if (likely(ret >= last))
1594                 return ret;
1595 
1596         /*
1597          * GCC likes to generate cmov here, but this branch is extremely
1598          * predictable (it's just a function of time and the likely is
1599          * very likely) and there's a data dependence, so force GCC
1600          * to generate a branch instead.  I don't barrier() because
1601          * we don't actually need a barrier, and if this function
1602          * ever gets inlined it will generate worse code.
1603          */
1604         asm volatile ("");
1605         return last;
1606 }
1607 
1608 static inline u64 vgettsc(u64 *cycle_now)
1609 {
1610         long v;
1611         struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1612 
1613         *cycle_now = read_tsc();
1614 
1615         v = (*cycle_now - gtod->clock.cycle_last) & gtod->clock.mask;
1616         return v * gtod->clock.mult;
1617 }
1618 
1619 static int do_monotonic_boot(s64 *t, u64 *cycle_now)
1620 {
1621         struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1622         unsigned long seq;
1623         int mode;
1624         u64 ns;
1625 
1626         do {
1627                 seq = read_seqcount_begin(&gtod->seq);
1628                 mode = gtod->clock.vclock_mode;
1629                 ns = gtod->nsec_base;
1630                 ns += vgettsc(cycle_now);
1631                 ns >>= gtod->clock.shift;
1632                 ns += gtod->boot_ns;
1633         } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
1634         *t = ns;
1635 
1636         return mode;
1637 }
1638 
1639 static int do_realtime(struct timespec *ts, u64 *cycle_now)
1640 {
1641         struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
1642         unsigned long seq;
1643         int mode;
1644         u64 ns;
1645 
1646         do {
1647                 seq = read_seqcount_begin(&gtod->seq);
1648                 mode = gtod->clock.vclock_mode;
1649                 ts->tv_sec = gtod->wall_time_sec;
1650                 ns = gtod->nsec_base;
1651                 ns += vgettsc(cycle_now);
1652                 ns >>= gtod->clock.shift;
1653         } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
1654 
1655         ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
1656         ts->tv_nsec = ns;
1657 
1658         return mode;
1659 }
1660 
1661 /* returns true if host is using tsc clocksource */
1662 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *cycle_now)
1663 {
1664         /* checked again under seqlock below */
1665         if (pvclock_gtod_data.clock.vclock_mode != VCLOCK_TSC)
1666                 return false;
1667 
1668         return do_monotonic_boot(kernel_ns, cycle_now) == VCLOCK_TSC;
1669 }
1670 
1671 /* returns true if host is using tsc clocksource */
1672 static bool kvm_get_walltime_and_clockread(struct timespec *ts,
1673                                            u64 *cycle_now)
1674 {
1675         /* checked again under seqlock below */
1676         if (pvclock_gtod_data.clock.vclock_mode != VCLOCK_TSC)
1677                 return false;
1678 
1679         return do_realtime(ts, cycle_now) == VCLOCK_TSC;
1680 }
1681 #endif
1682 
1683 /*
1684  *
1685  * Assuming a stable TSC across physical CPUS, and a stable TSC
1686  * across virtual CPUs, the following condition is possible.
1687  * Each numbered line represents an event visible to both
1688  * CPUs at the next numbered event.
1689  *
1690  * "timespecX" represents host monotonic time. "tscX" represents
1691  * RDTSC value.
1692  *
1693  *              VCPU0 on CPU0           |       VCPU1 on CPU1
1694  *
1695  * 1.  read timespec0,tsc0
1696  * 2.                                   | timespec1 = timespec0 + N
1697  *                                      | tsc1 = tsc0 + M
1698  * 3. transition to guest               | transition to guest
1699  * 4. ret0 = timespec0 + (rdtsc - tsc0) |
1700  * 5.                                   | ret1 = timespec1 + (rdtsc - tsc1)
1701  *                                      | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
1702  *
1703  * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
1704  *
1705  *      - ret0 < ret1
1706  *      - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
1707  *              ...
1708  *      - 0 < N - M => M < N
1709  *
1710  * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
1711  * always the case (the difference between two distinct xtime instances
1712  * might be smaller then the difference between corresponding TSC reads,
1713  * when updating guest vcpus pvclock areas).
1714  *
1715  * To avoid that problem, do not allow visibility of distinct
1716  * system_timestamp/tsc_timestamp values simultaneously: use a master
1717  * copy of host monotonic time values. Update that master copy
1718  * in lockstep.
1719  *
1720  * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
1721  *
1722  */
1723 
1724 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
1725 {
1726 #ifdef CONFIG_X86_64
1727         struct kvm_arch *ka = &kvm->arch;
1728         int vclock_mode;
1729         bool host_tsc_clocksource, vcpus_matched;
1730 
1731         vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
1732                         atomic_read(&kvm->online_vcpus));
1733 
1734         /*
1735          * If the host uses TSC clock, then passthrough TSC as stable
1736          * to the guest.
1737          */
1738         host_tsc_clocksource = kvm_get_time_and_clockread(
1739                                         &ka->master_kernel_ns,
1740                                         &ka->master_cycle_now);
1741 
1742         ka->use_master_clock = host_tsc_clocksource && vcpus_matched
1743                                 && !ka->backwards_tsc_observed
1744                                 && !ka->boot_vcpu_runs_old_kvmclock;
1745 
1746         if (ka->use_master_clock)
1747                 atomic_set(&kvm_guest_has_master_clock, 1);
1748 
1749         vclock_mode = pvclock_gtod_data.clock.vclock_mode;
1750         trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
1751                                         vcpus_matched);
1752 #endif
1753 }
1754 
1755 void kvm_make_mclock_inprogress_request(struct kvm *kvm)
1756 {
1757         kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
1758 }
1759 
1760 static void kvm_gen_update_masterclock(struct kvm *kvm)
1761 {
1762 #ifdef CONFIG_X86_64
1763         int i;
1764         struct kvm_vcpu *vcpu;
1765         struct kvm_arch *ka = &kvm->arch;
1766 
1767         spin_lock(&ka->pvclock_gtod_sync_lock);
1768         kvm_make_mclock_inprogress_request(kvm);
1769         /* no guest entries from this point */
1770         pvclock_update_vm_gtod_copy(kvm);
1771 
1772         kvm_for_each_vcpu(i, vcpu, kvm)
1773                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1774 
1775         /* guest entries allowed */
1776         kvm_for_each_vcpu(i, vcpu, kvm)
1777                 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
1778 
1779         spin_unlock(&ka->pvclock_gtod_sync_lock);
1780 #endif
1781 }
1782 
1783 u64 get_kvmclock_ns(struct kvm *kvm)
1784 {
1785         struct kvm_arch *ka = &kvm->arch;
1786         struct pvclock_vcpu_time_info hv_clock;
1787         u64 ret;
1788 
1789         spin_lock(&ka->pvclock_gtod_sync_lock);
1790         if (!ka->use_master_clock) {
1791                 spin_unlock(&ka->pvclock_gtod_sync_lock);
1792                 return ktime_get_boot_ns() + ka->kvmclock_offset;
1793         }
1794 
1795         hv_clock.tsc_timestamp = ka->master_cycle_now;
1796         hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
1797         spin_unlock(&ka->pvclock_gtod_sync_lock);
1798 
1799         /* both __this_cpu_read() and rdtsc() should be on the same cpu */
1800         get_cpu();
1801 
1802         if (__this_cpu_read(cpu_tsc_khz)) {
1803                 kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
1804                                    &hv_clock.tsc_shift,
1805                                    &hv_clock.tsc_to_system_mul);
1806                 ret = __pvclock_read_cycles(&hv_clock, rdtsc());
1807         } else
1808                 ret = ktime_get_boot_ns() + ka->kvmclock_offset;
1809 
1810         put_cpu();
1811 
1812         return ret;
1813 }
1814 
1815 static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
1816 {
1817         struct kvm_vcpu_arch *vcpu = &v->arch;
1818         struct pvclock_vcpu_time_info guest_hv_clock;
1819 
1820         if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
1821                 &guest_hv_clock, sizeof(guest_hv_clock))))
1822                 return;
1823 
1824         /* This VCPU is paused, but it's legal for a guest to read another
1825          * VCPU's kvmclock, so we really have to follow the specification where
1826          * it says that version is odd if data is being modified, and even after
1827          * it is consistent.
1828          *
1829          * Version field updates must be kept separate.  This is because
1830          * kvm_write_guest_cached might use a "rep movs" instruction, and
1831          * writes within a string instruction are weakly ordered.  So there
1832          * are three writes overall.
1833          *
1834          * As a small optimization, only write the version field in the first
1835          * and third write.  The vcpu->pv_time cache is still valid, because the
1836          * version field is the first in the struct.
1837          */
1838         BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
1839 
1840         if (guest_hv_clock.version & 1)
1841                 ++guest_hv_clock.version;  /* first time write, random junk */
1842 
1843         vcpu->hv_clock.version = guest_hv_clock.version + 1;
1844         kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1845                                 &vcpu->hv_clock,
1846                                 sizeof(vcpu->hv_clock.version));
1847 
1848         smp_wmb();
1849 
1850         /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
1851         vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
1852 
1853         if (vcpu->pvclock_set_guest_stopped_request) {
1854                 vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
1855                 vcpu->pvclock_set_guest_stopped_request = false;
1856         }
1857 
1858         trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
1859 
1860         kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1861                                 &vcpu->hv_clock,
1862                                 sizeof(vcpu->hv_clock));
1863 
1864         smp_wmb();
1865 
1866         vcpu->hv_clock.version++;
1867         kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
1868                                 &vcpu->hv_clock,
1869                                 sizeof(vcpu->hv_clock.version));
1870 }
1871 
1872 static int kvm_guest_time_update(struct kvm_vcpu *v)
1873 {
1874         unsigned long flags, tgt_tsc_khz;
1875         struct kvm_vcpu_arch *vcpu = &v->arch;
1876         struct kvm_arch *ka = &v->kvm->arch;
1877         s64 kernel_ns;
1878         u64 tsc_timestamp, host_tsc;
1879         u8 pvclock_flags;
1880         bool use_master_clock;
1881 
1882         kernel_ns = 0;
1883         host_tsc = 0;
1884 
1885         /*
1886          * If the host uses TSC clock, then passthrough TSC as stable
1887          * to the guest.
1888          */
1889         spin_lock(&ka->pvclock_gtod_sync_lock);
1890         use_master_clock = ka->use_master_clock;
1891         if (use_master_clock) {
1892                 host_tsc = ka->master_cycle_now;
1893                 kernel_ns = ka->master_kernel_ns;
1894         }
1895         spin_unlock(&ka->pvclock_gtod_sync_lock);
1896 
1897         /* Keep irq disabled to prevent changes to the clock */
1898         local_irq_save(flags);
1899         tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
1900         if (unlikely(tgt_tsc_khz == 0)) {
1901                 local_irq_restore(flags);
1902                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1903                 return 1;
1904         }
1905         if (!use_master_clock) {
1906                 host_tsc = rdtsc();
1907                 kernel_ns = ktime_get_boot_ns();
1908         }
1909 
1910         tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
1911 
1912         /*
1913          * We may have to catch up the TSC to match elapsed wall clock
1914          * time for two reasons, even if kvmclock is used.
1915          *   1) CPU could have been running below the maximum TSC rate
1916          *   2) Broken TSC compensation resets the base at each VCPU
1917          *      entry to avoid unknown leaps of TSC even when running
1918          *      again on the same CPU.  This may cause apparent elapsed
1919          *      time to disappear, and the guest to stand still or run
1920          *      very slowly.
1921          */
1922         if (vcpu->tsc_catchup) {
1923                 u64 tsc = compute_guest_tsc(v, kernel_ns);
1924                 if (tsc > tsc_timestamp) {
1925                         adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
1926                         tsc_timestamp = tsc;
1927                 }
1928         }
1929 
1930         local_irq_restore(flags);
1931 
1932         /* With all the info we got, fill in the values */
1933 
1934         if (kvm_has_tsc_control)
1935                 tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
1936 
1937         if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
1938                 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
1939                                    &vcpu->hv_clock.tsc_shift,
1940                                    &vcpu->hv_clock.tsc_to_system_mul);
1941                 vcpu->hw_tsc_khz = tgt_tsc_khz;
1942         }
1943 
1944         vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
1945         vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
1946         vcpu->last_guest_tsc = tsc_timestamp;
1947 
1948         /* If the host uses TSC clocksource, then it is stable */
1949         pvclock_flags = 0;
1950         if (use_master_clock)
1951                 pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
1952 
1953         vcpu->hv_clock.flags = pvclock_flags;
1954 
1955         if (vcpu->pv_time_enabled)
1956                 kvm_setup_pvclock_page(v);
1957         if (v == kvm_get_vcpu(v->kvm, 0))
1958                 kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
1959         return 0;
1960 }
1961 
1962 /*
1963  * kvmclock updates which are isolated to a given vcpu, such as
1964  * vcpu->cpu migration, should not allow system_timestamp from
1965  * the rest of the vcpus to remain static. Otherwise ntp frequency
1966  * correction applies to one vcpu's system_timestamp but not
1967  * the others.
1968  *
1969  * So in those cases, request a kvmclock update for all vcpus.
1970  * We need to rate-limit these requests though, as they can
1971  * considerably slow guests that have a large number of vcpus.
1972  * The time for a remote vcpu to update its kvmclock is bound
1973  * by the delay we use to rate-limit the updates.
1974  */
1975 
1976 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
1977 
1978 static void kvmclock_update_fn(struct work_struct *work)
1979 {
1980         int i;
1981         struct delayed_work *dwork = to_delayed_work(work);
1982         struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
1983                                            kvmclock_update_work);
1984         struct kvm *kvm = container_of(ka, struct kvm, arch);
1985         struct kvm_vcpu *vcpu;
1986 
1987         kvm_for_each_vcpu(i, vcpu, kvm) {
1988                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
1989                 kvm_vcpu_kick(vcpu);
1990         }
1991 }
1992 
1993 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
1994 {
1995         struct kvm *kvm = v->kvm;
1996 
1997         kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
1998         schedule_delayed_work(&kvm->arch.kvmclock_update_work,
1999                                         KVMCLOCK_UPDATE_DELAY);
2000 }
2001 
2002 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
2003 
2004 static void kvmclock_sync_fn(struct work_struct *work)
2005 {
2006         struct delayed_work *dwork = to_delayed_work(work);
2007         struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
2008                                            kvmclock_sync_work);
2009         struct kvm *kvm = container_of(ka, struct kvm, arch);
2010 
2011         if (!kvmclock_periodic_sync)
2012                 return;
2013 
2014         schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
2015         schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
2016                                         KVMCLOCK_SYNC_PERIOD);
2017 }
2018 
2019 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2020 {
2021         u64 mcg_cap = vcpu->arch.mcg_cap;
2022         unsigned bank_num = mcg_cap & 0xff;
2023         u32 msr = msr_info->index;
2024         u64 data = msr_info->data;
2025 
2026         switch (msr) {
2027         case MSR_IA32_MCG_STATUS:
2028                 vcpu->arch.mcg_status = data;
2029                 break;
2030         case MSR_IA32_MCG_CTL:
2031                 if (!(mcg_cap & MCG_CTL_P))
2032                         return 1;
2033                 if (data != 0 && data != ~(u64)0)
2034                         return -1;
2035                 vcpu->arch.mcg_ctl = data;
2036                 break;
2037         default:
2038                 if (msr >= MSR_IA32_MC0_CTL &&
2039                     msr < MSR_IA32_MCx_CTL(bank_num)) {
2040                         u32 offset = msr - MSR_IA32_MC0_CTL;
2041                         /* only 0 or all 1s can be written to IA32_MCi_CTL
2042                          * some Linux kernels though clear bit 10 in bank 4 to
2043                          * workaround a BIOS/GART TBL issue on AMD K8s, ignore
2044                          * this to avoid an uncatched #GP in the guest
2045                          */
2046                         if ((offset & 0x3) == 0 &&
2047                             data != 0 && (data | (1 << 10)) != ~(u64)0)
2048                                 return -1;
2049                         if (!msr_info->host_initiated &&
2050                                 (offset & 0x3) == 1 && data != 0)
2051                                 return -1;
2052                         vcpu->arch.mce_banks[offset] = data;
2053                         break;
2054                 }
2055                 return 1;
2056         }
2057         return 0;
2058 }
2059 
2060 static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
2061 {
2062         struct kvm *kvm = vcpu->kvm;
2063         int lm = is_long_mode(vcpu);
2064         u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
2065                 : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
2066         u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
2067                 : kvm->arch.xen_hvm_config.blob_size_32;
2068         u32 page_num = data & ~PAGE_MASK;
2069         u64 page_addr = data & PAGE_MASK;
2070         u8 *page;
2071         int r;
2072 
2073         r = -E2BIG;
2074         if (page_num >= blob_size)
2075                 goto out;
2076         r = -ENOMEM;
2077         page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
2078         if (IS_ERR(page)) {
2079                 r = PTR_ERR(page);
2080                 goto out;
2081         }
2082         if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
2083                 goto out_free;
2084         r = 0;
2085 out_free:
2086         kfree(page);
2087 out:
2088         return r;
2089 }
2090 
2091 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
2092 {
2093         gpa_t gpa = data & ~0x3f;
2094 
2095         /* Bits 3:5 are reserved, Should be zero */
2096         if (data & 0x38)
2097                 return 1;
2098 
2099         vcpu->arch.apf.msr_val = data;
2100 
2101         if (!(data & KVM_ASYNC_PF_ENABLED)) {
2102                 kvm_clear_async_pf_completion_queue(vcpu);
2103                 kvm_async_pf_hash_reset(vcpu);
2104                 return 0;
2105         }
2106 
2107         if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
2108                                         sizeof(u32)))
2109                 return 1;
2110 
2111         vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
2112         vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
2113         kvm_async_pf_wakeup_all(vcpu);
2114         return 0;
2115 }
2116 
2117 static void kvmclock_reset(struct kvm_vcpu *vcpu)
2118 {
2119         vcpu->arch.pv_time_enabled = false;
2120 }
2121 
2122 static void record_steal_time(struct kvm_vcpu *vcpu)
2123 {
2124         if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2125                 return;
2126 
2127         if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2128                 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
2129                 return;
2130 
2131         vcpu->arch.st.steal.preempted = 0;
2132 
2133         if (vcpu->arch.st.steal.version & 1)
2134                 vcpu->arch.st.steal.version += 1;  /* first time write, random junk */
2135 
2136         vcpu->arch.st.steal.version += 1;
2137 
2138         kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2139                 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2140 
2141         smp_wmb();
2142 
2143         vcpu->arch.st.steal.steal += current->sched_info.run_delay -
2144                 vcpu->arch.st.last_steal;
2145         vcpu->arch.st.last_steal = current->sched_info.run_delay;
2146 
2147         kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2148                 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2149 
2150         smp_wmb();
2151 
2152         vcpu->arch.st.steal.version += 1;
2153 
2154         kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
2155                 &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
2156 }
2157 
2158 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2159 {
2160         bool pr = false;
2161         u32 msr = msr_info->index;
2162         u64 data = msr_info->data;
2163 
2164         switch (msr) {
2165         case MSR_AMD64_NB_CFG:
2166         case MSR_IA32_UCODE_REV:
2167         case MSR_IA32_UCODE_WRITE:
2168         case MSR_VM_HSAVE_PA:
2169         case MSR_AMD64_PATCH_LOADER:
2170         case MSR_AMD64_BU_CFG2:
2171         case MSR_AMD64_DC_CFG:
2172                 break;
2173 
2174         case MSR_EFER:
2175                 return set_efer(vcpu, data);
2176         case MSR_K7_HWCR:
2177                 data &= ~(u64)0x40;     /* ignore flush filter disable */
2178                 data &= ~(u64)0x100;    /* ignore ignne emulation enable */
2179                 data &= ~(u64)0x8;      /* ignore TLB cache disable */
2180                 data &= ~(u64)0x40000;  /* ignore Mc status write enable */
2181                 if (data != 0) {
2182                         vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
2183                                     data);
2184                         return 1;
2185                 }
2186                 break;
2187         case MSR_FAM10H_MMIO_CONF_BASE:
2188                 if (data != 0) {
2189                         vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
2190                                     "0x%llx\n", data);
2191                         return 1;
2192                 }
2193                 break;
2194         case MSR_IA32_DEBUGCTLMSR:
2195                 if (!data) {
2196                         /* We support the non-activated case already */
2197                         break;
2198                 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
2199                         /* Values other than LBR and BTF are vendor-specific,
2200                            thus reserved and should throw a #GP */
2201                         return 1;
2202                 }
2203                 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
2204                             __func__, data);
2205                 break;
2206         case 0x200 ... 0x2ff:
2207                 return kvm_mtrr_set_msr(vcpu, msr, data);
2208         case MSR_IA32_APICBASE:
2209                 return kvm_set_apic_base(vcpu, msr_info);
2210         case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2211                 return kvm_x2apic_msr_write(vcpu, msr, data);
2212         case MSR_IA32_TSCDEADLINE:
2213                 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2214                 break;
2215         case MSR_IA32_TSC_ADJUST:
2216                 if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
2217                         if (!msr_info->host_initiated) {
2218                                 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
2219                                 adjust_tsc_offset_guest(vcpu, adj);
2220                         }
2221                         vcpu->arch.ia32_tsc_adjust_msr = data;
2222                 }
2223                 break;
2224         case MSR_IA32_MISC_ENABLE:
2225                 vcpu->arch.ia32_misc_enable_msr = data;
2226                 break;
2227         case MSR_IA32_SMBASE:
2228                 if (!msr_info->host_initiated)
2229                         return 1;
2230                 vcpu->arch.smbase = data;
2231                 break;
2232         case MSR_KVM_WALL_CLOCK_NEW:
2233         case MSR_KVM_WALL_CLOCK:
2234                 vcpu->kvm->arch.wall_clock = data;
2235                 kvm_write_wall_clock(vcpu->kvm, data);
2236                 break;
2237         case MSR_KVM_SYSTEM_TIME_NEW:
2238         case MSR_KVM_SYSTEM_TIME: {
2239                 struct kvm_arch *ka = &vcpu->kvm->arch;
2240 
2241                 kvmclock_reset(vcpu);
2242 
2243                 if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
2244                         bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
2245 
2246                         if (ka->boot_vcpu_runs_old_kvmclock != tmp)
2247                                 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2248 
2249                         ka->boot_vcpu_runs_old_kvmclock = tmp;
2250                 }
2251 
2252                 vcpu->arch.time = data;
2253                 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2254 
2255                 /* we verify if the enable bit is set... */
2256                 if (!(data & 1))
2257                         break;
2258 
2259                 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2260                      &vcpu->arch.pv_time, data & ~1ULL,
2261                      sizeof(struct pvclock_vcpu_time_info)))
2262                         vcpu->arch.pv_time_enabled = false;
2263                 else
2264                         vcpu->arch.pv_time_enabled = true;
2265 
2266                 break;
2267         }
2268         case MSR_KVM_ASYNC_PF_EN:
2269                 if (kvm_pv_enable_async_pf(vcpu, data))
2270                         return 1;
2271                 break;
2272         case MSR_KVM_STEAL_TIME:
2273 
2274                 if (unlikely(!sched_info_on()))
2275                         return 1;
2276 
2277                 if (data & KVM_STEAL_RESERVED_MASK)
2278                         return 1;
2279 
2280                 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
2281                                                 data & KVM_STEAL_VALID_BITS,
2282                                                 sizeof(struct kvm_steal_time)))
2283                         return 1;
2284 
2285                 vcpu->arch.st.msr_val = data;
2286 
2287                 if (!(data & KVM_MSR_ENABLED))
2288                         break;
2289 
2290                 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2291 
2292                 break;
2293         case MSR_KVM_PV_EOI_EN:
2294                 if (kvm_lapic_enable_pv_eoi(vcpu, data))
2295                         return 1;
2296                 break;
2297 
2298         case MSR_IA32_MCG_CTL:
2299         case MSR_IA32_MCG_STATUS:
2300         case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2301                 return set_msr_mce(vcpu, msr_info);
2302 
2303         case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2304         case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2305                 pr = true; /* fall through */
2306         case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2307         case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2308                 if (kvm_pmu_is_valid_msr(vcpu, msr))
2309                         return kvm_pmu_set_msr(vcpu, msr_info);
2310 
2311                 if (pr || data != 0)
2312                         vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
2313                                     "0x%x data 0x%llx\n", msr, data);
2314                 break;
2315         case MSR_K7_CLK_CTL:
2316                 /*
2317                  * Ignore all writes to this no longer documented MSR.
2318                  * Writes are only relevant for old K7 processors,
2319                  * all pre-dating SVM, but a recommended workaround from
2320                  * AMD for these chips. It is possible to specify the
2321                  * affected processor models on the command line, hence
2322                  * the need to ignore the workaround.
2323                  */
2324                 break;
2325         case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2326         case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2327         case HV_X64_MSR_CRASH_CTL:
2328         case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2329                 return kvm_hv_set_msr_common(vcpu, msr, data,
2330                                              msr_info->host_initiated);
2331         case MSR_IA32_BBL_CR_CTL3:
2332                 /* Drop writes to this legacy MSR -- see rdmsr
2333                  * counterpart for further detail.
2334                  */
2335                 if (report_ignored_msrs)
2336                         vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
2337                                 msr, data);
2338                 break;
2339         case MSR_AMD64_OSVW_ID_LENGTH:
2340                 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2341                         return 1;
2342                 vcpu->arch.osvw.length = data;
2343                 break;
2344         case MSR_AMD64_OSVW_STATUS:
2345                 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2346                         return 1;
2347                 vcpu->arch.osvw.status = data;
2348                 break;
2349         case MSR_PLATFORM_INFO:
2350                 if (!msr_info->host_initiated ||
2351                     data & ~MSR_PLATFORM_INFO_CPUID_FAULT ||
2352                     (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
2353                      cpuid_fault_enabled(vcpu)))
2354                         return 1;
2355                 vcpu->arch.msr_platform_info = data;
2356                 break;
2357         case MSR_MISC_FEATURES_ENABLES:
2358                 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
2359                     (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
2360                      !supports_cpuid_fault(vcpu)))
2361                         return 1;
2362                 vcpu->arch.msr_misc_features_enables = data;
2363                 break;
2364         default:
2365                 if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
2366                         return xen_hvm_config(vcpu, data);
2367                 if (kvm_pmu_is_valid_msr(vcpu, msr))
2368                         return kvm_pmu_set_msr(vcpu, msr_info);
2369                 if (!ignore_msrs) {
2370                         vcpu_debug_ratelimited(vcpu, "unhandled wrmsr: 0x%x data 0x%llx\n",
2371                                     msr, data);
2372                         return 1;
2373                 } else {
2374                         if (report_ignored_msrs)
2375                                 vcpu_unimpl(vcpu,
2376                                         "ignored wrmsr: 0x%x data 0x%llx\n",
2377                                         msr, data);
2378                         break;
2379                 }
2380         }
2381         return 0;
2382 }
2383 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
2384 
2385 
2386 /*
2387  * Reads an msr value (of 'msr_index') into 'pdata'.
2388  * Returns 0 on success, non-0 otherwise.
2389  * Assumes vcpu_load() was already called.
2390  */
2391 int kvm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2392 {
2393         return kvm_x86_ops->get_msr(vcpu, msr);
2394 }
2395 EXPORT_SYMBOL_GPL(kvm_get_msr);
2396 
2397 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
2398 {
2399         u64 data;
2400         u64 mcg_cap = vcpu->arch.mcg_cap;
2401         unsigned bank_num = mcg_cap & 0xff;
2402 
2403         switch (msr) {
2404         case MSR_IA32_P5_MC_ADDR:
2405         case MSR_IA32_P5_MC_TYPE:
2406                 data = 0;
2407                 break;
2408         case MSR_IA32_MCG_CAP:
2409                 data = vcpu->arch.mcg_cap;
2410                 break;
2411         case MSR_IA32_MCG_CTL:
2412                 if (!(mcg_cap & MCG_CTL_P))
2413                         return 1;
2414                 data = vcpu->arch.mcg_ctl;
2415                 break;
2416         case MSR_IA32_MCG_STATUS:
2417                 data = vcpu->arch.mcg_status;
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                         data = vcpu->arch.mce_banks[offset];
2424                         break;
2425                 }
2426                 return 1;
2427         }
2428         *pdata = data;
2429         return 0;
2430 }
2431 
2432 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2433 {
2434         switch (msr_info->index) {
2435         case MSR_IA32_PLATFORM_ID:
2436         case MSR_IA32_EBL_CR_POWERON:
2437         case MSR_IA32_DEBUGCTLMSR:
2438         case MSR_IA32_LASTBRANCHFROMIP:
2439         case MSR_IA32_LASTBRANCHTOIP:
2440         case MSR_IA32_LASTINTFROMIP:
2441         case MSR_IA32_LASTINTTOIP:
2442         case MSR_K8_SYSCFG:
2443         case MSR_K8_TSEG_ADDR:
2444         case MSR_K8_TSEG_MASK:
2445         case MSR_K7_HWCR:
2446         case MSR_VM_HSAVE_PA:
2447         case MSR_K8_INT_PENDING_MSG:
2448         case MSR_AMD64_NB_CFG:
2449         case MSR_FAM10H_MMIO_CONF_BASE:
2450         case MSR_AMD64_BU_CFG2:
2451         case MSR_IA32_PERF_CTL:
2452         case MSR_AMD64_DC_CFG:
2453                 msr_info->data = 0;
2454                 break;
2455         case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
2456         case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
2457         case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
2458         case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
2459                 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2460                         return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2461                 msr_info->data = 0;
2462                 break;
2463         case MSR_IA32_UCODE_REV:
2464                 msr_info->data = 0x100000000ULL;
2465                 break;
2466         case MSR_MTRRcap:
2467         case 0x200 ... 0x2ff:
2468                 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
2469         case 0xcd: /* fsb frequency */
2470                 msr_info->data = 3;
2471                 break;
2472                 /*
2473                  * MSR_EBC_FREQUENCY_ID
2474                  * Conservative value valid for even the basic CPU models.
2475                  * Models 0,1: 000 in bits 23:21 indicating a bus speed of
2476                  * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
2477                  * and 266MHz for model 3, or 4. Set Core Clock
2478                  * Frequency to System Bus Frequency Ratio to 1 (bits
2479                  * 31:24) even though these are only valid for CPU
2480                  * models > 2, however guests may end up dividing or
2481                  * multiplying by zero otherwise.
2482                  */
2483         case MSR_EBC_FREQUENCY_ID:
2484                 msr_info->data = 1 << 24;
2485                 break;
2486         case MSR_IA32_APICBASE:
2487                 msr_info->data = kvm_get_apic_base(vcpu);
2488                 break;
2489         case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
2490                 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
2491                 break;
2492         case MSR_IA32_TSCDEADLINE:
2493                 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
2494                 break;
2495         case MSR_IA32_TSC_ADJUST:
2496                 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
2497                 break;
2498         case MSR_IA32_MISC_ENABLE:
2499                 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
2500                 break;
2501         case MSR_IA32_SMBASE:
2502                 if (!msr_info->host_initiated)
2503                         return 1;
2504                 msr_info->data = vcpu->arch.smbase;
2505                 break;
2506         case MSR_IA32_PERF_STATUS:
2507                 /* TSC increment by tick */
2508                 msr_info->data = 1000ULL;
2509                 /* CPU multiplier */
2510                 msr_info->data |= (((uint64_t)4ULL) << 40);
2511                 break;
2512         case MSR_EFER:
2513                 msr_info->data = vcpu->arch.efer;
2514                 break;
2515         case MSR_KVM_WALL_CLOCK:
2516         case MSR_KVM_WALL_CLOCK_NEW:
2517                 msr_info->data = vcpu->kvm->arch.wall_clock;
2518                 break;
2519         case MSR_KVM_SYSTEM_TIME:
2520         case MSR_KVM_SYSTEM_TIME_NEW:
2521                 msr_info->data = vcpu->arch.time;
2522                 break;
2523         case MSR_KVM_ASYNC_PF_EN:
2524                 msr_info->data = vcpu->arch.apf.msr_val;
2525                 break;
2526         case MSR_KVM_STEAL_TIME:
2527                 msr_info->data = vcpu->arch.st.msr_val;
2528                 break;
2529         case MSR_KVM_PV_EOI_EN:
2530                 msr_info->data = vcpu->arch.pv_eoi.msr_val;
2531                 break;
2532         case MSR_IA32_P5_MC_ADDR:
2533         case MSR_IA32_P5_MC_TYPE:
2534         case MSR_IA32_MCG_CAP:
2535         case MSR_IA32_MCG_CTL:
2536         case MSR_IA32_MCG_STATUS:
2537         case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2538                 return get_msr_mce(vcpu, msr_info->index, &msr_info->data);
2539         case MSR_K7_CLK_CTL:
2540                 /*
2541                  * Provide expected ramp-up count for K7. All other
2542                  * are set to zero, indicating minimum divisors for
2543                  * every field.
2544                  *
2545                  * This prevents guest kernels on AMD host with CPU
2546                  * type 6, model 8 and higher from exploding due to
2547                  * the rdmsr failing.
2548                  */
2549                 msr_info->data = 0x20000000;
2550                 break;
2551         case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
2552         case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2553         case HV_X64_MSR_CRASH_CTL:
2554         case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
2555                 return kvm_hv_get_msr_common(vcpu,
2556                                              msr_info->index, &msr_info->data);
2557                 break;
2558         case MSR_IA32_BBL_CR_CTL3:
2559                 /* This legacy MSR exists but isn't fully documented in current
2560                  * silicon.  It is however accessed by winxp in very narrow
2561                  * scenarios where it sets bit #19, itself documented as
2562                  * a "reserved" bit.  Best effort attempt to source coherent
2563                  * read data here should the balance of the register be
2564                  * interpreted by the guest:
2565                  *
2566                  * L2 cache control register 3: 64GB range, 256KB size,
2567                  * enabled, latency 0x1, configured
2568                  */
2569                 msr_info->data = 0xbe702111;
2570                 break;
2571         case MSR_AMD64_OSVW_ID_LENGTH:
2572                 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2573                         return 1;
2574                 msr_info->data = vcpu->arch.osvw.length;
2575                 break;
2576         case MSR_AMD64_OSVW_STATUS:
2577                 if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
2578                         return 1;
2579                 msr_info->data = vcpu->arch.osvw.status;
2580                 break;
2581         case MSR_PLATFORM_INFO:
2582                 msr_info->data = vcpu->arch.msr_platform_info;
2583                 break;
2584         case MSR_MISC_FEATURES_ENABLES:
2585                 msr_info->data = vcpu->arch.msr_misc_features_enables;
2586                 break;
2587         default:
2588                 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
2589                         return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
2590                 if (!ignore_msrs) {
2591                         vcpu_debug_ratelimited(vcpu, "unhandled rdmsr: 0x%x\n",
2592                                                msr_info->index);
2593                         return 1;
2594                 } else {
2595                         if (report_ignored_msrs)
2596                                 vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n",
2597                                         msr_info->index);
2598                         msr_info->data = 0;
2599                 }
2600                 break;
2601         }
2602         return 0;
2603 }
2604 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
2605 
2606 /*
2607  * Read or write a bunch of msrs. All parameters are kernel addresses.
2608  *
2609  * @return number of msrs set successfully.
2610  */
2611 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
2612                     struct kvm_msr_entry *entries,
2613                     int (*do_msr)(struct kvm_vcpu *vcpu,
2614                                   unsigned index, u64 *data))
2615 {
2616         int i, idx;
2617 
2618         idx = srcu_read_lock(&vcpu->kvm->srcu);
2619         for (i = 0; i < msrs->nmsrs; ++i)
2620                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
2621                         break;
2622         srcu_read_unlock(&vcpu->kvm->srcu, idx);
2623 
2624         return i;
2625 }
2626 
2627 /*
2628  * Read or write a bunch of msrs. Parameters are user addresses.
2629  *
2630  * @return number of msrs set successfully.
2631  */
2632 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
2633                   int (*do_msr)(struct kvm_vcpu *vcpu,
2634                                 unsigned index, u64 *data),
2635                   int writeback)
2636 {
2637         struct kvm_msrs msrs;
2638         struct kvm_msr_entry *entries;
2639         int r, n;
2640         unsigned size;
2641 
2642         r = -EFAULT;
2643         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
2644                 goto out;
2645 
2646         r = -E2BIG;
2647         if (msrs.nmsrs >= MAX_IO_MSRS)
2648                 goto out;
2649 
2650         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
2651         entries = memdup_user(user_msrs->entries, size);
2652         if (IS_ERR(entries)) {
2653                 r = PTR_ERR(entries);
2654                 goto out;
2655         }
2656 
2657         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
2658         if (r < 0)
2659                 goto out_free;
2660 
2661         r = -EFAULT;
2662         if (writeback && copy_to_user(user_msrs->entries, entries, size))
2663                 goto out_free;
2664 
2665         r = n;
2666 
2667 out_free:
2668         kfree(entries);
2669 out:
2670         return r;
2671 }
2672 
2673 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
2674 {
2675         int r;
2676 
2677         switch (ext) {
2678         case KVM_CAP_IRQCHIP:
2679         case KVM_CAP_HLT:
2680         case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
2681         case KVM_CAP_SET_TSS_ADDR:
2682         case KVM_CAP_EXT_CPUID:
2683         case KVM_CAP_EXT_EMUL_CPUID:
2684         case KVM_CAP_CLOCKSOURCE:
2685         case KVM_CAP_PIT:
2686         case KVM_CAP_NOP_IO_DELAY:
2687         case KVM_CAP_MP_STATE:
2688         case KVM_CAP_SYNC_MMU:
2689         case KVM_CAP_USER_NMI:
2690         case KVM_CAP_REINJECT_CONTROL:
2691         case KVM_CAP_IRQ_INJECT_STATUS:
2692         case KVM_CAP_IOEVENTFD:
2693         case KVM_CAP_IOEVENTFD_NO_LENGTH:
2694         case KVM_CAP_PIT2:
2695         case KVM_CAP_PIT_STATE2:
2696         case KVM_CAP_SET_IDENTITY_MAP_ADDR:
2697         case KVM_CAP_XEN_HVM:
2698         case KVM_CAP_VCPU_EVENTS:
2699         case KVM_CAP_HYPERV:
2700         case KVM_CAP_HYPERV_VAPIC:
2701         case KVM_CAP_HYPERV_SPIN:
2702         case KVM_CAP_HYPERV_SYNIC:
2703         case KVM_CAP_HYPERV_SYNIC2:
2704         case KVM_CAP_HYPERV_VP_INDEX:
2705         case KVM_CAP_PCI_SEGMENT:
2706         case KVM_CAP_DEBUGREGS:
2707         case KVM_CAP_X86_ROBUST_SINGLESTEP:
2708         case KVM_CAP_XSAVE:
2709         case KVM_CAP_ASYNC_PF:
2710         case KVM_CAP_GET_TSC_KHZ:
2711         case KVM_CAP_KVMCLOCK_CTRL:
2712         case KVM_CAP_READONLY_MEM:
2713         case KVM_CAP_HYPERV_TIME:
2714         case KVM_CAP_IOAPIC_POLARITY_IGNORED:
2715         case KVM_CAP_TSC_DEADLINE_TIMER:
2716         case KVM_CAP_ENABLE_CAP_VM:
2717         case KVM_CAP_DISABLE_QUIRKS:
2718         case KVM_CAP_SET_BOOT_CPU_ID:
2719         case KVM_CAP_SPLIT_IRQCHIP:
2720         case KVM_CAP_IMMEDIATE_EXIT:
2721                 r = 1;
2722                 break;
2723         case KVM_CAP_ADJUST_CLOCK:
2724                 r = KVM_CLOCK_TSC_STABLE;
2725                 break;
2726         case KVM_CAP_X86_GUEST_MWAIT:
2727                 r = kvm_mwait_in_guest();
2728                 break;
2729         case KVM_CAP_X86_SMM:
2730                 /* SMBASE is usually relocated above 1M on modern chipsets,
2731                  * and SMM handlers might indeed rely on 4G segment limits,
2732                  * so do not report SMM to be available if real mode is
2733                  * emulated via vm86 mode.  Still, do not go to great lengths
2734                  * to avoid userspace's usage of the feature, because it is a
2735                  * fringe case that is not enabled except via specific settings
2736                  * of the module parameters.
2737                  */
2738                 r = kvm_x86_ops->cpu_has_high_real_mode_segbase();
2739                 break;
2740         case KVM_CAP_VAPIC:
2741                 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
2742                 break;
2743         case KVM_CAP_NR_VCPUS:
2744                 r = KVM_SOFT_MAX_VCPUS;
2745                 break;
2746         case KVM_CAP_MAX_VCPUS:
2747                 r = KVM_MAX_VCPUS;
2748                 break;
2749         case KVM_CAP_NR_MEMSLOTS:
2750                 r = KVM_USER_MEM_SLOTS;
2751                 break;
2752         case KVM_CAP_PV_MMU:    /* obsolete */
2753                 r = 0;
2754                 break;
2755         case KVM_CAP_MCE:
2756                 r = KVM_MAX_MCE_BANKS;
2757                 break;
2758         case KVM_CAP_XCRS:
2759                 r = boot_cpu_has(X86_FEATURE_XSAVE);
2760                 break;
2761         case KVM_CAP_TSC_CONTROL:
2762                 r = kvm_has_tsc_control;
2763                 break;
2764         case KVM_CAP_X2APIC_API:
2765                 r = KVM_X2APIC_API_VALID_FLAGS;
2766                 break;
2767         default:
2768                 r = 0;
2769                 break;
2770         }
2771         return r;
2772 
2773 }
2774 
2775 long kvm_arch_dev_ioctl(struct file *filp,
2776                         unsigned int ioctl, unsigned long arg)
2777 {
2778         void __user *argp = (void __user *)arg;
2779         long r;
2780 
2781         switch (ioctl) {
2782         case KVM_GET_MSR_INDEX_LIST: {
2783                 struct kvm_msr_list __user *user_msr_list = argp;
2784                 struct kvm_msr_list msr_list;
2785                 unsigned n;
2786 
2787                 r = -EFAULT;
2788                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
2789                         goto out;
2790                 n = msr_list.nmsrs;
2791                 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
2792                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
2793                         goto out;
2794                 r = -E2BIG;
2795                 if (n < msr_list.nmsrs)
2796                         goto out;
2797                 r = -EFAULT;
2798                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
2799                                  num_msrs_to_save * sizeof(u32)))
2800                         goto out;
2801                 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
2802                                  &emulated_msrs,
2803                                  num_emulated_msrs * sizeof(u32)))
2804                         goto out;
2805                 r = 0;
2806                 break;
2807         }
2808         case KVM_GET_SUPPORTED_CPUID:
2809         case KVM_GET_EMULATED_CPUID: {
2810                 struct kvm_cpuid2 __user *cpuid_arg = argp;
2811                 struct kvm_cpuid2 cpuid;
2812 
2813                 r = -EFAULT;
2814                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
2815                         goto out;
2816 
2817                 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
2818                                             ioctl);
2819                 if (r)
2820                         goto out;
2821 
2822                 r = -EFAULT;
2823                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
2824                         goto out;
2825                 r = 0;
2826                 break;
2827         }
2828         case KVM_X86_GET_MCE_CAP_SUPPORTED: {
2829                 r = -EFAULT;
2830                 if (copy_to_user(argp, &kvm_mce_cap_supported,
2831                                  sizeof(kvm_mce_cap_supported)))
2832                         goto out;
2833                 r = 0;
2834                 break;
2835         }
2836         default:
2837                 r = -EINVAL;
2838         }
2839 out:
2840         return r;
2841 }
2842 
2843 static void wbinvd_ipi(void *garbage)
2844 {
2845         wbinvd();
2846 }
2847 
2848 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
2849 {
2850         return kvm_arch_has_noncoherent_dma(vcpu->kvm);
2851 }
2852 
2853 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2854 {
2855         /* Address WBINVD may be executed by guest */
2856         if (need_emulate_wbinvd(vcpu)) {
2857                 if (kvm_x86_ops->has_wbinvd_exit())
2858                         cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
2859                 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
2860                         smp_call_function_single(vcpu->cpu,
2861                                         wbinvd_ipi, NULL, 1);
2862         }
2863 
2864         kvm_x86_ops->vcpu_load(vcpu, cpu);
2865 
2866         /* Apply any externally detected TSC adjustments (due to suspend) */
2867         if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
2868                 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
2869                 vcpu->arch.tsc_offset_adjustment = 0;
2870                 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
2871         }
2872 
2873         if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
2874                 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
2875                                 rdtsc() - vcpu->arch.last_host_tsc;
2876                 if (tsc_delta < 0)
2877                         mark_tsc_unstable("KVM discovered backwards TSC");
2878 
2879                 if (check_tsc_unstable()) {
2880                         u64 offset = kvm_compute_tsc_offset(vcpu,
2881                                                 vcpu->arch.last_guest_tsc);
2882                         kvm_vcpu_write_tsc_offset(vcpu, offset);
2883                         vcpu->arch.tsc_catchup = 1;
2884                 }
2885 
2886                 if (kvm_lapic_hv_timer_in_use(vcpu))
2887                         kvm_lapic_restart_hv_timer(vcpu);
2888 
2889                 /*
2890                  * On a host with synchronized TSC, there is no need to update
2891                  * kvmclock on vcpu->cpu migration
2892                  */
2893                 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
2894                         kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2895                 if (vcpu->cpu != cpu)
2896                         kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
2897                 vcpu->cpu = cpu;
2898         }
2899 
2900         kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
2901 }
2902 
2903 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
2904 {
2905         if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
2906                 return;
2907 
2908         vcpu->arch.st.steal.preempted = 1;
2909 
2910         kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.st.stime,
2911                         &vcpu->arch.st.steal.preempted,
2912                         offsetof(struct kvm_steal_time, preempted),
2913                         sizeof(vcpu->arch.st.steal.preempted));
2914 }
2915 
2916 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
2917 {
2918         int idx;
2919 
2920         if (vcpu->preempted)
2921                 vcpu->arch.preempted_in_kernel = !kvm_x86_ops->get_cpl(vcpu);
2922 
2923         /*
2924          * Disable page faults because we're in atomic context here.
2925          * kvm_write_guest_offset_cached() would call might_fault()
2926          * that relies on pagefault_disable() to tell if there's a
2927          * bug. NOTE: the write to guest memory may not go through if
2928          * during postcopy live migration or if there's heavy guest
2929          * paging.
2930          */
2931         pagefault_disable();
2932         /*
2933          * kvm_memslots() will be called by
2934          * kvm_write_guest_offset_cached() so take the srcu lock.
2935          */
2936         idx = srcu_read_lock(&vcpu->kvm->srcu);
2937         kvm_steal_time_set_preempted(vcpu);
2938         srcu_read_unlock(&vcpu->kvm->srcu, idx);
2939         pagefault_enable();
2940         kvm_x86_ops->vcpu_put(vcpu);
2941         vcpu->arch.last_host_tsc = rdtsc();
2942         /*
2943          * If userspace has set any breakpoints or watchpoints, dr6 is restored
2944          * on every vmexit, but if not, we might have a stale dr6 from the
2945          * guest. do_debug expects dr6 to be cleared after it runs, do the same.
2946          */
2947         set_debugreg(0, 6);
2948 }
2949 
2950 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
2951                                     struct kvm_lapic_state *s)
2952 {
2953         if (kvm_x86_ops->sync_pir_to_irr && vcpu->arch.apicv_active)
2954                 kvm_x86_ops->sync_pir_to_irr(vcpu);
2955 
2956         return kvm_apic_get_state(vcpu, s);
2957 }
2958 
2959 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
2960                                     struct kvm_lapic_state *s)
2961 {
2962         int r;
2963 
2964         r = kvm_apic_set_state(vcpu, s);
2965         if (r)
2966                 return r;
2967         update_cr8_intercept(vcpu);
2968 
2969         return 0;
2970 }
2971 
2972 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
2973 {
2974         return (!lapic_in_kernel(vcpu) ||
2975                 kvm_apic_accept_pic_intr(vcpu));
2976 }
2977 
2978 /*
2979  * if userspace requested an interrupt window, check that the
2980  * interrupt window is open.
2981  *
2982  * No need to exit to userspace if we already have an interrupt queued.
2983  */
2984 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
2985 {
2986         return kvm_arch_interrupt_allowed(vcpu) &&
2987                 !kvm_cpu_has_interrupt(vcpu) &&
2988                 !kvm_event_needs_reinjection(vcpu) &&
2989                 kvm_cpu_accept_dm_intr(vcpu);
2990 }
2991 
2992 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
2993                                     struct kvm_interrupt *irq)
2994 {
2995         if (irq->irq >= KVM_NR_INTERRUPTS)
2996                 return -EINVAL;
2997 
2998         if (!irqchip_in_kernel(vcpu->kvm)) {
2999                 kvm_queue_interrupt(vcpu, irq->irq, false);
3000                 kvm_make_request(KVM_REQ_EVENT, vcpu);
3001                 return 0;
3002         }
3003 
3004         /*
3005          * With in-kernel LAPIC, we only use this to inject EXTINT, so
3006          * fail for in-kernel 8259.
3007          */
3008         if (pic_in_kernel(vcpu->kvm))
3009                 return -ENXIO;
3010 
3011         if (vcpu->arch.pending_external_vector != -1)
3012                 return -EEXIST;
3013 
3014         vcpu->arch.pending_external_vector = irq->irq;
3015         kvm_make_request(KVM_REQ_EVENT, vcpu);
3016         return 0;
3017 }
3018 
3019 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
3020 {
3021         kvm_inject_nmi(vcpu);
3022 
3023         return 0;
3024 }
3025 
3026 static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
3027 {
3028         kvm_make_request(KVM_REQ_SMI, vcpu);
3029 
3030         return 0;
3031 }
3032 
3033 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
3034                                            struct kvm_tpr_access_ctl *tac)
3035 {
3036         if (tac->flags)
3037                 return -EINVAL;
3038         vcpu->arch.tpr_access_reporting = !!tac->enabled;
3039         return 0;
3040 }
3041 
3042 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
3043                                         u64 mcg_cap)
3044 {
3045         int r;
3046         unsigned bank_num = mcg_cap & 0xff, bank;
3047 
3048         r = -EINVAL;
3049         if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
3050                 goto out;
3051         if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
3052                 goto out;
3053         r = 0;
3054         vcpu->arch.mcg_cap = mcg_cap;
3055         /* Init IA32_MCG_CTL to all 1s */
3056         if (mcg_cap & MCG_CTL_P)
3057                 vcpu->arch.mcg_ctl = ~(u64)0;
3058         /* Init IA32_MCi_CTL to all 1s */
3059         for (bank = 0; bank < bank_num; bank++)
3060                 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
3061 
3062         if (kvm_x86_ops->setup_mce)
3063                 kvm_x86_ops->setup_mce(vcpu);
3064 out:
3065         return r;
3066 }
3067 
3068 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
3069                                       struct kvm_x86_mce *mce)
3070 {
3071         u64 mcg_cap = vcpu->arch.mcg_cap;
3072         unsigned bank_num = mcg_cap & 0xff;
3073         u64 *banks = vcpu->arch.mce_banks;
3074 
3075         if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
3076                 return -EINVAL;
3077         /*
3078          * if IA32_MCG_CTL is not all 1s, the uncorrected error
3079          * reporting is disabled
3080          */
3081         if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
3082             vcpu->arch.mcg_ctl != ~(u64)0)
3083                 return 0;
3084         banks += 4 * mce->bank;
3085         /*
3086          * if IA32_MCi_CTL is not all 1s, the uncorrected error
3087          * reporting is disabled for the bank
3088          */
3089         if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
3090                 return 0;
3091         if (mce->status & MCI_STATUS_UC) {
3092                 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
3093                     !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
3094                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3095                         return 0;
3096                 }
3097                 if (banks[1] & MCI_STATUS_VAL)
3098                         mce->status |= MCI_STATUS_OVER;
3099                 banks[2] = mce->addr;
3100                 banks[3] = mce->misc;
3101                 vcpu->arch.mcg_status = mce->mcg_status;
3102                 banks[1] = mce->status;
3103                 kvm_queue_exception(vcpu, MC_VECTOR);
3104         } else if (!(banks[1] & MCI_STATUS_VAL)
3105                    || !(banks[1] & MCI_STATUS_UC)) {
3106                 if (banks[1] & MCI_STATUS_VAL)
3107                         mce->status |= MCI_STATUS_OVER;
3108                 banks[2] = mce->addr;
3109                 banks[3] = mce->misc;
3110                 banks[1] = mce->status;
3111         } else
3112                 banks[1] |= MCI_STATUS_OVER;
3113         return 0;
3114 }
3115 
3116 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
3117                                                struct kvm_vcpu_events *events)
3118 {
3119         process_nmi(vcpu);
3120         /*
3121          * FIXME: pass injected and pending separately.  This is only
3122          * needed for nested virtualization, whose state cannot be
3123          * migrated yet.  For now we can combine them.
3124          */
3125         events->exception.injected =
3126                 (vcpu->arch.exception.pending ||
3127                  vcpu->arch.exception.injected) &&
3128                 !kvm_exception_is_soft(vcpu->arch.exception.nr);
3129         events->exception.nr = vcpu->arch.exception.nr;
3130         events->exception.has_error_code = vcpu->arch.exception.has_error_code;
3131         events->exception.pad = 0;
3132         events->exception.error_code = vcpu->arch.exception.error_code;
3133 
3134         events->interrupt.injected =
3135                 vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
3136         events->interrupt.nr = vcpu->arch.interrupt.nr;
3137         events->interrupt.soft = 0;
3138         events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
3139 
3140         events->nmi.injected = vcpu->arch.nmi_injected;
3141         events->nmi.pending = vcpu->arch.nmi_pending != 0;
3142         events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
3143         events->nmi.pad = 0;
3144 
3145         events->sipi_vector = 0; /* never valid when reporting to user space */
3146 
3147         events->smi.smm = is_smm(vcpu);
3148         events->smi.pending = vcpu->arch.smi_pending;
3149         events->smi.smm_inside_nmi =
3150                 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
3151         events->smi.latched_init = kvm_lapic_latched_init(vcpu);
3152 
3153         events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
3154                          | KVM_VCPUEVENT_VALID_SHADOW
3155                          | KVM_VCPUEVENT_VALID_SMM);
3156         memset(&events->reserved, 0, sizeof(events->reserved));
3157 }
3158 
3159 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags);
3160 
3161 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
3162                                               struct kvm_vcpu_events *events)
3163 {
3164         if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
3165                               | KVM_VCPUEVENT_VALID_SIPI_VECTOR
3166                               | KVM_VCPUEVENT_VALID_SHADOW
3167                               | KVM_VCPUEVENT_VALID_SMM))
3168                 return -EINVAL;
3169 
3170         if (events->exception.injected &&
3171             (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR ||
3172              is_guest_mode(vcpu)))
3173                 return -EINVAL;
3174 
3175         /* INITs are latched while in SMM */
3176         if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
3177             (events->smi.smm || events->smi.pending) &&
3178             vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
3179                 return -EINVAL;
3180 
3181         process_nmi(vcpu);
3182         vcpu->arch.exception.injected = false;
3183         vcpu->arch.exception.pending = events->exception.injected;
3184         vcpu->arch.exception.nr = events->exception.nr;
3185         vcpu->arch.exception.has_error_code = events->exception.has_error_code;
3186         vcpu->arch.exception.error_code = events->exception.error_code;
3187 
3188         vcpu->arch.interrupt.pending = events->interrupt.injected;
3189         vcpu->arch.interrupt.nr = events->interrupt.nr;
3190         vcpu->arch.interrupt.soft = events->interrupt.soft;
3191         if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
3192                 kvm_x86_ops->set_interrupt_shadow(vcpu,
3193                                                   events->interrupt.shadow);
3194 
3195         vcpu->arch.nmi_injected = events->nmi.injected;
3196         if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
3197                 vcpu->arch.nmi_pending = events->nmi.pending;
3198         kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
3199 
3200         if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
3201             lapic_in_kernel(vcpu))
3202                 vcpu->arch.apic->sipi_vector = events->sipi_vector;
3203 
3204         if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
3205                 u32 hflags = vcpu->arch.hflags;
3206                 if (events->smi.smm)
3207                         hflags |= HF_SMM_MASK;
3208                 else
3209                         hflags &= ~HF_SMM_MASK;
3210                 kvm_set_hflags(vcpu, hflags);
3211 
3212                 vcpu->arch.smi_pending = events->smi.pending;
3213 
3214                 if (events->smi.smm) {
3215                         if (events->smi.smm_inside_nmi)
3216                                 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
3217                         else
3218                                 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
3219                         if (lapic_in_kernel(vcpu)) {
3220                                 if (events->smi.latched_init)
3221                                         set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3222                                 else
3223                                         clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
3224                         }
3225                 }
3226         }
3227 
3228         kvm_make_request(KVM_REQ_EVENT, vcpu);
3229 
3230         return 0;
3231 }
3232 
3233 static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
3234                                              struct kvm_debugregs *dbgregs)
3235 {
3236         unsigned long val;
3237 
3238         memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
3239         kvm_get_dr(vcpu, 6, &val);
3240         dbgregs->dr6 = val;
3241         dbgregs->dr7 = vcpu->arch.dr7;
3242         dbgregs->flags = 0;
3243         memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
3244 }
3245 
3246 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
3247                                             struct kvm_debugregs *dbgregs)
3248 {
3249         if (dbgregs->flags)
3250                 return -EINVAL;
3251 
3252         if (dbgregs->dr6 & ~0xffffffffull)
3253                 return -EINVAL;
3254         if (dbgregs->dr7 & ~0xffffffffull)
3255                 return -EINVAL;
3256 
3257         memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
3258         kvm_update_dr0123(vcpu);
3259         vcpu->arch.dr6 = dbgregs->dr6;
3260         kvm_update_dr6(vcpu);
3261         vcpu->arch.dr7 = dbgregs->dr7;
3262         kvm_update_dr7(vcpu);
3263 
3264         return 0;
3265 }
3266 
3267 #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
3268 
3269 static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
3270 {
3271         struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3272         u64 xstate_bv = xsave->header.xfeatures;
3273         u64 valid;
3274 
3275         /*
3276          * Copy legacy XSAVE area, to avoid complications with CPUID
3277          * leaves 0 and 1 in the loop below.
3278          */
3279         memcpy(dest, xsave, XSAVE_HDR_OFFSET);
3280 
3281         /* Set XSTATE_BV */
3282         xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
3283         *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
3284 
3285         /*
3286          * Copy each region from the possibly compacted offset to the
3287          * non-compacted offset.
3288          */
3289         valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3290         while (valid) {
3291                 u64 feature = valid & -valid;
3292                 int index = fls64(feature) - 1;
3293                 void *src = get_xsave_addr(xsave, feature);
3294 
3295                 if (src) {
3296                         u32 size, offset, ecx, edx;
3297                         cpuid_count(XSTATE_CPUID, index,
3298                                     &size, &offset, &ecx, &edx);
3299                         if (feature == XFEATURE_MASK_PKRU)
3300                                 memcpy(dest + offset, &vcpu->arch.pkru,
3301                                        sizeof(vcpu->arch.pkru));
3302                         else
3303                                 memcpy(dest + offset, src, size);
3304 
3305                 }
3306 
3307                 valid -= feature;
3308         }
3309 }
3310 
3311 static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
3312 {
3313         struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
3314         u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
3315         u64 valid;
3316 
3317         /*
3318          * Copy legacy XSAVE area, to avoid complications with CPUID
3319          * leaves 0 and 1 in the loop below.
3320          */
3321         memcpy(xsave, src, XSAVE_HDR_OFFSET);
3322 
3323         /* Set XSTATE_BV and possibly XCOMP_BV.  */
3324         xsave->header.xfeatures = xstate_bv;
3325         if (boot_cpu_has(X86_FEATURE_XSAVES))
3326                 xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
3327 
3328         /*
3329          * Copy each region from the non-compacted offset to the
3330          * possibly compacted offset.
3331          */
3332         valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
3333         while (valid) {
3334                 u64 feature = valid & -valid;
3335                 int index = fls64(feature) - 1;
3336                 void *dest = get_xsave_addr(xsave, feature);
3337 
3338                 if (dest) {
3339                         u32 size, offset, ecx, edx;
3340                         cpuid_count(XSTATE_CPUID, index,
3341                                     &size, &offset, &ecx, &edx);
3342                         if (feature == XFEATURE_MASK_PKRU)
3343                                 memcpy(&vcpu->arch.pkru, src + offset,
3344                                        sizeof(vcpu->arch.pkru));
3345                         else
3346                                 memcpy(dest, src + offset, size);
3347                 }
3348 
3349                 valid -= feature;
3350         }
3351 }
3352 
3353 static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
3354                                          struct kvm_xsave *guest_xsave)
3355 {
3356         if (boot_cpu_has(X86_FEATURE_XSAVE)) {
3357                 memset(guest_xsave, 0, sizeof(struct kvm_xsave));
3358                 fill_xsave((u8 *) guest_xsave->region, vcpu);
3359         } else {
3360                 memcpy(guest_xsave->region,
3361                         &vcpu->arch.guest_fpu.state.fxsave,
3362                         sizeof(struct fxregs_state));
3363                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
3364                         XFEATURE_MASK_FPSSE;
3365         }
3366 }
3367 
3368 #define XSAVE_MXCSR_OFFSET 24
3369 
3370 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
3371                                         struct kvm_xsave *guest_xsave)
3372 {
3373         u64 xstate_bv =
3374                 *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
3375         u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
3376 
3377         if (boot_cpu_has(X86_FEATURE_XSAVE)) {
3378                 /*
3379                  * Here we allow setting states that are not present in
3380                  * CPUID leaf 0xD, index 0, EDX:EAX.  This is for compatibility
3381                  * with old userspace.
3382                  */
3383                 if (xstate_bv & ~kvm_supported_xcr0() ||
3384                         mxcsr & ~mxcsr_feature_mask)
3385                         return -EINVAL;
3386                 load_xsave(vcpu, (u8 *)guest_xsave->region);
3387         } else {
3388                 if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
3389                         mxcsr & ~mxcsr_feature_mask)
3390                         return -EINVAL;
3391                 memcpy(&vcpu->arch.guest_fpu.state.fxsave,
3392                         guest_xsave->region, sizeof(struct fxregs_state));
3393         }
3394         return 0;
3395 }
3396 
3397 static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
3398                                         struct kvm_xcrs *guest_xcrs)
3399 {
3400         if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
3401                 guest_xcrs->nr_xcrs = 0;
3402                 return;
3403         }
3404 
3405         guest_xcrs->nr_xcrs = 1;
3406         guest_xcrs->flags = 0;
3407         guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
3408         guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
3409 }
3410 
3411 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
3412                                        struct kvm_xcrs *guest_xcrs)
3413 {
3414         int i, r = 0;
3415 
3416         if (!boot_cpu_has(X86_FEATURE_XSAVE))
3417                 return -EINVAL;
3418 
3419         if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
3420                 return -EINVAL;
3421 
3422         for (i = 0; i < guest_xcrs->nr_xcrs; i++)
3423                 /* Only support XCR0 currently */
3424                 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
3425                         r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
3426                                 guest_xcrs->xcrs[i].value);
3427                         break;
3428                 }
3429         if (r)
3430                 r = -EINVAL;
3431         return r;
3432 }
3433 
3434 /*
3435  * kvm_set_guest_paused() indicates to the guest kernel that it has been
3436  * stopped by the hypervisor.  This function will be called from the host only.
3437  * EINVAL is returned when the host attempts to set the flag for a guest that
3438  * does not support pv clocks.
3439  */
3440 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
3441 {
3442         if (!vcpu->arch.pv_time_enabled)
3443                 return -EINVAL;
3444         vcpu->arch.pvclock_set_guest_stopped_request = true;
3445         kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3446         return 0;
3447 }
3448 
3449 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
3450                                      struct kvm_enable_cap *cap)
3451 {
3452         if (cap->flags)
3453                 return -EINVAL;
3454 
3455         switch (cap->cap) {
3456         case KVM_CAP_HYPERV_SYNIC2:
3457                 if (cap->args[0])
3458                         return -EINVAL;
3459         case KVM_CAP_HYPERV_SYNIC:
3460                 if (!irqchip_in_kernel(vcpu->kvm))
3461                         return -EINVAL;
3462                 return kvm_hv_activate_synic(vcpu, cap->cap ==
3463                                              KVM_CAP_HYPERV_SYNIC2);
3464         default:
3465                 return -EINVAL;
3466         }
3467 }
3468 
3469 long kvm_arch_vcpu_ioctl(struct file *filp,
3470                          unsigned int ioctl, unsigned long arg)
3471 {
3472         struct kvm_vcpu *vcpu = filp->private_data;
3473         void __user *argp = (void __user *)arg;
3474         int r;
3475         union {
3476                 struct kvm_lapic_state *lapic;
3477                 struct kvm_xsave *xsave;
3478                 struct kvm_xcrs *xcrs;
3479                 void *buffer;
3480         } u;
3481 
3482         u.buffer = NULL;
3483         switch (ioctl) {
3484         case KVM_GET_LAPIC: {
3485                 r = -EINVAL;
3486                 if (!lapic_in_kernel(vcpu))
3487                         goto out;
3488                 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
3489 
3490                 r = -ENOMEM;
3491                 if (!u.lapic)
3492                         goto out;
3493                 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
3494                 if (r)
3495                         goto out;
3496                 r = -EFAULT;
3497                 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
3498                         goto out;
3499                 r = 0;
3500                 break;
3501         }
3502         case KVM_SET_LAPIC: {
3503                 r = -EINVAL;
3504                 if (!lapic_in_kernel(vcpu))
3505                         goto out;
3506                 u.lapic = memdup_user(argp, sizeof(*u.lapic));
3507                 if (IS_ERR(u.lapic))
3508                         return PTR_ERR(u.lapic);
3509 
3510                 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
3511                 break;
3512         }
3513         case KVM_INTERRUPT: {
3514                 struct kvm_interrupt irq;
3515 
3516                 r = -EFAULT;
3517                 if (copy_from_user(&irq, argp, sizeof irq))
3518                         goto out;
3519                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
3520                 break;
3521         }
3522         case KVM_NMI: {
3523                 r = kvm_vcpu_ioctl_nmi(vcpu);
3524                 break;
3525         }
3526         case KVM_SMI: {
3527                 r = kvm_vcpu_ioctl_smi(vcpu);
3528                 break;
3529         }
3530         case KVM_SET_CPUID: {
3531                 struct kvm_cpuid __user *cpuid_arg = argp;
3532                 struct kvm_cpuid cpuid;
3533 
3534                 r = -EFAULT;
3535                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3536                         goto out;
3537                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
3538                 break;
3539         }
3540         case KVM_SET_CPUID2: {
3541                 struct kvm_cpuid2 __user *cpuid_arg = argp;
3542                 struct kvm_cpuid2 cpuid;
3543 
3544                 r = -EFAULT;
3545                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3546                         goto out;
3547                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
3548                                               cpuid_arg->entries);
3549                 break;
3550         }
3551         case KVM_GET_CPUID2: {
3552                 struct kvm_cpuid2 __user *cpuid_arg = argp;
3553                 struct kvm_cpuid2 cpuid;
3554 
3555                 r = -EFAULT;
3556                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
3557                         goto out;
3558                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
3559                                               cpuid_arg->entries);
3560                 if (r)
3561                         goto out;
3562                 r = -EFAULT;
3563                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
3564                         goto out;
3565                 r = 0;
3566                 break;
3567         }
3568         case KVM_GET_MSRS:
3569                 r = msr_io(vcpu, argp, do_get_msr, 1);
3570                 break;
3571         case KVM_SET_MSRS:
3572                 r = msr_io(vcpu, argp, do_set_msr, 0);
3573                 break;
3574         case KVM_TPR_ACCESS_REPORTING: {
3575                 struct kvm_tpr_access_ctl tac;
3576 
3577                 r = -EFAULT;
3578                 if (copy_from_user(&tac, argp, sizeof tac))
3579                         goto out;
3580                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
3581                 if (r)
3582                         goto out;
3583                 r = -EFAULT;
3584                 if (copy_to_user(argp, &tac, sizeof tac))
3585                         goto out;
3586                 r = 0;
3587                 break;
3588         };
3589         case KVM_SET_VAPIC_ADDR: {
3590                 struct kvm_vapic_addr va;
3591                 int idx;
3592 
3593                 r = -EINVAL;
3594                 if (!lapic_in_kernel(vcpu))
3595                         goto out;
3596                 r = -EFAULT;
3597                 if (copy_from_user(&va, argp, sizeof va))
3598                         goto out;
3599                 idx = srcu_read_lock(&vcpu->kvm->srcu);
3600                 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
3601                 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3602                 break;
3603         }
3604         case KVM_X86_SETUP_MCE: {
3605                 u64 mcg_cap;
3606 
3607                 r = -EFAULT;
3608                 if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
3609                         goto out;
3610                 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
3611                 break;
3612         }
3613         case KVM_X86_SET_MCE: {
3614                 struct kvm_x86_mce mce;
3615 
3616                 r = -EFAULT;
3617                 if (copy_from_user(&mce, argp, sizeof mce))
3618                         goto out;
3619                 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
3620                 break;
3621         }
3622         case KVM_GET_VCPU_EVENTS: {
3623                 struct kvm_vcpu_events events;
3624 
3625                 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
3626 
3627                 r = -EFAULT;
3628                 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
3629                         break;
3630                 r = 0;
3631                 break;
3632         }
3633         case KVM_SET_VCPU_EVENTS: {
3634                 struct kvm_vcpu_events events;
3635 
3636                 r = -EFAULT;
3637                 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
3638                         break;
3639 
3640                 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
3641                 break;
3642         }
3643         case KVM_GET_DEBUGREGS: {
3644                 struct kvm_debugregs dbgregs;
3645 
3646                 kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
3647 
3648                 r = -EFAULT;
3649                 if (copy_to_user(argp, &dbgregs,
3650                                  sizeof(struct kvm_debugregs)))
3651                         break;
3652                 r = 0;
3653                 break;
3654         }
3655         case KVM_SET_DEBUGREGS: {
3656                 struct kvm_debugregs dbgregs;
3657 
3658                 r = -EFAULT;
3659                 if (copy_from_user(&dbgregs, argp,
3660                                    sizeof(struct kvm_debugregs)))
3661                         break;
3662 
3663                 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
3664                 break;
3665         }
3666         case KVM_GET_XSAVE: {
3667                 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
3668                 r = -ENOMEM;
3669                 if (!u.xsave)
3670                         break;
3671 
3672                 kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
3673 
3674                 r = -EFAULT;
3675                 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
3676                         break;
3677                 r = 0;
3678                 break;
3679         }
3680         case KVM_SET_XSAVE: {
3681                 u.xsave = memdup_user(argp, sizeof(*u.xsave));
3682                 if (IS_ERR(u.xsave))
3683                         return PTR_ERR(u.xsave);
3684 
3685                 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
3686                 break;
3687         }
3688         case KVM_GET_XCRS: {
3689                 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
3690                 r = -ENOMEM;
3691                 if (!u.xcrs)
3692                         break;
3693 
3694                 kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
3695 
3696                 r = -EFAULT;
3697                 if (copy_to_user(argp, u.xcrs,
3698                                  sizeof(struct kvm_xcrs)))
3699                         break;
3700                 r = 0;
3701                 break;
3702         }
3703         case KVM_SET_XCRS: {
3704                 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
3705                 if (IS_ERR(u.xcrs))
3706                         return PTR_ERR(u.xcrs);
3707 
3708                 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
3709                 break;
3710         }
3711         case KVM_SET_TSC_KHZ: {
3712                 u32 user_tsc_khz;
3713 
3714                 r = -EINVAL;
3715                 user_tsc_khz = (u32)arg;
3716 
3717                 if (user_tsc_khz >= kvm_max_guest_tsc_khz)
3718                         goto out;
3719 
3720                 if (user_tsc_khz == 0)
3721                         user_tsc_khz = tsc_khz;
3722 
3723                 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
3724                         r = 0;
3725 
3726                 goto out;
3727         }
3728         case KVM_GET_TSC_KHZ: {
3729                 r = vcpu->arch.virtual_tsc_khz;
3730                 goto out;
3731         }
3732         case KVM_KVMCLOCK_CTRL: {
3733                 r = kvm_set_guest_paused(vcpu);
3734                 goto out;
3735         }
3736         case KVM_ENABLE_CAP: {
3737                 struct kvm_enable_cap cap;
3738 
3739                 r = -EFAULT;
3740                 if (copy_from_user(&cap, argp, sizeof(cap)))
3741                         goto out;
3742                 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
3743                 break;
3744         }
3745         default:
3746                 r = -EINVAL;
3747         }
3748 out:
3749         kfree(u.buffer);
3750         return r;
3751 }
3752 
3753 int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
3754 {
3755         return VM_FAULT_SIGBUS;
3756 }
3757 
3758 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
3759 {
3760         int ret;
3761 
3762         if (addr > (unsigned int)(-3 * PAGE_SIZE))
3763                 return -EINVAL;
3764         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
3765         return ret;
3766 }
3767 
3768 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
3769                                               u64 ident_addr)
3770 {
3771         kvm->arch.ept_identity_map_addr = ident_addr;
3772         return 0;
3773 }
3774 
3775 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
3776                                           u32 kvm_nr_mmu_pages)
3777 {
3778         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
3779                 return -EINVAL;
3780 
3781         mutex_lock(&kvm->slots_lock);
3782 
3783         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
3784         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
3785 
3786         mutex_unlock(&kvm->slots_lock);
3787         return 0;
3788 }
3789 
3790 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
3791 {
3792         return kvm->arch.n_max_mmu_pages;
3793 }
3794 
3795 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3796 {
3797         struct kvm_pic *pic = kvm->arch.vpic;
3798         int r;
3799 
3800         r = 0;
3801         switch (chip->chip_id) {
3802         case KVM_IRQCHIP_PIC_MASTER:
3803                 memcpy(&chip->chip.pic, &pic->pics[0],
3804                         sizeof(struct kvm_pic_state));
3805                 break;
3806         case KVM_IRQCHIP_PIC_SLAVE:
3807                 memcpy(&chip->chip.pic, &pic->pics[1],
3808                         sizeof(struct kvm_pic_state));
3809                 break;
3810         case KVM_IRQCHIP_IOAPIC:
3811                 kvm_get_ioapic(kvm, &chip->chip.ioapic);
3812                 break;
3813         default:
3814                 r = -EINVAL;
3815                 break;
3816         }
3817         return r;
3818 }
3819 
3820 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
3821 {
3822         struct kvm_pic *pic = kvm->arch.vpic;
3823         int r;
3824 
3825         r = 0;
3826         switch (chip->chip_id) {
3827         case KVM_IRQCHIP_PIC_MASTER:
3828                 spin_lock(&pic->lock);
3829                 memcpy(&pic->pics[0], &chip->chip.pic,
3830                         sizeof(struct kvm_pic_state));
3831                 spin_unlock(&pic->lock);
3832                 break;
3833         case KVM_IRQCHIP_PIC_SLAVE:
3834                 spin_lock(&pic->lock);
3835                 memcpy(&pic->pics[1], &chip->chip.pic,
3836                         sizeof(struct kvm_pic_state));
3837                 spin_unlock(&pic->lock);
3838                 break;
3839         case KVM_IRQCHIP_IOAPIC:
3840                 kvm_set_ioapic(kvm, &chip->chip.ioapic);
3841                 break;
3842         default:
3843                 r = -EINVAL;
3844                 break;
3845         }
3846         kvm_pic_update_irq(pic);
3847         return r;
3848 }
3849 
3850 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3851 {
3852         struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
3853 
3854         BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
3855 
3856         mutex_lock(&kps->lock);
3857         memcpy(ps, &kps->channels, sizeof(*ps));
3858         mutex_unlock(&kps->lock);
3859         return 0;
3860 }
3861 
3862 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
3863 {
3864         int i;
3865         struct kvm_pit *pit = kvm->arch.vpit;
3866 
3867         mutex_lock(&pit->pit_state.lock);
3868         memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
3869         for (i = 0; i < 3; i++)
3870                 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
3871         mutex_unlock(&pit->pit_state.lock);
3872         return 0;
3873 }
3874 
3875 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3876 {
3877         mutex_lock(&kvm->arch.vpit->pit_state.lock);
3878         memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
3879                 sizeof(ps->channels));
3880         ps->flags = kvm->arch.vpit->pit_state.flags;
3881         mutex_unlock(&kvm->arch.vpit->pit_state.lock);
3882         memset(&ps->reserved, 0, sizeof(ps->reserved));
3883         return 0;
3884 }
3885 
3886 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
3887 {
3888         int start = 0;
3889         int i;
3890         u32 prev_legacy, cur_legacy;
3891         struct kvm_pit *pit = kvm->arch.vpit;
3892 
3893         mutex_lock(&pit->pit_state.lock);
3894         prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
3895         cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
3896         if (!prev_legacy && cur_legacy)
3897                 start = 1;
3898         memcpy(&pit->pit_state.channels, &ps->channels,
3899                sizeof(pit->pit_state.channels));
3900         pit->pit_state.flags = ps->flags;
3901         for (i = 0; i < 3; i++)
3902                 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
3903                                    start && i == 0);
3904         mutex_unlock(&pit->pit_state.lock);
3905         return 0;
3906 }
3907 
3908 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
3909                                  struct kvm_reinject_control *control)
3910 {
3911         struct kvm_pit *pit = kvm->arch.vpit;
3912 
3913         if (!pit)
3914                 return -ENXIO;
3915 
3916         /* pit->pit_state.lock was overloaded to prevent userspace from getting
3917          * an inconsistent state after running multiple KVM_REINJECT_CONTROL
3918          * ioctls in parallel.  Use a separate lock if that ioctl isn't rare.
3919          */
3920         mutex_lock(&pit->pit_state.lock);
3921         kvm_pit_set_reinject(pit, control->pit_reinject);
3922         mutex_unlock(&pit->pit_state.lock);
3923 
3924         return 0;
3925 }
3926 
3927 /**
3928  * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
3929  * @kvm: kvm instance
3930  * @log: slot id and address to which we copy the log
3931  *
3932  * Steps 1-4 below provide general overview of dirty page logging. See
3933  * kvm_get_dirty_log_protect() function description for additional details.
3934  *
3935  * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
3936  * always flush the TLB (step 4) even if previous step failed  and the dirty
3937  * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
3938  * does not preclude user space subsequent dirty log read. Flushing TLB ensures
3939  * writes will be marked dirty for next log read.
3940  *
3941  *   1. Take a snapshot of the bit and clear it if needed.
3942  *   2. Write protect the corresponding page.
3943  *   3. Copy the snapshot to the userspace.
3944  *   4. Flush TLB's if needed.
3945  */
3946 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
3947 {
3948         bool is_dirty = false;
3949         int r;
3950 
3951         mutex_lock(&kvm->slots_lock);
3952 
3953         /*
3954          * Flush potentially hardware-cached dirty pages to dirty_bitmap.
3955          */
3956         if (kvm_x86_ops->flush_log_dirty)
3957                 kvm_x86_ops->flush_log_dirty(kvm);
3958 
3959         r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
3960 
3961         /*
3962          * All the TLBs can be flushed out of mmu lock, see the comments in
3963          * kvm_mmu_slot_remove_write_access().
3964          */
3965         lockdep_assert_held(&kvm->slots_lock);
3966         if (is_dirty)
3967                 kvm_flush_remote_tlbs(kvm);
3968 
3969         mutex_unlock(&kvm->slots_lock);
3970         return r;
3971 }
3972 
3973 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
3974                         bool line_status)
3975 {
3976         if (!irqchip_in_kernel(kvm))
3977                 return -ENXIO;
3978 
3979         irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
3980                                         irq_event->irq, irq_event->level,
3981                                         line_status);
3982         return 0;
3983 }
3984 
3985 static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3986                                    struct kvm_enable_cap *cap)
3987 {
3988         int r;
3989 
3990         if (cap->flags)
3991                 return -EINVAL;
3992 
3993         switch (cap->cap) {
3994         case KVM_CAP_DISABLE_QUIRKS:
3995                 kvm->arch.disabled_quirks = cap->args[0];
3996                 r = 0;
3997                 break;
3998         case KVM_CAP_SPLIT_IRQCHIP: {
3999                 mutex_lock(&kvm->lock);
4000                 r = -EINVAL;
4001                 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
4002                         goto split_irqchip_unlock;
4003                 r = -EEXIST;
4004                 if (irqchip_in_kernel(kvm))
4005                         goto split_irqchip_unlock;
4006                 if (kvm->created_vcpus)
4007                         goto split_irqchip_unlock;
4008                 r = kvm_setup_empty_irq_routing(kvm);
4009                 if (r)
4010                         goto split_irqchip_unlock;
4011                 /* Pairs with irqchip_in_kernel. */
4012                 smp_wmb();
4013                 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
4014                 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
4015                 r = 0;
4016 split_irqchip_unlock:
4017                 mutex_unlock(&kvm->lock);
4018                 break;
4019         }
4020         case KVM_CAP_X2APIC_API:
4021                 r = -EINVAL;
4022                 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
4023                         break;
4024 
4025                 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
4026                         kvm->arch.x2apic_format = true;
4027                 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
4028                         kvm->arch.x2apic_broadcast_quirk_disabled = true;
4029 
4030                 r = 0;
4031                 break;
4032         default:
4033                 r = -EINVAL;
4034                 break;
4035         }
4036         return r;
4037 }
4038 
4039 long kvm_arch_vm_ioctl(struct file *filp,
4040                        unsigned int ioctl, unsigned long arg)
4041 {
4042         struct kvm *kvm = filp->private_data;
4043         void __user *argp = (void __user *)arg;
4044         int r = -ENOTTY;
4045         /*
4046          * This union makes it completely explicit to gcc-3.x
4047          * that these two variables' stack usage should be
4048          * combined, not added together.
4049          */
4050         union {
4051                 struct kvm_pit_state ps;
4052                 struct kvm_pit_state2 ps2;
4053                 struct kvm_pit_config pit_config;
4054         } u;
4055 
4056         switch (ioctl) {
4057         case KVM_SET_TSS_ADDR:
4058                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
4059                 break;
4060         case KVM_SET_IDENTITY_MAP_ADDR: {
4061                 u64 ident_addr;
4062 
4063                 mutex_lock(&kvm->lock);
4064                 r = -EINVAL;
4065                 if (kvm->created_vcpus)
4066                         goto set_identity_unlock;
4067                 r = -EFAULT;
4068                 if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
4069                         goto set_identity_unlock;
4070                 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
4071 set_identity_unlock:
4072                 mutex_unlock(&kvm->lock);
4073                 break;
4074         }
4075         case KVM_SET_NR_MMU_PAGES:
4076                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
4077                 break;
4078         case KVM_GET_NR_MMU_PAGES:
4079                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
4080                 break;
4081         case KVM_CREATE_IRQCHIP: {
4082                 mutex_lock(&kvm->lock);
4083 
4084                 r = -EEXIST;
4085                 if (irqchip_in_kernel(kvm))
4086                         goto create_irqchip_unlock;
4087 
4088                 r = -EINVAL;
4089                 if (kvm->created_vcpus)
4090                         goto create_irqchip_unlock;
4091 
4092                 r = kvm_pic_init(kvm);
4093                 if (r)
4094                         goto create_irqchip_unlock;
4095 
4096                 r = kvm_ioapic_init(kvm);
4097                 if (r) {
4098                         kvm_pic_destroy(kvm);
4099                         goto create_irqchip_unlock;
4100                 }
4101 
4102                 r = kvm_setup_default_irq_routing(kvm);
4103                 if (r) {
4104                         kvm_ioapic_destroy(kvm);
4105                         kvm_pic_destroy(kvm);
4106                         goto create_irqchip_unlock;
4107                 }
4108                 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
4109                 smp_wmb();
4110                 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
4111         create_irqchip_unlock:
4112                 mutex_unlock(&kvm->lock);
4113                 break;
4114         }
4115         case KVM_CREATE_PIT:
4116                 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
4117                 goto create_pit;
4118         case KVM_CREATE_PIT2:
4119                 r = -EFAULT;
4120                 if (copy_from_user(&u.pit_config, argp,
4121                                    sizeof(struct kvm_pit_config)))
4122                         goto out;
4123         create_pit:
4124                 mutex_lock(&kvm->lock);
4125                 r = -EEXIST;
4126                 if (kvm->arch.vpit)
4127                         goto create_pit_unlock;
4128                 r = -ENOMEM;
4129                 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
4130                 if (kvm->arch.vpit)
4131                         r = 0;
4132         create_pit_unlock:
4133                 mutex_unlock(&kvm->lock);
4134                 break;
4135         case KVM_GET_IRQCHIP: {
4136                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4137                 struct kvm_irqchip *chip;
4138 
4139                 chip = memdup_user(argp, sizeof(*chip));
4140                 if (IS_ERR(chip)) {
4141                         r = PTR_ERR(chip);
4142                         goto out;
4143                 }
4144 
4145                 r = -ENXIO;
4146                 if (!irqchip_kernel(kvm))
4147                         goto get_irqchip_out;
4148                 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
4149                 if (r)
4150                         goto get_irqchip_out;
4151                 r = -EFAULT;
4152                 if (copy_to_user(argp, chip, sizeof *chip))
4153                         goto get_irqchip_out;
4154                 r = 0;
4155         get_irqchip_out:
4156                 kfree(chip);
4157                 break;
4158         }
4159         case KVM_SET_IRQCHIP: {
4160                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
4161                 struct kvm_irqchip *chip;
4162 
4163                 chip = memdup_user(argp, sizeof(*chip));
4164                 if (IS_ERR(chip)) {
4165                         r = PTR_ERR(chip);
4166                         goto out;
4167                 }
4168 
4169                 r = -ENXIO;
4170                 if (!irqchip_kernel(kvm))
4171                         goto set_irqchip_out;
4172                 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
4173                 if (r)
4174                         goto set_irqchip_out;
4175                 r = 0;
4176         set_irqchip_out:
4177                 kfree(chip);
4178                 break;
4179         }
4180         case KVM_GET_PIT: {
4181                 r = -EFAULT;
4182                 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
4183                         goto out;
4184                 r = -ENXIO;
4185                 if (!kvm->arch.vpit)
4186                         goto out;
4187                 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
4188                 if (r)
4189                         goto out;
4190                 r = -EFAULT;
4191                 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
4192                         goto out;
4193                 r = 0;
4194                 break;
4195         }
4196         case KVM_SET_PIT: {
4197                 r = -EFAULT;
4198                 if (copy_from_user(&u.ps, argp, sizeof u.ps))
4199                         goto out;
4200                 r = -ENXIO;
4201                 if (!kvm->arch.vpit)
4202                         goto out;
4203                 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
4204                 break;
4205         }
4206         case KVM_GET_PIT2: {
4207                 r = -ENXIO;
4208                 if (!kvm->arch.vpit)
4209                         goto out;
4210                 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
4211                 if (r)
4212                         goto out;
4213                 r = -EFAULT;
4214                 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
4215                         goto out;
4216                 r = 0;
4217                 break;
4218         }
4219         case KVM_SET_PIT2: {
4220                 r = -EFAULT;
4221                 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
4222                         goto out;
4223                 r = -ENXIO;
4224                 if (!kvm->arch.vpit)
4225                         goto out;
4226                 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
4227                 break;
4228         }
4229         case KVM_REINJECT_CONTROL: {
4230                 struct kvm_reinject_control control;
4231                 r =  -EFAULT;
4232                 if (copy_from_user(&control, argp, sizeof(control)))
4233                         goto out;
4234                 r = kvm_vm_ioctl_reinject(kvm, &control);
4235                 break;
4236         }
4237         case KVM_SET_BOOT_CPU_ID:
4238                 r = 0;
4239                 mutex_lock(&kvm->lock);
4240                 if (kvm->created_vcpus)
4241                         r = -EBUSY;
4242                 else
4243                         kvm->arch.bsp_vcpu_id = arg;
4244                 mutex_unlock(&kvm->lock);
4245                 break;
4246         case KVM_XEN_HVM_CONFIG: {
4247                 r = -EFAULT;
4248                 if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
4249                                    sizeof(struct kvm_xen_hvm_config)))
4250                         goto out;
4251                 r = -EINVAL;
4252                 if (kvm->arch.xen_hvm_config.flags)
4253                         goto out;
4254                 r = 0;
4255                 break;
4256         }
4257         case KVM_SET_CLOCK: {
4258                 struct kvm_clock_data user_ns;
4259                 u64 now_ns;
4260 
4261                 r = -EFAULT;
4262                 if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
4263                         goto out;
4264 
4265                 r = -EINVAL;
4266                 if (user_ns.flags)
4267                         goto out;
4268 
4269                 r = 0;
4270                 /*
4271                  * TODO: userspace has to take care of races with VCPU_RUN, so
4272                  * kvm_gen_update_masterclock() can be cut down to locked
4273                  * pvclock_update_vm_gtod_copy().
4274                  */
4275                 kvm_gen_update_masterclock(kvm);
4276                 now_ns = get_kvmclock_ns(kvm);
4277                 kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
4278                 kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
4279                 break;
4280         }
4281         case KVM_GET_CLOCK: {
4282                 struct kvm_clock_data user_ns;
4283                 u64 now_ns;
4284 
4285                 now_ns = get_kvmclock_ns(kvm);
4286                 user_ns.clock = now_ns;
4287                 user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
4288                 memset(&user_ns.pad, 0, sizeof(user_ns.pad));
4289 
4290                 r = -EFAULT;
4291                 if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
4292                         goto out;
4293                 r = 0;
4294                 break;
4295         }
4296         case KVM_ENABLE_CAP: {
4297                 struct kvm_enable_cap cap;
4298 
4299                 r = -EFAULT;
4300                 if (copy_from_user(&cap, argp, sizeof(cap)))
4301                         goto out;
4302                 r = kvm_vm_ioctl_enable_cap(kvm, &cap);
4303                 break;
4304         }
4305         default:
4306                 r = -ENOTTY;
4307         }
4308 out:
4309         return r;
4310 }
4311 
4312 static void kvm_init_msr_list(void)
4313 {
4314         u32 dummy[2];
4315         unsigned i, j;
4316 
4317         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
4318                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
4319                         continue;
4320 
4321                 /*
4322                  * Even MSRs that are valid in the host may not be exposed
4323                  * to the guests in some cases.
4324                  */
4325                 switch (msrs_to_save[i]) {
4326                 case MSR_IA32_BNDCFGS:
4327                         if (!kvm_x86_ops->mpx_supported())
4328                                 continue;
4329                         break;
4330                 case MSR_TSC_AUX:
4331                         if (!kvm_x86_ops->rdtscp_supported())
4332                                 continue;
4333                         break;
4334                 default:
4335                         break;
4336                 }
4337 
4338                 if (j < i)
4339                         msrs_to_save[j] = msrs_to_save[i];
4340                 j++;
4341         }
4342         num_msrs_to_save = j;
4343 
4344         for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
4345                 switch (emulated_msrs[i]) {
4346                 case MSR_IA32_SMBASE:
4347                         if (!kvm_x86_ops->cpu_has_high_real_mode_segbase())
4348                                 continue;
4349                         break;
4350                 default:
4351                         break;
4352                 }
4353 
4354                 if (j < i)
4355                         emulated_msrs[j] = emulated_msrs[i];
4356                 j++;
4357         }
4358         num_emulated_msrs = j;
4359 }
4360 
4361 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
4362                            const void *v)
4363 {
4364         int handled = 0;
4365         int n;
4366 
4367         do {
4368                 n = min(len, 8);
4369                 if (!(lapic_in_kernel(vcpu) &&
4370                       !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
4371                     && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
4372                         break;
4373                 handled += n;
4374                 addr += n;
4375                 len -= n;
4376                 v += n;
4377         } while (len);
4378 
4379         return handled;
4380 }
4381 
4382 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
4383 {
4384         int handled = 0;
4385         int n;
4386 
4387         do {
4388                 n = min(len, 8);
4389                 if (!(lapic_in_kernel(vcpu) &&
4390                       !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
4391                                          addr, n, v))
4392                     && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
4393                         break;
4394                 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
4395                 handled += n;
4396                 addr += n;
4397                 len -= n;
4398                 v += n;
4399         } while (len);
4400 
4401         return handled;
4402 }
4403 
4404 static void kvm_set_segment(struct kvm_vcpu *vcpu,
4405                         struct kvm_segment *var, int seg)
4406 {
4407         kvm_x86_ops->set_segment(vcpu, var, seg);
4408 }
4409 
4410 void kvm_get_segment(struct kvm_vcpu *vcpu,
4411                      struct kvm_segment *var, int seg)
4412 {
4413         kvm_x86_ops->get_segment(vcpu, var, seg);
4414 }
4415 
4416 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
4417                            struct x86_exception *exception)
4418 {
4419         gpa_t t_gpa;
4420 
4421         BUG_ON(!mmu_is_nested(vcpu));
4422 
4423         /* NPT walks are always user-walks */
4424         access |= PFERR_USER_MASK;
4425         t_gpa  = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception);
4426 
4427         return t_gpa;
4428 }
4429 
4430 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
4431                               struct x86_exception *exception)
4432 {
4433         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4434         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4435 }
4436 
4437  gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
4438                                 struct x86_exception *exception)
4439 {
4440         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4441         access |= PFERR_FETCH_MASK;
4442         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4443 }
4444 
4445 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
4446                                struct x86_exception *exception)
4447 {
4448         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4449         access |= PFERR_WRITE_MASK;
4450         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4451 }
4452 
4453 /* uses this to access any guest's mapped memory without checking CPL */
4454 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
4455                                 struct x86_exception *exception)
4456 {
4457         return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
4458 }
4459 
4460 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
4461                                       struct kvm_vcpu *vcpu, u32 access,
4462                                       struct x86_exception *exception)
4463 {
4464         void *data = val;
4465         int r = X86EMUL_CONTINUE;
4466 
4467         while (bytes) {
4468                 gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
4469                                                             exception);
4470                 unsigned offset = addr & (PAGE_SIZE-1);
4471                 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
4472                 int ret;
4473 
4474                 if (gpa == UNMAPPED_GVA)
4475                         return X86EMUL_PROPAGATE_FAULT;
4476                 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
4477                                                offset, toread);
4478                 if (ret < 0) {
4479                         r = X86EMUL_IO_NEEDED;
4480                         goto out;
4481                 }
4482 
4483                 bytes -= toread;
4484                 data += toread;
4485                 addr += toread;
4486         }
4487 out:
4488         return r;
4489 }
4490 
4491 /* used for instruction fetching */
4492 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
4493                                 gva_t addr, void *val, unsigned int bytes,
4494                                 struct x86_exception *exception)
4495 {
4496         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4497         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4498         unsigned offset;
4499         int ret;
4500 
4501         /* Inline kvm_read_guest_virt_helper for speed.  */
4502         gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
4503                                                     exception);
4504         if (unlikely(gpa == UNMAPPED_GVA))
4505                 return X86EMUL_PROPAGATE_FAULT;
4506 
4507         offset = addr & (PAGE_SIZE-1);
4508         if (WARN_ON(offset + bytes > PAGE_SIZE))
4509                 bytes = (unsigned)PAGE_SIZE - offset;
4510         ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
4511                                        offset, bytes);
4512         if (unlikely(ret < 0))
4513                 return X86EMUL_IO_NEEDED;
4514 
4515         return X86EMUL_CONTINUE;
4516 }
4517 
4518 int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
4519                                gva_t addr, void *val, unsigned int bytes,
4520                                struct x86_exception *exception)
4521 {
4522         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4523         u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
4524 
4525         return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
4526                                           exception);
4527 }
4528 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
4529 
4530 static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4531                                       gva_t addr, void *val, unsigned int bytes,
4532                                       struct x86_exception *exception)
4533 {
4534         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4535         return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
4536 }
4537 
4538 static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
4539                 unsigned long addr, void *val, unsigned int bytes)
4540 {
4541         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4542         int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
4543 
4544         return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
4545 }
4546 
4547 int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
4548                                        gva_t addr, void *val,
4549                                        unsigned int bytes,
4550                                        struct x86_exception *exception)
4551 {
4552         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4553         void *data = val;
4554         int r = X86EMUL_CONTINUE;
4555 
4556         while (bytes) {
4557                 gpa_t gpa =  vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
4558                                                              PFERR_WRITE_MASK,
4559                                                              exception);
4560                 unsigned offset = addr & (PAGE_SIZE-1);
4561                 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
4562                 int ret;
4563 
4564                 if (gpa == UNMAPPED_GVA)
4565                         return X86EMUL_PROPAGATE_FAULT;
4566                 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
4567                 if (ret < 0) {
4568                         r = X86EMUL_IO_NEEDED;
4569                         goto out;
4570                 }
4571 
4572                 bytes -= towrite;
4573                 data += towrite;
4574                 addr += towrite;
4575         }
4576 out:
4577         return r;
4578 }
4579 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
4580 
4581 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4582                             gpa_t gpa, bool write)
4583 {
4584         /* For APIC access vmexit */
4585         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4586                 return 1;
4587 
4588         if (vcpu_match_mmio_gpa(vcpu, gpa)) {
4589                 trace_vcpu_match_mmio(gva, gpa, write, true);
4590                 return 1;
4591         }
4592 
4593         return 0;
4594 }
4595 
4596 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
4597                                 gpa_t *gpa, struct x86_exception *exception,
4598                                 bool write)
4599 {
4600         u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
4601                 | (write ? PFERR_WRITE_MASK : 0);
4602 
4603         /*
4604          * currently PKRU is only applied to ept enabled guest so
4605          * there is no pkey in EPT page table for L1 guest or EPT
4606          * shadow page table for L2 guest.
4607          */
4608         if (vcpu_match_mmio_gva(vcpu, gva)
4609             && !permission_fault(vcpu, vcpu->arch.walk_mmu,
4610                                  vcpu->arch.access, 0, access)) {
4611                 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
4612                                         (gva & (PAGE_SIZE - 1));
4613                 trace_vcpu_match_mmio(gva, *gpa, write, false);
4614                 return 1;
4615         }
4616 
4617         *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
4618 
4619         if (*gpa == UNMAPPED_GVA)
4620                 return -1;
4621 
4622         return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
4623 }
4624 
4625 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
4626                         const void *val, int bytes)
4627 {
4628         int ret;
4629 
4630         ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
4631         if (ret < 0)
4632                 return 0;
4633         kvm_page_track_write(vcpu, gpa, val, bytes);
4634         return 1;
4635 }
4636 
4637 struct read_write_emulator_ops {
4638         int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
4639                                   int bytes);
4640         int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
4641                                   void *val, int bytes);
4642         int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4643                                int bytes, void *val);
4644         int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
4645                                     void *val, int bytes);
4646         bool write;
4647 };
4648 
4649 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
4650 {
4651         if (vcpu->mmio_read_completed) {
4652                 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
4653                                vcpu->mmio_fragments[0].gpa, val);
4654                 vcpu->mmio_read_completed = 0;
4655                 return 1;
4656         }
4657 
4658         return 0;
4659 }
4660 
4661 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4662                         void *val, int bytes)
4663 {
4664         return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
4665 }
4666 
4667 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
4668                          void *val, int bytes)
4669 {
4670         return emulator_write_phys(vcpu, gpa, val, bytes);
4671 }
4672 
4673 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
4674 {
4675         trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
4676         return vcpu_mmio_write(vcpu, gpa, bytes, val);
4677 }
4678 
4679 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4680                           void *val, int bytes)
4681 {
4682         trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
4683         return X86EMUL_IO_NEEDED;
4684 }
4685 
4686 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
4687                            void *val, int bytes)
4688 {
4689         struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
4690 
4691         memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
4692         return X86EMUL_CONTINUE;
4693 }
4694 
4695 static const struct read_write_emulator_ops read_emultor = {
4696         .read_write_prepare = read_prepare,
4697         .read_write_emulate = read_emulate,
4698         .read_write_mmio = vcpu_mmio_read,
4699         .read_write_exit_mmio = read_exit_mmio,
4700 };
4701 
4702 static const struct read_write_emulator_ops write_emultor = {
4703         .read_write_emulate = write_emulate,
4704         .read_write_mmio = write_mmio,
4705         .read_write_exit_mmio = write_exit_mmio,
4706         .write = true,
4707 };
4708 
4709 static int emulator_read_write_onepage(unsigned long addr, void *val,
4710                                        unsigned int bytes,
4711                                        struct x86_exception *exception,
4712                                        struct kvm_vcpu *vcpu,
4713                                        const struct read_write_emulator_ops *ops)
4714 {
4715         gpa_t gpa;
4716         int handled, ret;
4717         bool write = ops->write;
4718         struct kvm_mmio_fragment *frag;
4719         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
4720 
4721         /*
4722          * If the exit was due to a NPF we may already have a GPA.
4723          * If the GPA is present, use it to avoid the GVA to GPA table walk.
4724          * Note, this cannot be used on string operations since string
4725          * operation using rep will only have the initial GPA from the NPF
4726          * occurred.
4727          */
4728         if (vcpu->arch.gpa_available &&
4729             emulator_can_use_gpa(ctxt) &&
4730             (addr & ~PAGE_MASK) == (vcpu->arch.gpa_val & ~PAGE_MASK)) {
4731                 gpa = vcpu->arch.gpa_val;
4732                 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
4733         } else {
4734                 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
4735                 if (ret < 0)
4736                         return X86EMUL_PROPAGATE_FAULT;
4737         }
4738 
4739         if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
4740                 return X86EMUL_CONTINUE;
4741 
4742         /*
4743          * Is this MMIO handled locally?
4744          */
4745         handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
4746         if (handled == bytes)
4747                 return X86EMUL_CONTINUE;
4748 
4749         gpa += handled;
4750         bytes -= handled;
4751         val += handled;
4752 
4753         WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
4754         frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
4755         frag->gpa = gpa;
4756         frag->data = val;
4757         frag->len = bytes;
4758         return X86EMUL_CONTINUE;
4759 }
4760 
4761 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
4762                         unsigned long addr,
4763                         void *val, unsigned int bytes,
4764                         struct x86_exception *exception,
4765                         const struct read_write_emulator_ops *ops)
4766 {
4767         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4768         gpa_t gpa;
4769         int rc;
4770 
4771         if (ops->read_write_prepare &&
4772                   ops->read_write_prepare(vcpu, val, bytes))
4773                 return X86EMUL_CONTINUE;
4774 
4775         vcpu->mmio_nr_fragments = 0;
4776 
4777         /* Crossing a page boundary? */
4778         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
4779                 int now;
4780 
4781                 now = -addr & ~PAGE_MASK;
4782                 rc = emulator_read_write_onepage(addr, val, now, exception,
4783                                                  vcpu, ops);
4784 
4785                 if (rc != X86EMUL_CONTINUE)
4786                         return rc;
4787                 addr += now;
4788                 if (ctxt->mode != X86EMUL_MODE_PROT64)
4789                         addr = (u32)addr;
4790                 val += now;
4791                 bytes -= now;
4792         }
4793 
4794         rc = emulator_read_write_onepage(addr, val, bytes, exception,
4795                                          vcpu, ops);
4796         if (rc != X86EMUL_CONTINUE)
4797                 return rc;
4798 
4799         if (!vcpu->mmio_nr_fragments)
4800                 return rc;
4801 
4802         gpa = vcpu->mmio_fragments[0].gpa;
4803 
4804         vcpu->mmio_needed = 1;
4805         vcpu->mmio_cur_fragment = 0;
4806 
4807         vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
4808         vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
4809         vcpu->run->exit_reason = KVM_EXIT_MMIO;
4810         vcpu->run->mmio.phys_addr = gpa;
4811 
4812         return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
4813 }
4814 
4815 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
4816                                   unsigned long addr,
4817                                   void *val,
4818                                   unsigned int bytes,
4819                                   struct x86_exception *exception)
4820 {
4821         return emulator_read_write(ctxt, addr, val, bytes,
4822                                    exception, &read_emultor);
4823 }
4824 
4825 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
4826                             unsigned long addr,
4827                             const void *val,
4828                             unsigned int bytes,
4829                             struct x86_exception *exception)
4830 {
4831         return emulator_read_write(ctxt, addr, (void *)val, bytes,
4832                                    exception, &write_emultor);
4833 }
4834 
4835 #define CMPXCHG_TYPE(t, ptr, old, new) \
4836         (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
4837 
4838 #ifdef CONFIG_X86_64
4839 #  define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
4840 #else
4841 #  define CMPXCHG64(ptr, old, new) \
4842         (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
4843 #endif
4844 
4845 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
4846                                      unsigned long addr,
4847                                      const void *old,
4848                                      const void *new,
4849                                      unsigned int bytes,
4850                                      struct x86_exception *exception)
4851 {
4852         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4853         gpa_t gpa;
4854         struct page *page;
4855         char *kaddr;
4856         bool exchanged;
4857 
4858         /* guests cmpxchg8b have to be emulated atomically */
4859         if (bytes > 8 || (bytes & (bytes - 1)))
4860                 goto emul_write;
4861 
4862         gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
4863 
4864         if (gpa == UNMAPPED_GVA ||
4865             (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
4866                 goto emul_write;
4867 
4868         if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
4869                 goto emul_write;
4870 
4871         page = kvm_vcpu_gfn_to_page(vcpu, gpa >> PAGE_SHIFT);
4872         if (is_error_page(page))
4873                 goto emul_write;
4874 
4875         kaddr = kmap_atomic(page);
4876         kaddr += offset_in_page(gpa);
4877         switch (bytes) {
4878         case 1:
4879                 exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
4880                 break;
4881         case 2:
4882                 exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
4883                 break;
4884         case 4:
4885                 exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
4886                 break;
4887         case 8:
4888                 exchanged = CMPXCHG64(kaddr, old, new);
4889                 break;
4890         default:
4891                 BUG();
4892         }
4893         kunmap_atomic(kaddr);
4894         kvm_release_page_dirty(page);
4895 
4896         if (!exchanged)
4897                 return X86EMUL_CMPXCHG_FAILED;
4898 
4899         kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
4900         kvm_page_track_write(vcpu, gpa, new, bytes);
4901 
4902         return X86EMUL_CONTINUE;
4903 
4904 emul_write:
4905         printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
4906 
4907         return emulator_write_emulated(ctxt, addr, new, bytes, exception);
4908 }
4909 
4910 static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
4911 {
4912         int r = 0, i;
4913 
4914         for (i = 0; i < vcpu->arch.pio.count; i++) {
4915                 if (vcpu->arch.pio.in)
4916                         r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
4917                                             vcpu->arch.pio.size, pd);
4918                 else
4919                         r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
4920                                              vcpu->arch.pio.port, vcpu->arch.pio.size,
4921                                              pd);
4922                 if (r)
4923                         break;
4924                 pd += vcpu->arch.pio.size;
4925         }
4926         return r;
4927 }
4928 
4929 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
4930                                unsigned short port, void *val,
4931                                unsigned int count, bool in)
4932 {
4933         vcpu->arch.pio.port = port;
4934         vcpu->arch.pio.in = in;
4935         vcpu->arch.pio.count  = count;
4936         vcpu->arch.pio.size = size;
4937 
4938         if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
4939                 vcpu->arch.pio.count = 0;
4940                 return 1;
4941         }
4942 
4943         vcpu->run->exit_reason = KVM_EXIT_IO;
4944         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
4945         vcpu->run->io.size = size;
4946         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
4947         vcpu->run->io.count = count;
4948         vcpu->run->io.port = port;
4949 
4950         return 0;
4951 }
4952 
4953 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
4954                                     int size, unsigned short port, void *val,
4955                                     unsigned int count)
4956 {
4957         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4958         int ret;
4959 
4960         if (vcpu->arch.pio.count)
4961                 goto data_avail;
4962 
4963         memset(vcpu->arch.pio_data, 0, size * count);
4964 
4965         ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
4966         if (ret) {
4967 data_avail:
4968                 memcpy(val, vcpu->arch.pio_data, size * count);
4969                 trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
4970                 vcpu->arch.pio.count = 0;
4971                 return 1;
4972         }
4973 
4974         return 0;
4975 }
4976 
4977 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
4978                                      int size, unsigned short port,
4979                                      const void *val, unsigned int count)
4980 {
4981         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
4982 
4983         memcpy(vcpu->arch.pio_data, val, size * count);
4984         trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
4985         return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
4986 }
4987 
4988 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
4989 {
4990         return kvm_x86_ops->get_segment_base(vcpu, seg);
4991 }
4992 
4993 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
4994 {
4995         kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
4996 }
4997 
4998 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
4999 {
5000         if (!need_emulate_wbinvd(vcpu))
5001                 return X86EMUL_CONTINUE;
5002 
5003         if (kvm_x86_ops->has_wbinvd_exit()) {
5004                 int cpu = get_cpu();
5005 
5006                 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
5007                 smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
5008                                 wbinvd_ipi, NULL, 1);
5009                 put_cpu();
5010                 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
5011         } else
5012                 wbinvd();
5013         return X86EMUL_CONTINUE;
5014 }
5015 
5016 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
5017 {
5018         kvm_emulate_wbinvd_noskip(vcpu);
5019         return kvm_skip_emulated_instruction(vcpu);
5020 }
5021 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
5022 
5023 
5024 
5025 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
5026 {
5027         kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
5028 }
5029 
5030 static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
5031                            unsigned long *dest)
5032 {
5033         return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
5034 }
5035 
5036 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
5037                            unsigned long value)
5038 {
5039 
5040         return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
5041 }
5042 
5043 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
5044 {
5045         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
5046 }
5047 
5048 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
5049 {
5050         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5051         unsigned long value;
5052 
5053         switch (cr) {
5054         case 0:
5055                 value = kvm_read_cr0(vcpu);
5056                 break;
5057         case 2:
5058                 value = vcpu->arch.cr2;
5059                 break;
5060         case 3:
5061                 value = kvm_read_cr3(vcpu);
5062                 break;
5063         case 4:
5064                 value = kvm_read_cr4(vcpu);
5065                 break;
5066         case 8:
5067                 value = kvm_get_cr8(vcpu);
5068                 break;
5069         default:
5070                 kvm_err("%s: unexpected cr %u\n", __func__, cr);
5071                 return 0;
5072         }
5073 
5074         return value;
5075 }
5076 
5077 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
5078 {
5079         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5080         int res = 0;
5081 
5082         switch (cr) {
5083         case 0:
5084                 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
5085                 break;
5086         case 2:
5087                 vcpu->arch.cr2 = val;
5088                 break;
5089         case 3:
5090                 res = kvm_set_cr3(vcpu, val);
5091                 break;
5092         case 4:
5093                 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
5094                 break;
5095         case 8:
5096                 res = kvm_set_cr8(vcpu, val);
5097                 break;
5098         default:
5099                 kvm_err("%s: unexpected cr %u\n", __func__, cr);
5100                 res = -1;
5101         }
5102 
5103         return res;
5104 }
5105 
5106 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
5107 {
5108         return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
5109 }
5110 
5111 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5112 {
5113         kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
5114 }
5115 
5116 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5117 {
5118         kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
5119 }
5120 
5121 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5122 {
5123         kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
5124 }
5125 
5126 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
5127 {
5128         kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
5129 }
5130 
5131 static unsigned long emulator_get_cached_segment_base(
5132         struct x86_emulate_ctxt *ctxt, int seg)
5133 {
5134         return get_segment_base(emul_to_vcpu(ctxt), seg);
5135 }
5136 
5137 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
5138                                  struct desc_struct *desc, u32 *base3,
5139                                  int seg)
5140 {
5141         struct kvm_segment var;
5142 
5143         kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
5144         *selector = var.selector;
5145 
5146         if (var.unusable) {
5147                 memset(desc, 0, sizeof(*desc));
5148                 if (base3)
5149                         *base3 = 0;
5150                 return false;
5151         }
5152 
5153         if (var.g)
5154                 var.limit >>= 12;
5155         set_desc_limit(desc, var.limit);
5156         set_desc_base(desc, (unsigned long)var.base);
5157 #ifdef CONFIG_X86_64
5158         if (base3)
5159                 *base3 = var.base >> 32;
5160 #endif
5161         desc->type = var.type;
5162         desc->s = var.s;
5163         desc->dpl = var.dpl;
5164         desc->p = var.present;
5165         desc->avl = var.avl;
5166         desc->l = var.l;
5167         desc->d = var.db;
5168         desc->g = var.g;
5169 
5170         return true;
5171 }
5172 
5173 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
5174                                  struct desc_struct *desc, u32 base3,
5175                                  int seg)
5176 {
5177         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5178         struct kvm_segment var;
5179 
5180         var.selector = selector;
5181         var.base = get_desc_base(desc);
5182 #ifdef CONFIG_X86_64
5183         var.base |= ((u64)base3) << 32;
5184 #endif
5185         var.limit = get_desc_limit(desc);
5186         if (desc->g)
5187                 var.limit = (var.limit << 12) | 0xfff;
5188         var.type = desc->type;
5189         var.dpl = desc->dpl;
5190         var.db = desc->d;
5191         var.s = desc->s;
5192         var.l = desc->l;
5193         var.g = desc->g;
5194         var.avl = desc->avl;
5195         var.present = desc->p;
5196         var.unusable = !var.present;
5197         var.padding = 0;
5198 
5199         kvm_set_segment(vcpu, &var, seg);
5200         return;
5201 }
5202 
5203 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
5204                             u32 msr_index, u64 *pdata)
5205 {
5206         struct msr_data msr;
5207         int r;
5208 
5209         msr.index = msr_index;
5210         msr.host_initiated = false;
5211         r = kvm_get_msr(emul_to_vcpu(ctxt), &msr);
5212         if (r)
5213                 return r;
5214 
5215         *pdata = msr.data;
5216         return 0;
5217 }
5218 
5219 static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
5220                             u32 msr_index, u64 data)
5221 {
5222         struct msr_data msr;
5223 
5224         msr.data = data;
5225         msr.index = msr_index;
5226         msr.host_initiated = false;
5227         return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
5228 }
5229 
5230 static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
5231 {
5232         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5233 
5234         return vcpu->arch.smbase;
5235 }
5236 
5237 static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
5238 {
5239         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5240 
5241         vcpu->arch.smbase = smbase;
5242 }
5243 
5244 static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
5245                               u32 pmc)
5246 {
5247         return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
5248 }
5249 
5250 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
5251                              u32 pmc, u64 *pdata)
5252 {
5253         return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
5254 }
5255 
5256 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
5257 {
5258         emul_to_vcpu(ctxt)->arch.halt_request = 1;
5259 }
5260 
5261 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
5262                               struct x86_instruction_info *info,
5263                               enum x86_intercept_stage stage)
5264 {
5265         return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
5266 }
5267 
5268 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
5269                         u32 *eax, u32 *ebx, u32 *ecx, u32 *edx, bool check_limit)
5270 {
5271         return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, check_limit);
5272 }
5273 
5274 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
5275 {
5276         return kvm_register_read(emul_to_vcpu(ctxt), reg);
5277 }
5278 
5279 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
5280 {
5281         kvm_register_write(emul_to_vcpu(ctxt), reg, val);
5282 }
5283 
5284 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
5285 {
5286         kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
5287 }
5288 
5289 static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
5290 {
5291         return emul_to_vcpu(ctxt)->arch.hflags;
5292 }
5293 
5294 static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
5295 {
5296         kvm_set_hflags(emul_to_vcpu(ctxt), emul_flags);
5297 }
5298 
5299 static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt, u64 smbase)
5300 {
5301         return kvm_x86_ops->pre_leave_smm(emul_to_vcpu(ctxt), smbase);
5302 }
5303 
5304 static const struct x86_emulate_ops emulate_ops = {
5305         .read_gpr            = emulator_read_gpr,
5306         .write_gpr           = emulator_write_gpr,
5307         .read_std            = kvm_read_guest_virt_system,
5308         .write_std           = kvm_write_guest_virt_system,
5309         .read_phys           = kvm_read_guest_phys_system,
5310         .fetch               = kvm_fetch_guest_virt,
5311         .read_emulated       = emulator_read_emulated,
5312         .write_emulated      = emulator_write_emulated,
5313         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
5314         .invlpg              = emulator_invlpg,
5315         .pio_in_emulated     = emulator_pio_in_emulated,
5316         .pio_out_emulated    = emulator_pio_out_emulated,
5317         .get_segment         = emulator_get_segment,
5318         .set_segment         = emulator_set_segment,
5319         .get_cached_segment_base = emulator_get_cached_segment_base,
5320         .get_gdt             = emulator_get_gdt,
5321         .get_idt             = emulator_get_idt,
5322         .set_gdt             = emulator_set_gdt,
5323         .set_idt             = emulator_set_idt,
5324         .get_cr              = emulator_get_cr,
5325         .set_cr              = emulator_set_cr,
5326         .cpl                 = emulator_get_cpl,
5327         .get_dr              = emulator_get_dr,
5328         .set_dr              = emulator_set_dr,
5329         .get_smbase          = emulator_get_smbase,
5330         .set_smbase          = emulator_set_smbase,
5331         .set_msr             = emulator_set_msr,
5332         .get_msr             = emulator_get_msr,
5333         .check_pmc           = emulator_check_pmc,
5334         .read_pmc            = emulator_read_pmc,
5335         .halt                = emulator_halt,
5336         .wbinvd              = emulator_wbinvd,
5337         .fix_hypercall       = emulator_fix_hypercall,
5338         .intercept           = emulator_intercept,
5339         .get_cpuid           = emulator_get_cpuid,
5340         .set_nmi_mask        = emulator_set_nmi_mask,
5341         .get_hflags          = emulator_get_hflags,
5342         .set_hflags          = emulator_set_hflags,
5343         .pre_leave_smm       = emulator_pre_leave_smm,
5344 };
5345 
5346 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
5347 {
5348         u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
5349         /*
5350          * an sti; sti; sequence only disable interrupts for the first
5351          * instruction. So, if the last instruction, be it emulated or
5352          * not, left the system with the INT_STI flag enabled, it
5353          * means that the last instruction is an sti. We should not
5354          * leave the flag on in this case. The same goes for mov ss
5355          */
5356         if (int_shadow & mask)
5357                 mask = 0;
5358         if (unlikely(int_shadow || mask)) {
5359                 kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
5360                 if (!mask)
5361                         kvm_make_request(KVM_REQ_EVENT, vcpu);
5362         }
5363 }
5364 
5365 static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
5366 {
5367         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5368         if (ctxt->exception.vector == PF_VECTOR)
5369                 return kvm_propagate_fault(vcpu, &ctxt->exception);
5370 
5371         if (ctxt->exception.error_code_valid)
5372                 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
5373                                       ctxt->exception.error_code);
5374         else
5375                 kvm_queue_exception(vcpu, ctxt->exception.vector);
5376         return false;
5377 }
5378 
5379 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
5380 {
5381         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5382         int cs_db, cs_l;
5383 
5384         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
5385 
5386         ctxt->eflags = kvm_get_rflags(vcpu);
5387         ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
5388 
5389         ctxt->eip = kvm_rip_read(vcpu);
5390         ctxt->mode = (!is_protmode(vcpu))               ? X86EMUL_MODE_REAL :
5391                      (ctxt->eflags & X86_EFLAGS_VM)     ? X86EMUL_MODE_VM86 :
5392                      (cs_l && is_long_mode(vcpu))       ? X86EMUL_MODE_PROT64 :
5393                      cs_db                              ? X86EMUL_MODE_PROT32 :
5394                                                           X86EMUL_MODE_PROT16;
5395         BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
5396         BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
5397         BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
5398 
5399         init_decode_cache(ctxt);
5400         vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5401 }
5402 
5403 int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
5404 {
5405         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5406         int ret;
5407 
5408         init_emulate_ctxt(vcpu);
5409 
5410         ctxt->op_bytes = 2;
5411         ctxt->ad_bytes = 2;
5412         ctxt->_eip = ctxt->eip + inc_eip;
5413         ret = emulate_int_real(ctxt, irq);
5414 
5415         if (ret != X86EMUL_CONTINUE)
5416                 return EMULATE_FAIL;
5417 
5418         ctxt->eip = ctxt->_eip;
5419         kvm_rip_write(vcpu, ctxt->eip);
5420         kvm_set_rflags(vcpu, ctxt->eflags);
5421 
5422         if (irq == NMI_VECTOR)
5423                 vcpu->arch.nmi_pending = 0;
5424         else
5425                 vcpu->arch.interrupt.pending = false;
5426 
5427         return EMULATE_DONE;
5428 }
5429 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
5430 
5431 static int handle_emulation_failure(struct kvm_vcpu *vcpu)
5432 {
5433         int r = EMULATE_DONE;
5434 
5435         ++vcpu->stat.insn_emulation_fail;
5436         trace_kvm_emulate_insn_failed(vcpu);
5437         if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
5438                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5439                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5440                 vcpu->run->internal.ndata = 0;
5441                 r = EMULATE_USER_EXIT;
5442         }
5443         kvm_queue_exception(vcpu, UD_VECTOR);
5444 
5445         return r;
5446 }
5447 
5448 static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
5449                                   bool write_fault_to_shadow_pgtable,
5450                                   int emulation_type)
5451 {
5452         gpa_t gpa = cr2;
5453         kvm_pfn_t pfn;
5454 
5455         if (emulation_type & EMULTYPE_NO_REEXECUTE)
5456                 return false;
5457 
5458         if (!vcpu->arch.mmu.direct_map) {
5459                 /*
5460                  * Write permission should be allowed since only
5461                  * write access need to be emulated.
5462                  */
5463                 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5464 
5465                 /*
5466                  * If the mapping is invalid in guest, let cpu retry
5467                  * it to generate fault.
5468                  */
5469                 if (gpa == UNMAPPED_GVA)
5470                         return true;
5471         }
5472 
5473         /*
5474          * Do not retry the unhandleable instruction if it faults on the
5475          * readonly host memory, otherwise it will goto a infinite loop:
5476          * retry instruction -> write #PF -> emulation fail -> retry
5477          * instruction -> ...
5478          */
5479         pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
5480 
5481         /*
5482          * If the instruction failed on the error pfn, it can not be fixed,
5483          * report the error to userspace.
5484          */
5485         if (is_error_noslot_pfn(pfn))
5486                 return false;
5487 
5488         kvm_release_pfn_clean(pfn);
5489 
5490         /* The instructions are well-emulated on direct mmu. */
5491         if (vcpu->arch.mmu.direct_map) {
5492                 unsigned int indirect_shadow_pages;
5493 
5494                 spin_lock(&vcpu->kvm->mmu_lock);
5495                 indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
5496                 spin_unlock(&vcpu->kvm->mmu_lock);
5497 
5498                 if (indirect_shadow_pages)
5499                         kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5500 
5501                 return true;
5502         }
5503 
5504         /*
5505          * if emulation was due to access to shadowed page table
5506          * and it failed try to unshadow page and re-enter the
5507          * guest to let CPU execute the instruction.
5508          */
5509         kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5510 
5511         /*
5512          * If the access faults on its page table, it can not
5513          * be fixed by unprotecting shadow page and it should
5514          * be reported to userspace.
5515          */
5516         return !write_fault_to_shadow_pgtable;
5517 }
5518 
5519 static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
5520                               unsigned long cr2,  int emulation_type)
5521 {
5522         struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
5523         unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
5524 
5525         last_retry_eip = vcpu->arch.last_retry_eip;
5526         last_retry_addr = vcpu->arch.last_retry_addr;
5527 
5528         /*
5529          * If the emulation is caused by #PF and it is non-page_table
5530          * writing instruction, it means the VM-EXIT is caused by shadow
5531          * page protected, we can zap the shadow page and retry this
5532          * instruction directly.
5533          *
5534          * Note: if the guest uses a non-page-table modifying instruction
5535          * on the PDE that points to the instruction, then we will unmap
5536          * the instruction and go to an infinite loop. So, we cache the
5537          * last retried eip and the last fault address, if we meet the eip
5538          * and the address again, we can break out of the potential infinite
5539          * loop.
5540          */
5541         vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
5542 
5543         if (!(emulation_type & EMULTYPE_RETRY))
5544                 return false;
5545 
5546         if (x86_page_table_writing_insn(ctxt))
5547                 return false;
5548 
5549         if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
5550                 return false;
5551 
5552         vcpu->arch.last_retry_eip = ctxt->eip;
5553         vcpu->arch.last_retry_addr = cr2;
5554 
5555         if (!vcpu->arch.mmu.direct_map)
5556                 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
5557 
5558         kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
5559 
5560         return true;
5561 }
5562 
5563 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
5564 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
5565 
5566 static void kvm_smm_changed(struct kvm_vcpu *vcpu)
5567 {
5568         if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
5569                 /* This is a good place to trace that we are exiting SMM.  */
5570                 trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
5571 
5572                 /* Process a latched INIT or SMI, if any.  */
5573                 kvm_make_request(KVM_REQ_EVENT, vcpu);
5574         }
5575 
5576         kvm_mmu_reset_context(vcpu);
5577 }
5578 
5579 static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags)
5580 {
5581         unsigned changed = vcpu->arch.hflags ^ emul_flags;
5582 
5583         vcpu->arch.hflags = emul_flags;
5584 
5585         if (changed & HF_SMM_MASK)
5586                 kvm_smm_changed(vcpu);
5587 }
5588 
5589 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
5590                                 unsigned long *db)
5591 {
5592         u32 dr6 = 0;
5593         int i;
5594         u32 enable, rwlen;
5595 
5596         enable = dr7;
5597         rwlen = dr7 >> 16;
5598         for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
5599                 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
5600                         dr6 |= (1 << i);
5601         return dr6;
5602 }
5603 
5604 static void kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu, int *r)
5605 {
5606         struct kvm_run *kvm_run = vcpu->run;
5607 
5608         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
5609                 kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
5610                 kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
5611                 kvm_run->debug.arch.exception = DB_VECTOR;
5612                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5613                 *r = EMULATE_USER_EXIT;
5614         } else {
5615                 /*
5616                  * "Certain debug exceptions may clear bit 0-3.  The
5617                  * remaining contents of the DR6 register are never
5618                  * cleared by the processor".
5619                  */
5620                 vcpu->arch.dr6 &= ~15;
5621                 vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
5622                 kvm_queue_exception(vcpu, DB_VECTOR);
5623         }
5624 }
5625 
5626 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
5627 {
5628         unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
5629         int r = EMULATE_DONE;
5630 
5631         kvm_x86_ops->skip_emulated_instruction(vcpu);
5632 
5633         /*
5634          * rflags is the old, "raw" value of the flags.  The new value has
5635          * not been saved yet.
5636          *
5637          * This is correct even for TF set by the guest, because "the
5638          * processor will not generate this exception after the instruction
5639          * that sets the TF flag".
5640          */
5641         if (unlikely(rflags & X86_EFLAGS_TF))
5642                 kvm_vcpu_do_singlestep(vcpu, &r);
5643         return r == EMULATE_DONE;
5644 }
5645 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
5646 
5647 static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
5648 {
5649         if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
5650             (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
5651                 struct kvm_run *kvm_run = vcpu->run;
5652                 unsigned long eip = kvm_get_linear_rip(vcpu);
5653                 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5654                                            vcpu->arch.guest_debug_dr7,
5655                                            vcpu->arch.eff_db);
5656 
5657                 if (dr6 != 0) {
5658                         kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
5659                         kvm_run->debug.arch.pc = eip;
5660                         kvm_run->debug.arch.exception = DB_VECTOR;
5661                         kvm_run->exit_reason = KVM_EXIT_DEBUG;
5662                         *r = EMULATE_USER_EXIT;
5663                         return true;
5664                 }
5665         }
5666 
5667         if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
5668             !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
5669                 unsigned long eip = kvm_get_linear_rip(vcpu);
5670                 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
5671                                            vcpu->arch.dr7,
5672                                            vcpu->arch.db);
5673 
5674                 if (dr6 != 0) {
5675                         vcpu->arch.dr6 &= ~15;
5676                         vcpu->arch.dr6 |= dr6 | DR6_RTM;
5677                         kvm_queue_exception(vcpu, DB_VECTOR);
5678                         *r = EMULATE_DONE;
5679                         return true;
5680                 }
5681         }
5682 
5683         return false;
5684 }
5685 
5686 int x86_emulate_instruction(struct kvm_vcpu *vcpu,
5687                             unsigned long cr2,
5688                             int emulation_type,
5689                             void *insn,
5690                             int insn_len)
5691 {
5692         int r;
5693         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
5694         bool writeback = true;
5695         bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
5696 
5697         /*
5698          * Clear write_fault_to_shadow_pgtable here to ensure it is
5699          * never reused.
5700          */
5701         vcpu->arch.write_fault_to_shadow_pgtable = false;
5702         kvm_clear_exception_queue(vcpu);
5703 
5704         if (!(emulation_type & EMULTYPE_NO_DECODE)) {
5705                 init_emulate_ctxt(vcpu);
5706 
5707                 /*
5708                  * We will reenter on the same instruction since
5709                  * we do not set complete_userspace_io.  This does not
5710                  * handle watchpoints yet, those would be handled in
5711                  * the emulate_ops.
5712                  */
5713                 if (kvm_vcpu_check_breakpoint(vcpu, &r))
5714                         return r;
5715 
5716                 ctxt->interruptibility = 0;
5717                 ctxt->have_exception = false;
5718                 ctxt->exception.vector = -1;
5719                 ctxt->perm_ok = false;
5720 
5721                 ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
5722 
5723                 r = x86_decode_insn(ctxt, insn, insn_len);
5724 
5725                 trace_kvm_emulate_insn_start(vcpu);
5726                 ++vcpu->stat.insn_emulation;
5727                 if (r != EMULATION_OK)  {
5728                         if (emulation_type & EMULTYPE_TRAP_UD)
5729                                 return EMULATE_FAIL;
5730                         if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5731                                                 emulation_type))
5732                                 return EMULATE_DONE;
5733                         if (ctxt->have_exception && inject_emulated_exception(vcpu))
5734                                 return EMULATE_DONE;
5735                         if (emulation_type & EMULTYPE_SKIP)
5736                                 return EMULATE_FAIL;
5737                         return handle_emulation_failure(vcpu);
5738                 }
5739         }
5740 
5741         if (emulation_type & EMULTYPE_SKIP) {
5742                 kvm_rip_write(vcpu, ctxt->_eip);
5743                 if (ctxt->eflags & X86_EFLAGS_RF)
5744                         kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
5745                 return EMULATE_DONE;
5746         }
5747 
5748         if (retry_instruction(ctxt, cr2, emulation_type))
5749                 return EMULATE_DONE;
5750 
5751         /* this is needed for vmware backdoor interface to work since it
5752            changes registers values  during IO operation */
5753         if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
5754                 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
5755                 emulator_invalidate_register_cache(ctxt);
5756         }
5757 
5758 restart:
5759         /* Save the faulting GPA (cr2) in the address field */
5760         ctxt->exception.address = cr2;
5761 
5762         r = x86_emulate_insn(ctxt);
5763 
5764         if (r == EMULATION_INTERCEPTED)
5765                 return EMULATE_DONE;
5766 
5767         if (r == EMULATION_FAILED) {
5768                 if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
5769                                         emulation_type))
5770                         return EMULATE_DONE;
5771 
5772                 return handle_emulation_failure(vcpu);
5773         }
5774 
5775         if (ctxt->have_exception) {
5776                 r = EMULATE_DONE;
5777                 if (inject_emulated_exception(vcpu))
5778                         return r;
5779         } else if (vcpu->arch.pio.count) {
5780                 if (!vcpu->arch.pio.in) {
5781                         /* FIXME: return into emulator if single-stepping.  */
5782                         vcpu->arch.pio.count = 0;
5783                 } else {
5784                         writeback = false;
5785                         vcpu->arch.complete_userspace_io = complete_emulated_pio;
5786                 }
5787                 r = EMULATE_USER_EXIT;
5788         } else if (vcpu->mmio_needed) {
5789                 if (!vcpu->mmio_is_write)
5790                         writeback = false;
5791                 r = EMULATE_USER_EXIT;
5792                 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
5793         } else if (r == EMULATION_RESTART)
5794                 goto restart;
5795         else
5796                 r = EMULATE_DONE;
5797 
5798         if (writeback) {
5799                 unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
5800                 toggle_interruptibility(vcpu, ctxt->interruptibility);
5801                 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
5802                 kvm_rip_write(vcpu, ctxt->eip);
5803                 if (r == EMULATE_DONE &&
5804                     (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
5805                         kvm_vcpu_do_singlestep(vcpu, &r);
5806                 if (!ctxt->have_exception ||
5807                     exception_type(ctxt->exception.vector) == EXCPT_TRAP)
5808                         __kvm_set_rflags(vcpu, ctxt->eflags);
5809 
5810                 /*
5811                  * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
5812                  * do nothing, and it will be requested again as soon as
5813                  * the shadow expires.  But we still need to check here,
5814                  * because POPF has no interrupt shadow.
5815                  */
5816                 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
5817                         kvm_make_request(KVM_REQ_EVENT, vcpu);
5818         } else
5819                 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
5820 
5821         return r;
5822 }
5823 EXPORT_SYMBOL_GPL(x86_emulate_instruction);
5824 
5825 int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
5826 {
5827         unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
5828         int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
5829                                             size, port, &val, 1);
5830         /* do not return to emulator after return from userspace */
5831         vcpu->arch.pio.count = 0;
5832         return ret;
5833 }
5834 EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
5835 
5836 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
5837 {
5838         unsigned long val;
5839 
5840         /* We should only ever be called with arch.pio.count equal to 1 */
5841         BUG_ON(vcpu->arch.pio.count != 1);
5842 
5843         /* For size less than 4 we merge, else we zero extend */
5844         val = (vcpu->arch.pio.size < 4) ? kvm_register_read(vcpu, VCPU_REGS_RAX)
5845                                         : 0;
5846 
5847         /*
5848          * Since vcpu->arch.pio.count == 1 let emulator_pio_in_emulated perform
5849          * the copy and tracing
5850          */
5851         emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, vcpu->arch.pio.size,
5852                                  vcpu->arch.pio.port, &val, 1);
5853         kvm_register_write(vcpu, VCPU_REGS_RAX, val);
5854 
5855         return 1;
5856 }
5857 
5858 int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size, unsigned short port)
5859 {
5860         unsigned long val;
5861         int ret;
5862 
5863         /* For size less than 4 we merge, else we zero extend */
5864         val = (size < 4) ? kvm_register_read(vcpu, VCPU_REGS_RAX) : 0;
5865 
5866         ret = emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, size, port,
5867                                        &val, 1);
5868         if (ret) {
5869                 kvm_register_write(vcpu, VCPU_REGS_RAX, val);
5870                 return ret;
5871         }
5872 
5873         vcpu->arch.complete_userspace_io = complete_fast_pio_in;
5874 
5875         return 0;
5876 }
5877 EXPORT_SYMBOL_GPL(kvm_fast_pio_in);
5878 
5879 static int kvmclock_cpu_down_prep(unsigned int cpu)
5880 {
5881         __this_cpu_write(cpu_tsc_khz, 0);
5882         return 0;
5883 }
5884 
5885 static void tsc_khz_changed(void *data)
5886 {
5887         struct cpufreq_freqs *freq = data;
5888         unsigned long khz = 0;
5889 
5890         if (data)
5891                 khz = freq->new;
5892         else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
5893                 khz = cpufreq_quick_get(raw_smp_processor_id());
5894         if (!khz)
5895                 khz = tsc_khz;
5896         __this_cpu_write(cpu_tsc_khz, khz);
5897 }
5898 
5899 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
5900                                      void *data)
5901 {
5902         struct cpufreq_freqs *freq = data;
5903         struct kvm *kvm;
5904         struct kvm_vcpu *vcpu;
5905         int i, send_ipi = 0;
5906 
5907         /*
5908          * We allow guests to temporarily run on slowing clocks,
5909          * provided we notify them after, or to run on accelerating
5910          * clocks, provided we notify them before.  Thus time never
5911          * goes backwards.
5912          *
5913          * However, we have a problem.  We can't atomically update
5914          * the frequency of a given CPU from this function; it is
5915          * merely a notifier, which can be called from any CPU.
5916          * Changing the TSC frequency at arbitrary points in time
5917          * requires a recomputation of local variables related to
5918          * the TSC for each VCPU.  We must flag these local variables
5919          * to be updated and be sure the update takes place with the
5920          * new frequency before any guests proceed.
5921          *
5922          * Unfortunately, the combination of hotplug CPU and frequency
5923          * change creates an intractable locking scenario; the order
5924          * of when these callouts happen is undefined with respect to
5925          * CPU hotplug, and they can race with each other.  As such,
5926          * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
5927          * undefined; you can actually have a CPU frequency change take
5928          * place in between the computation of X and the setting of the
5929          * variable.  To protect against this problem, all updates of
5930          * the per_cpu tsc_khz variable are done in an interrupt
5931          * protected IPI, and all callers wishing to update the value
5932          * must wait for a synchronous IPI to complete (which is trivial
5933          * if the caller is on the CPU already).  This establishes the
5934          * necessary total order on variable updates.
5935          *
5936          * Note that because a guest time update may take place
5937          * anytime after the setting of the VCPU's request bit, the
5938          * correct TSC value must be set before the request.  However,
5939          * to ensure the update actually makes it to any guest which
5940          * starts running in hardware virtualization between the set
5941          * and the acquisition of the spinlock, we must also ping the
5942          * CPU after setting the request bit.
5943          *
5944          */
5945 
5946         if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
5947                 return 0;
5948         if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
5949                 return 0;
5950 
5951         smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5952 
5953         spin_lock(&kvm_lock);
5954         list_for_each_entry(kvm, &vm_list, vm_list) {
5955                 kvm_for_each_vcpu(i, vcpu, kvm) {
5956                         if (vcpu->cpu != freq->cpu)
5957                                 continue;
5958                         kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5959                         if (vcpu->cpu != smp_processor_id())
5960                                 send_ipi = 1;
5961                 }
5962         }
5963         spin_unlock(&kvm_lock);
5964 
5965         if (freq->old < freq->new && send_ipi) {
5966                 /*
5967                  * We upscale the frequency.  Must make the guest
5968                  * doesn't see old kvmclock values while running with
5969                  * the new frequency, otherwise we risk the guest sees
5970                  * time go backwards.
5971                  *
5972                  * In case we update the frequency for another cpu
5973                  * (which might be in guest context) send an interrupt
5974                  * to kick the cpu out of guest context.  Next time
5975                  * guest context is entered kvmclock will be updated,
5976                  * so the guest will not see stale values.
5977                  */
5978                 smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
5979         }
5980         return 0;
5981 }
5982 
5983 static struct notifier_block kvmclock_cpufreq_notifier_block = {
5984         .notifier_call  = kvmclock_cpufreq_notifier
5985 };
5986 
5987 static int kvmclock_cpu_online(unsigned int cpu)
5988 {
5989         tsc_khz_changed(NULL);
5990         return 0;
5991 }
5992 
5993 static void kvm_timer_init(void)
5994 {
5995         max_tsc_khz = tsc_khz;
5996 
5997         if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
5998 #ifdef CONFIG_CPU_FREQ
5999                 struct cpufreq_policy policy;
6000                 int cpu;
6001 
6002                 memset(&policy, 0, sizeof(policy));
6003                 cpu = get_cpu();
6004                 cpufreq_get_policy(&policy, cpu);
6005                 if (policy.cpuinfo.max_freq)
6006                         max_tsc_khz = policy.cpuinfo.max_freq;
6007                 put_cpu();
6008 #endif
6009                 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
6010                                           CPUFREQ_TRANSITION_NOTIFIER);
6011         }
6012         pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
6013 
6014         cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
6015                           kvmclock_cpu_online, kvmclock_cpu_down_prep);
6016 }
6017 
6018 static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
6019 
6020 int kvm_is_in_guest(void)
6021 {
6022         return __this_cpu_read(current_vcpu) != NULL;
6023 }
6024 
6025 static int kvm_is_user_mode(void)
6026 {
6027         int user_mode = 3;
6028 
6029         if (