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