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