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