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

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

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