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