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