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