OSDN Git Service

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