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