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