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