873602b5edfd2ed5127651329ddd27036e0d00ab
[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
40 #include <asm/uaccess.h>
41 #include <asm/msr.h>
42 #include <asm/desc.h>
43 #include <asm/mtrr.h>
44
45 #define MAX_IO_MSRS 256
46 #define CR0_RESERVED_BITS                                               \
47         (~(unsigned long)(X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS \
48                           | X86_CR0_ET | X86_CR0_NE | X86_CR0_WP | X86_CR0_AM \
49                           | X86_CR0_NW | X86_CR0_CD | X86_CR0_PG))
50 #define CR4_RESERVED_BITS                                               \
51         (~(unsigned long)(X86_CR4_VME | X86_CR4_PVI | X86_CR4_TSD | X86_CR4_DE\
52                           | X86_CR4_PSE | X86_CR4_PAE | X86_CR4_MCE     \
53                           | X86_CR4_PGE | X86_CR4_PCE | X86_CR4_OSFXSR  \
54                           | X86_CR4_OSXMMEXCPT | X86_CR4_VMXE))
55
56 #define CR8_RESERVED_BITS (~(unsigned long)X86_CR8_TPR)
57 /* EFER defaults:
58  * - enable syscall per default because its emulated by KVM
59  * - enable LME and LMA per default on 64 bit KVM
60  */
61 #ifdef CONFIG_X86_64
62 static u64 __read_mostly efer_reserved_bits = 0xfffffffffffffafeULL;
63 #else
64 static u64 __read_mostly efer_reserved_bits = 0xfffffffffffffffeULL;
65 #endif
66
67 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
68 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
69
70 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
71                                     struct kvm_cpuid_entry2 __user *entries);
72 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry(struct kvm_vcpu *vcpu,
73                                               u32 function, u32 index);
74
75 struct kvm_x86_ops *kvm_x86_ops;
76 EXPORT_SYMBOL_GPL(kvm_x86_ops);
77
78 struct kvm_stats_debugfs_item debugfs_entries[] = {
79         { "pf_fixed", VCPU_STAT(pf_fixed) },
80         { "pf_guest", VCPU_STAT(pf_guest) },
81         { "tlb_flush", VCPU_STAT(tlb_flush) },
82         { "invlpg", VCPU_STAT(invlpg) },
83         { "exits", VCPU_STAT(exits) },
84         { "io_exits", VCPU_STAT(io_exits) },
85         { "mmio_exits", VCPU_STAT(mmio_exits) },
86         { "signal_exits", VCPU_STAT(signal_exits) },
87         { "irq_window", VCPU_STAT(irq_window_exits) },
88         { "nmi_window", VCPU_STAT(nmi_window_exits) },
89         { "halt_exits", VCPU_STAT(halt_exits) },
90         { "halt_wakeup", VCPU_STAT(halt_wakeup) },
91         { "hypercalls", VCPU_STAT(hypercalls) },
92         { "request_irq", VCPU_STAT(request_irq_exits) },
93         { "request_nmi", VCPU_STAT(request_nmi_exits) },
94         { "irq_exits", VCPU_STAT(irq_exits) },
95         { "host_state_reload", VCPU_STAT(host_state_reload) },
96         { "efer_reload", VCPU_STAT(efer_reload) },
97         { "fpu_reload", VCPU_STAT(fpu_reload) },
98         { "insn_emulation", VCPU_STAT(insn_emulation) },
99         { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
100         { "irq_injections", VCPU_STAT(irq_injections) },
101         { "nmi_injections", VCPU_STAT(nmi_injections) },
102         { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
103         { "mmu_pte_write", VM_STAT(mmu_pte_write) },
104         { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
105         { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
106         { "mmu_flooded", VM_STAT(mmu_flooded) },
107         { "mmu_recycled", VM_STAT(mmu_recycled) },
108         { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
109         { "mmu_unsync", VM_STAT(mmu_unsync) },
110         { "mmu_unsync_global", VM_STAT(mmu_unsync_global) },
111         { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
112         { "largepages", VM_STAT(lpages) },
113         { NULL }
114 };
115
116 unsigned long segment_base(u16 selector)
117 {
118         struct descriptor_table gdt;
119         struct desc_struct *d;
120         unsigned long table_base;
121         unsigned long v;
122
123         if (selector == 0)
124                 return 0;
125
126         asm("sgdt %0" : "=m"(gdt));
127         table_base = gdt.base;
128
129         if (selector & 4) {           /* from ldt */
130                 u16 ldt_selector;
131
132                 asm("sldt %0" : "=g"(ldt_selector));
133                 table_base = segment_base(ldt_selector);
134         }
135         d = (struct desc_struct *)(table_base + (selector & ~7));
136         v = d->base0 | ((unsigned long)d->base1 << 16) |
137                 ((unsigned long)d->base2 << 24);
138 #ifdef CONFIG_X86_64
139         if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
140                 v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
141 #endif
142         return v;
143 }
144 EXPORT_SYMBOL_GPL(segment_base);
145
146 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
147 {
148         if (irqchip_in_kernel(vcpu->kvm))
149                 return vcpu->arch.apic_base;
150         else
151                 return vcpu->arch.apic_base;
152 }
153 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
154
155 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
156 {
157         /* TODO: reserve bits check */
158         if (irqchip_in_kernel(vcpu->kvm))
159                 kvm_lapic_set_base(vcpu, data);
160         else
161                 vcpu->arch.apic_base = data;
162 }
163 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
164
165 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
166 {
167         WARN_ON(vcpu->arch.exception.pending);
168         vcpu->arch.exception.pending = true;
169         vcpu->arch.exception.has_error_code = false;
170         vcpu->arch.exception.nr = nr;
171 }
172 EXPORT_SYMBOL_GPL(kvm_queue_exception);
173
174 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, unsigned long addr,
175                            u32 error_code)
176 {
177         ++vcpu->stat.pf_guest;
178
179         if (vcpu->arch.exception.pending) {
180                 if (vcpu->arch.exception.nr == PF_VECTOR) {
181                         printk(KERN_DEBUG "kvm: inject_page_fault:"
182                                         " double fault 0x%lx\n", addr);
183                         vcpu->arch.exception.nr = DF_VECTOR;
184                         vcpu->arch.exception.error_code = 0;
185                 } else if (vcpu->arch.exception.nr == DF_VECTOR) {
186                         /* triple fault -> shutdown */
187                         set_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests);
188                 }
189                 return;
190         }
191         vcpu->arch.cr2 = addr;
192         kvm_queue_exception_e(vcpu, PF_VECTOR, error_code);
193 }
194
195 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
196 {
197         vcpu->arch.nmi_pending = 1;
198 }
199 EXPORT_SYMBOL_GPL(kvm_inject_nmi);
200
201 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
202 {
203         WARN_ON(vcpu->arch.exception.pending);
204         vcpu->arch.exception.pending = true;
205         vcpu->arch.exception.has_error_code = true;
206         vcpu->arch.exception.nr = nr;
207         vcpu->arch.exception.error_code = error_code;
208 }
209 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
210
211 static void __queue_exception(struct kvm_vcpu *vcpu)
212 {
213         kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
214                                      vcpu->arch.exception.has_error_code,
215                                      vcpu->arch.exception.error_code);
216 }
217
218 /*
219  * Load the pae pdptrs.  Return true is they are all valid.
220  */
221 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
222 {
223         gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
224         unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
225         int i;
226         int ret;
227         u64 pdpte[ARRAY_SIZE(vcpu->arch.pdptrs)];
228
229         ret = kvm_read_guest_page(vcpu->kvm, pdpt_gfn, pdpte,
230                                   offset * sizeof(u64), sizeof(pdpte));
231         if (ret < 0) {
232                 ret = 0;
233                 goto out;
234         }
235         for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
236                 if ((pdpte[i] & 1) && (pdpte[i] & 0xfffffff0000001e6ull)) {
237                         ret = 0;
238                         goto out;
239                 }
240         }
241         ret = 1;
242
243         memcpy(vcpu->arch.pdptrs, pdpte, sizeof(vcpu->arch.pdptrs));
244 out:
245
246         return ret;
247 }
248 EXPORT_SYMBOL_GPL(load_pdptrs);
249
250 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
251 {
252         u64 pdpte[ARRAY_SIZE(vcpu->arch.pdptrs)];
253         bool changed = true;
254         int r;
255
256         if (is_long_mode(vcpu) || !is_pae(vcpu))
257                 return false;
258
259         r = kvm_read_guest(vcpu->kvm, vcpu->arch.cr3 & ~31u, pdpte, sizeof(pdpte));
260         if (r < 0)
261                 goto out;
262         changed = memcmp(pdpte, vcpu->arch.pdptrs, sizeof(pdpte)) != 0;
263 out:
264
265         return changed;
266 }
267
268 void kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
269 {
270         if (cr0 & CR0_RESERVED_BITS) {
271                 printk(KERN_DEBUG "set_cr0: 0x%lx #GP, reserved bits 0x%lx\n",
272                        cr0, vcpu->arch.cr0);
273                 kvm_inject_gp(vcpu, 0);
274                 return;
275         }
276
277         if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD)) {
278                 printk(KERN_DEBUG "set_cr0: #GP, CD == 0 && NW == 1\n");
279                 kvm_inject_gp(vcpu, 0);
280                 return;
281         }
282
283         if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE)) {
284                 printk(KERN_DEBUG "set_cr0: #GP, set PG flag "
285                        "and a clear PE flag\n");
286                 kvm_inject_gp(vcpu, 0);
287                 return;
288         }
289
290         if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
291 #ifdef CONFIG_X86_64
292                 if ((vcpu->arch.shadow_efer & EFER_LME)) {
293                         int cs_db, cs_l;
294
295                         if (!is_pae(vcpu)) {
296                                 printk(KERN_DEBUG "set_cr0: #GP, start paging "
297                                        "in long mode while PAE is disabled\n");
298                                 kvm_inject_gp(vcpu, 0);
299                                 return;
300                         }
301                         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
302                         if (cs_l) {
303                                 printk(KERN_DEBUG "set_cr0: #GP, start paging "
304                                        "in long mode while CS.L == 1\n");
305                                 kvm_inject_gp(vcpu, 0);
306                                 return;
307
308                         }
309                 } else
310 #endif
311                 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.cr3)) {
312                         printk(KERN_DEBUG "set_cr0: #GP, pdptrs "
313                                "reserved bits\n");
314                         kvm_inject_gp(vcpu, 0);
315                         return;
316                 }
317
318         }
319
320         kvm_x86_ops->set_cr0(vcpu, cr0);
321         vcpu->arch.cr0 = cr0;
322
323         kvm_mmu_sync_global(vcpu);
324         kvm_mmu_reset_context(vcpu);
325         return;
326 }
327 EXPORT_SYMBOL_GPL(kvm_set_cr0);
328
329 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
330 {
331         kvm_set_cr0(vcpu, (vcpu->arch.cr0 & ~0x0ful) | (msw & 0x0f));
332         KVMTRACE_1D(LMSW, vcpu,
333                     (u32)((vcpu->arch.cr0 & ~0x0ful) | (msw & 0x0f)),
334                     handler);
335 }
336 EXPORT_SYMBOL_GPL(kvm_lmsw);
337
338 void kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
339 {
340         if (cr4 & CR4_RESERVED_BITS) {
341                 printk(KERN_DEBUG "set_cr4: #GP, reserved bits\n");
342                 kvm_inject_gp(vcpu, 0);
343                 return;
344         }
345
346         if (is_long_mode(vcpu)) {
347                 if (!(cr4 & X86_CR4_PAE)) {
348                         printk(KERN_DEBUG "set_cr4: #GP, clearing PAE while "
349                                "in long mode\n");
350                         kvm_inject_gp(vcpu, 0);
351                         return;
352                 }
353         } else if (is_paging(vcpu) && !is_pae(vcpu) && (cr4 & X86_CR4_PAE)
354                    && !load_pdptrs(vcpu, vcpu->arch.cr3)) {
355                 printk(KERN_DEBUG "set_cr4: #GP, pdptrs reserved bits\n");
356                 kvm_inject_gp(vcpu, 0);
357                 return;
358         }
359
360         if (cr4 & X86_CR4_VMXE) {
361                 printk(KERN_DEBUG "set_cr4: #GP, setting VMXE\n");
362                 kvm_inject_gp(vcpu, 0);
363                 return;
364         }
365         kvm_x86_ops->set_cr4(vcpu, cr4);
366         vcpu->arch.cr4 = cr4;
367         vcpu->arch.mmu.base_role.cr4_pge = !!(cr4 & X86_CR4_PGE);
368         kvm_mmu_sync_global(vcpu);
369         kvm_mmu_reset_context(vcpu);
370 }
371 EXPORT_SYMBOL_GPL(kvm_set_cr4);
372
373 void kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
374 {
375         if (cr3 == vcpu->arch.cr3 && !pdptrs_changed(vcpu)) {
376                 kvm_mmu_sync_roots(vcpu);
377                 kvm_mmu_flush_tlb(vcpu);
378                 return;
379         }
380
381         if (is_long_mode(vcpu)) {
382                 if (cr3 & CR3_L_MODE_RESERVED_BITS) {
383                         printk(KERN_DEBUG "set_cr3: #GP, reserved bits\n");
384                         kvm_inject_gp(vcpu, 0);
385                         return;
386                 }
387         } else {
388                 if (is_pae(vcpu)) {
389                         if (cr3 & CR3_PAE_RESERVED_BITS) {
390                                 printk(KERN_DEBUG
391                                        "set_cr3: #GP, reserved bits\n");
392                                 kvm_inject_gp(vcpu, 0);
393                                 return;
394                         }
395                         if (is_paging(vcpu) && !load_pdptrs(vcpu, cr3)) {
396                                 printk(KERN_DEBUG "set_cr3: #GP, pdptrs "
397                                        "reserved bits\n");
398                                 kvm_inject_gp(vcpu, 0);
399                                 return;
400                         }
401                 }
402                 /*
403                  * We don't check reserved bits in nonpae mode, because
404                  * this isn't enforced, and VMware depends on this.
405                  */
406         }
407
408         /*
409          * Does the new cr3 value map to physical memory? (Note, we
410          * catch an invalid cr3 even in real-mode, because it would
411          * cause trouble later on when we turn on paging anyway.)
412          *
413          * A real CPU would silently accept an invalid cr3 and would
414          * attempt to use it - with largely undefined (and often hard
415          * to debug) behavior on the guest side.
416          */
417         if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
418                 kvm_inject_gp(vcpu, 0);
419         else {
420                 vcpu->arch.cr3 = cr3;
421                 vcpu->arch.mmu.new_cr3(vcpu);
422         }
423 }
424 EXPORT_SYMBOL_GPL(kvm_set_cr3);
425
426 void kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
427 {
428         if (cr8 & CR8_RESERVED_BITS) {
429                 printk(KERN_DEBUG "set_cr8: #GP, reserved bits 0x%lx\n", cr8);
430                 kvm_inject_gp(vcpu, 0);
431                 return;
432         }
433         if (irqchip_in_kernel(vcpu->kvm))
434                 kvm_lapic_set_tpr(vcpu, cr8);
435         else
436                 vcpu->arch.cr8 = cr8;
437 }
438 EXPORT_SYMBOL_GPL(kvm_set_cr8);
439
440 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
441 {
442         if (irqchip_in_kernel(vcpu->kvm))
443                 return kvm_lapic_get_cr8(vcpu);
444         else
445                 return vcpu->arch.cr8;
446 }
447 EXPORT_SYMBOL_GPL(kvm_get_cr8);
448
449 static inline u32 bit(int bitno)
450 {
451         return 1 << (bitno & 31);
452 }
453
454 /*
455  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
456  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
457  *
458  * This list is modified at module load time to reflect the
459  * capabilities of the host cpu.
460  */
461 static u32 msrs_to_save[] = {
462         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
463         MSR_K6_STAR,
464 #ifdef CONFIG_X86_64
465         MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
466 #endif
467         MSR_IA32_TIME_STAMP_COUNTER, MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
468         MSR_IA32_PERF_STATUS, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA
469 };
470
471 static unsigned num_msrs_to_save;
472
473 static u32 emulated_msrs[] = {
474         MSR_IA32_MISC_ENABLE,
475 };
476
477 static void set_efer(struct kvm_vcpu *vcpu, u64 efer)
478 {
479         if (efer & efer_reserved_bits) {
480                 printk(KERN_DEBUG "set_efer: 0x%llx #GP, reserved bits\n",
481                        efer);
482                 kvm_inject_gp(vcpu, 0);
483                 return;
484         }
485
486         if (is_paging(vcpu)
487             && (vcpu->arch.shadow_efer & EFER_LME) != (efer & EFER_LME)) {
488                 printk(KERN_DEBUG "set_efer: #GP, change LME while paging\n");
489                 kvm_inject_gp(vcpu, 0);
490                 return;
491         }
492
493         if (efer & EFER_SVME) {
494                 struct kvm_cpuid_entry2 *feat;
495
496                 feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
497                 if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM))) {
498                         printk(KERN_DEBUG "set_efer: #GP, enable SVM w/o SVM\n");
499                         kvm_inject_gp(vcpu, 0);
500                         return;
501                 }
502         }
503
504         kvm_x86_ops->set_efer(vcpu, efer);
505
506         efer &= ~EFER_LMA;
507         efer |= vcpu->arch.shadow_efer & EFER_LMA;
508
509         vcpu->arch.shadow_efer = efer;
510 }
511
512 void kvm_enable_efer_bits(u64 mask)
513 {
514        efer_reserved_bits &= ~mask;
515 }
516 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
517
518
519 /*
520  * Writes msr value into into the appropriate "register".
521  * Returns 0 on success, non-0 otherwise.
522  * Assumes vcpu_load() was already called.
523  */
524 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
525 {
526         return kvm_x86_ops->set_msr(vcpu, msr_index, data);
527 }
528
529 /*
530  * Adapt set_msr() to msr_io()'s calling convention
531  */
532 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
533 {
534         return kvm_set_msr(vcpu, index, *data);
535 }
536
537 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
538 {
539         static int version;
540         struct pvclock_wall_clock wc;
541         struct timespec now, sys, boot;
542
543         if (!wall_clock)
544                 return;
545
546         version++;
547
548         kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
549
550         /*
551          * The guest calculates current wall clock time by adding
552          * system time (updated by kvm_write_guest_time below) to the
553          * wall clock specified here.  guest system time equals host
554          * system time for us, thus we must fill in host boot time here.
555          */
556         now = current_kernel_time();
557         ktime_get_ts(&sys);
558         boot = ns_to_timespec(timespec_to_ns(&now) - timespec_to_ns(&sys));
559
560         wc.sec = boot.tv_sec;
561         wc.nsec = boot.tv_nsec;
562         wc.version = version;
563
564         kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
565
566         version++;
567         kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
568 }
569
570 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
571 {
572         uint32_t quotient, remainder;
573
574         /* Don't try to replace with do_div(), this one calculates
575          * "(dividend << 32) / divisor" */
576         __asm__ ( "divl %4"
577                   : "=a" (quotient), "=d" (remainder)
578                   : "0" (0), "1" (dividend), "r" (divisor) );
579         return quotient;
580 }
581
582 static void kvm_set_time_scale(uint32_t tsc_khz, struct pvclock_vcpu_time_info *hv_clock)
583 {
584         uint64_t nsecs = 1000000000LL;
585         int32_t  shift = 0;
586         uint64_t tps64;
587         uint32_t tps32;
588
589         tps64 = tsc_khz * 1000LL;
590         while (tps64 > nsecs*2) {
591                 tps64 >>= 1;
592                 shift--;
593         }
594
595         tps32 = (uint32_t)tps64;
596         while (tps32 <= (uint32_t)nsecs) {
597                 tps32 <<= 1;
598                 shift++;
599         }
600
601         hv_clock->tsc_shift = shift;
602         hv_clock->tsc_to_system_mul = div_frac(nsecs, tps32);
603
604         pr_debug("%s: tsc_khz %u, tsc_shift %d, tsc_mul %u\n",
605                  __func__, tsc_khz, hv_clock->tsc_shift,
606                  hv_clock->tsc_to_system_mul);
607 }
608
609 static void kvm_write_guest_time(struct kvm_vcpu *v)
610 {
611         struct timespec ts;
612         unsigned long flags;
613         struct kvm_vcpu_arch *vcpu = &v->arch;
614         void *shared_kaddr;
615
616         if ((!vcpu->time_page))
617                 return;
618
619         if (unlikely(vcpu->hv_clock_tsc_khz != tsc_khz)) {
620                 kvm_set_time_scale(tsc_khz, &vcpu->hv_clock);
621                 vcpu->hv_clock_tsc_khz = tsc_khz;
622         }
623
624         /* Keep irq disabled to prevent changes to the clock */
625         local_irq_save(flags);
626         kvm_get_msr(v, MSR_IA32_TIME_STAMP_COUNTER,
627                           &vcpu->hv_clock.tsc_timestamp);
628         ktime_get_ts(&ts);
629         local_irq_restore(flags);
630
631         /* With all the info we got, fill in the values */
632
633         vcpu->hv_clock.system_time = ts.tv_nsec +
634                                      (NSEC_PER_SEC * (u64)ts.tv_sec);
635         /*
636          * The interface expects us to write an even number signaling that the
637          * update is finished. Since the guest won't see the intermediate
638          * state, we just increase by 2 at the end.
639          */
640         vcpu->hv_clock.version += 2;
641
642         shared_kaddr = kmap_atomic(vcpu->time_page, KM_USER0);
643
644         memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock,
645                sizeof(vcpu->hv_clock));
646
647         kunmap_atomic(shared_kaddr, KM_USER0);
648
649         mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT);
650 }
651
652 static bool msr_mtrr_valid(unsigned msr)
653 {
654         switch (msr) {
655         case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
656         case MSR_MTRRfix64K_00000:
657         case MSR_MTRRfix16K_80000:
658         case MSR_MTRRfix16K_A0000:
659         case MSR_MTRRfix4K_C0000:
660         case MSR_MTRRfix4K_C8000:
661         case MSR_MTRRfix4K_D0000:
662         case MSR_MTRRfix4K_D8000:
663         case MSR_MTRRfix4K_E0000:
664         case MSR_MTRRfix4K_E8000:
665         case MSR_MTRRfix4K_F0000:
666         case MSR_MTRRfix4K_F8000:
667         case MSR_MTRRdefType:
668         case MSR_IA32_CR_PAT:
669                 return true;
670         case 0x2f8:
671                 return true;
672         }
673         return false;
674 }
675
676 static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
677 {
678         u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
679
680         if (!msr_mtrr_valid(msr))
681                 return 1;
682
683         if (msr == MSR_MTRRdefType) {
684                 vcpu->arch.mtrr_state.def_type = data;
685                 vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
686         } else if (msr == MSR_MTRRfix64K_00000)
687                 p[0] = data;
688         else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
689                 p[1 + msr - MSR_MTRRfix16K_80000] = data;
690         else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
691                 p[3 + msr - MSR_MTRRfix4K_C0000] = data;
692         else if (msr == MSR_IA32_CR_PAT)
693                 vcpu->arch.pat = data;
694         else {  /* Variable MTRRs */
695                 int idx, is_mtrr_mask;
696                 u64 *pt;
697
698                 idx = (msr - 0x200) / 2;
699                 is_mtrr_mask = msr - 0x200 - 2 * idx;
700                 if (!is_mtrr_mask)
701                         pt =
702                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
703                 else
704                         pt =
705                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
706                 *pt = data;
707         }
708
709         kvm_mmu_reset_context(vcpu);
710         return 0;
711 }
712
713 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
714 {
715         switch (msr) {
716         case MSR_EFER:
717                 set_efer(vcpu, data);
718                 break;
719         case MSR_IA32_MC0_STATUS:
720                 pr_unimpl(vcpu, "%s: MSR_IA32_MC0_STATUS 0x%llx, nop\n",
721                        __func__, data);
722                 break;
723         case MSR_IA32_MCG_STATUS:
724                 pr_unimpl(vcpu, "%s: MSR_IA32_MCG_STATUS 0x%llx, nop\n",
725                         __func__, data);
726                 break;
727         case MSR_IA32_MCG_CTL:
728                 pr_unimpl(vcpu, "%s: MSR_IA32_MCG_CTL 0x%llx, nop\n",
729                         __func__, data);
730                 break;
731         case MSR_IA32_DEBUGCTLMSR:
732                 if (!data) {
733                         /* We support the non-activated case already */
734                         break;
735                 } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
736                         /* Values other than LBR and BTF are vendor-specific,
737                            thus reserved and should throw a #GP */
738                         return 1;
739                 }
740                 pr_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
741                         __func__, data);
742                 break;
743         case MSR_IA32_UCODE_REV:
744         case MSR_IA32_UCODE_WRITE:
745                 break;
746         case 0x200 ... 0x2ff:
747                 return set_msr_mtrr(vcpu, msr, data);
748         case MSR_IA32_APICBASE:
749                 kvm_set_apic_base(vcpu, data);
750                 break;
751         case MSR_IA32_MISC_ENABLE:
752                 vcpu->arch.ia32_misc_enable_msr = data;
753                 break;
754         case MSR_KVM_WALL_CLOCK:
755                 vcpu->kvm->arch.wall_clock = data;
756                 kvm_write_wall_clock(vcpu->kvm, data);
757                 break;
758         case MSR_KVM_SYSTEM_TIME: {
759                 if (vcpu->arch.time_page) {
760                         kvm_release_page_dirty(vcpu->arch.time_page);
761                         vcpu->arch.time_page = NULL;
762                 }
763
764                 vcpu->arch.time = data;
765
766                 /* we verify if the enable bit is set... */
767                 if (!(data & 1))
768                         break;
769
770                 /* ...but clean it before doing the actual write */
771                 vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
772
773                 vcpu->arch.time_page =
774                                 gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
775
776                 if (is_error_page(vcpu->arch.time_page)) {
777                         kvm_release_page_clean(vcpu->arch.time_page);
778                         vcpu->arch.time_page = NULL;
779                 }
780
781                 kvm_write_guest_time(vcpu);
782                 break;
783         }
784         default:
785                 pr_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n", msr, data);
786                 return 1;
787         }
788         return 0;
789 }
790 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
791
792
793 /*
794  * Reads an msr value (of 'msr_index') into 'pdata'.
795  * Returns 0 on success, non-0 otherwise.
796  * Assumes vcpu_load() was already called.
797  */
798 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
799 {
800         return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
801 }
802
803 static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
804 {
805         u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
806
807         if (!msr_mtrr_valid(msr))
808                 return 1;
809
810         if (msr == MSR_MTRRdefType)
811                 *pdata = vcpu->arch.mtrr_state.def_type +
812                          (vcpu->arch.mtrr_state.enabled << 10);
813         else if (msr == MSR_MTRRfix64K_00000)
814                 *pdata = p[0];
815         else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
816                 *pdata = p[1 + msr - MSR_MTRRfix16K_80000];
817         else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
818                 *pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
819         else if (msr == MSR_IA32_CR_PAT)
820                 *pdata = vcpu->arch.pat;
821         else {  /* Variable MTRRs */
822                 int idx, is_mtrr_mask;
823                 u64 *pt;
824
825                 idx = (msr - 0x200) / 2;
826                 is_mtrr_mask = msr - 0x200 - 2 * idx;
827                 if (!is_mtrr_mask)
828                         pt =
829                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
830                 else
831                         pt =
832                           (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
833                 *pdata = *pt;
834         }
835
836         return 0;
837 }
838
839 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
840 {
841         u64 data;
842
843         switch (msr) {
844         case 0xc0010010: /* SYSCFG */
845         case 0xc0010015: /* HWCR */
846         case MSR_IA32_PLATFORM_ID:
847         case MSR_IA32_P5_MC_ADDR:
848         case MSR_IA32_P5_MC_TYPE:
849         case MSR_IA32_MC0_CTL:
850         case MSR_IA32_MCG_STATUS:
851         case MSR_IA32_MCG_CAP:
852         case MSR_IA32_MCG_CTL:
853         case MSR_IA32_MC0_MISC:
854         case MSR_IA32_MC0_MISC+4:
855         case MSR_IA32_MC0_MISC+8:
856         case MSR_IA32_MC0_MISC+12:
857         case MSR_IA32_MC0_MISC+16:
858         case MSR_IA32_MC0_MISC+20:
859         case MSR_IA32_UCODE_REV:
860         case MSR_IA32_EBL_CR_POWERON:
861         case MSR_IA32_DEBUGCTLMSR:
862         case MSR_IA32_LASTBRANCHFROMIP:
863         case MSR_IA32_LASTBRANCHTOIP:
864         case MSR_IA32_LASTINTFROMIP:
865         case MSR_IA32_LASTINTTOIP:
866                 data = 0;
867                 break;
868         case MSR_MTRRcap:
869                 data = 0x500 | KVM_NR_VAR_MTRR;
870                 break;
871         case 0x200 ... 0x2ff:
872                 return get_msr_mtrr(vcpu, msr, pdata);
873         case 0xcd: /* fsb frequency */
874                 data = 3;
875                 break;
876         case MSR_IA32_APICBASE:
877                 data = kvm_get_apic_base(vcpu);
878                 break;
879         case MSR_IA32_MISC_ENABLE:
880                 data = vcpu->arch.ia32_misc_enable_msr;
881                 break;
882         case MSR_IA32_PERF_STATUS:
883                 /* TSC increment by tick */
884                 data = 1000ULL;
885                 /* CPU multiplier */
886                 data |= (((uint64_t)4ULL) << 40);
887                 break;
888         case MSR_EFER:
889                 data = vcpu->arch.shadow_efer;
890                 break;
891         case MSR_KVM_WALL_CLOCK:
892                 data = vcpu->kvm->arch.wall_clock;
893                 break;
894         case MSR_KVM_SYSTEM_TIME:
895                 data = vcpu->arch.time;
896                 break;
897         default:
898                 pr_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
899                 return 1;
900         }
901         *pdata = data;
902         return 0;
903 }
904 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
905
906 /*
907  * Read or write a bunch of msrs. All parameters are kernel addresses.
908  *
909  * @return number of msrs set successfully.
910  */
911 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
912                     struct kvm_msr_entry *entries,
913                     int (*do_msr)(struct kvm_vcpu *vcpu,
914                                   unsigned index, u64 *data))
915 {
916         int i;
917
918         vcpu_load(vcpu);
919
920         down_read(&vcpu->kvm->slots_lock);
921         for (i = 0; i < msrs->nmsrs; ++i)
922                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
923                         break;
924         up_read(&vcpu->kvm->slots_lock);
925
926         vcpu_put(vcpu);
927
928         return i;
929 }
930
931 /*
932  * Read or write a bunch of msrs. Parameters are user addresses.
933  *
934  * @return number of msrs set successfully.
935  */
936 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
937                   int (*do_msr)(struct kvm_vcpu *vcpu,
938                                 unsigned index, u64 *data),
939                   int writeback)
940 {
941         struct kvm_msrs msrs;
942         struct kvm_msr_entry *entries;
943         int r, n;
944         unsigned size;
945
946         r = -EFAULT;
947         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
948                 goto out;
949
950         r = -E2BIG;
951         if (msrs.nmsrs >= MAX_IO_MSRS)
952                 goto out;
953
954         r = -ENOMEM;
955         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
956         entries = vmalloc(size);
957         if (!entries)
958                 goto out;
959
960         r = -EFAULT;
961         if (copy_from_user(entries, user_msrs->entries, size))
962                 goto out_free;
963
964         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
965         if (r < 0)
966                 goto out_free;
967
968         r = -EFAULT;
969         if (writeback && copy_to_user(user_msrs->entries, entries, size))
970                 goto out_free;
971
972         r = n;
973
974 out_free:
975         vfree(entries);
976 out:
977         return r;
978 }
979
980 int kvm_dev_ioctl_check_extension(long ext)
981 {
982         int r;
983
984         switch (ext) {
985         case KVM_CAP_IRQCHIP:
986         case KVM_CAP_HLT:
987         case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
988         case KVM_CAP_SET_TSS_ADDR:
989         case KVM_CAP_EXT_CPUID:
990         case KVM_CAP_PIT:
991         case KVM_CAP_NOP_IO_DELAY:
992         case KVM_CAP_MP_STATE:
993         case KVM_CAP_SYNC_MMU:
994                 r = 1;
995                 break;
996         case KVM_CAP_COALESCED_MMIO:
997                 r = KVM_COALESCED_MMIO_PAGE_OFFSET;
998                 break;
999         case KVM_CAP_VAPIC:
1000                 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
1001                 break;
1002         case KVM_CAP_NR_VCPUS:
1003                 r = KVM_MAX_VCPUS;
1004                 break;
1005         case KVM_CAP_NR_MEMSLOTS:
1006                 r = KVM_MEMORY_SLOTS;
1007                 break;
1008         case KVM_CAP_PV_MMU:
1009                 r = !tdp_enabled;
1010                 break;
1011         case KVM_CAP_IOMMU:
1012                 r = iommu_found();
1013                 break;
1014         case KVM_CAP_CLOCKSOURCE:
1015                 r = boot_cpu_has(X86_FEATURE_CONSTANT_TSC);
1016                 break;
1017         default:
1018                 r = 0;
1019                 break;
1020         }
1021         return r;
1022
1023 }
1024
1025 long kvm_arch_dev_ioctl(struct file *filp,
1026                         unsigned int ioctl, unsigned long arg)
1027 {
1028         void __user *argp = (void __user *)arg;
1029         long r;
1030
1031         switch (ioctl) {
1032         case KVM_GET_MSR_INDEX_LIST: {
1033                 struct kvm_msr_list __user *user_msr_list = argp;
1034                 struct kvm_msr_list msr_list;
1035                 unsigned n;
1036
1037                 r = -EFAULT;
1038                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
1039                         goto out;
1040                 n = msr_list.nmsrs;
1041                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
1042                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
1043                         goto out;
1044                 r = -E2BIG;
1045                 if (n < num_msrs_to_save)
1046                         goto out;
1047                 r = -EFAULT;
1048                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
1049                                  num_msrs_to_save * sizeof(u32)))
1050                         goto out;
1051                 if (copy_to_user(user_msr_list->indices
1052                                  + num_msrs_to_save * sizeof(u32),
1053                                  &emulated_msrs,
1054                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
1055                         goto out;
1056                 r = 0;
1057                 break;
1058         }
1059         case KVM_GET_SUPPORTED_CPUID: {
1060                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1061                 struct kvm_cpuid2 cpuid;
1062
1063                 r = -EFAULT;
1064                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1065                         goto out;
1066                 r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
1067                         cpuid_arg->entries);
1068                 if (r)
1069                         goto out;
1070
1071                 r = -EFAULT;
1072                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1073                         goto out;
1074                 r = 0;
1075                 break;
1076         }
1077         default:
1078                 r = -EINVAL;
1079         }
1080 out:
1081         return r;
1082 }
1083
1084 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1085 {
1086         kvm_x86_ops->vcpu_load(vcpu, cpu);
1087         kvm_write_guest_time(vcpu);
1088 }
1089
1090 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
1091 {
1092         kvm_x86_ops->vcpu_put(vcpu);
1093         kvm_put_guest_fpu(vcpu);
1094 }
1095
1096 static int is_efer_nx(void)
1097 {
1098         u64 efer;
1099
1100         rdmsrl(MSR_EFER, efer);
1101         return efer & EFER_NX;
1102 }
1103
1104 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
1105 {
1106         int i;
1107         struct kvm_cpuid_entry2 *e, *entry;
1108
1109         entry = NULL;
1110         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
1111                 e = &vcpu->arch.cpuid_entries[i];
1112                 if (e->function == 0x80000001) {
1113                         entry = e;
1114                         break;
1115                 }
1116         }
1117         if (entry && (entry->edx & (1 << 20)) && !is_efer_nx()) {
1118                 entry->edx &= ~(1 << 20);
1119                 printk(KERN_INFO "kvm: guest NX capability removed\n");
1120         }
1121 }
1122
1123 /* when an old userspace process fills a new kernel module */
1124 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
1125                                     struct kvm_cpuid *cpuid,
1126                                     struct kvm_cpuid_entry __user *entries)
1127 {
1128         int r, i;
1129         struct kvm_cpuid_entry *cpuid_entries;
1130
1131         r = -E2BIG;
1132         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1133                 goto out;
1134         r = -ENOMEM;
1135         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry) * cpuid->nent);
1136         if (!cpuid_entries)
1137                 goto out;
1138         r = -EFAULT;
1139         if (copy_from_user(cpuid_entries, entries,
1140                            cpuid->nent * sizeof(struct kvm_cpuid_entry)))
1141                 goto out_free;
1142         for (i = 0; i < cpuid->nent; i++) {
1143                 vcpu->arch.cpuid_entries[i].function = cpuid_entries[i].function;
1144                 vcpu->arch.cpuid_entries[i].eax = cpuid_entries[i].eax;
1145                 vcpu->arch.cpuid_entries[i].ebx = cpuid_entries[i].ebx;
1146                 vcpu->arch.cpuid_entries[i].ecx = cpuid_entries[i].ecx;
1147                 vcpu->arch.cpuid_entries[i].edx = cpuid_entries[i].edx;
1148                 vcpu->arch.cpuid_entries[i].index = 0;
1149                 vcpu->arch.cpuid_entries[i].flags = 0;
1150                 vcpu->arch.cpuid_entries[i].padding[0] = 0;
1151                 vcpu->arch.cpuid_entries[i].padding[1] = 0;
1152                 vcpu->arch.cpuid_entries[i].padding[2] = 0;
1153         }
1154         vcpu->arch.cpuid_nent = cpuid->nent;
1155         cpuid_fix_nx_cap(vcpu);
1156         r = 0;
1157
1158 out_free:
1159         vfree(cpuid_entries);
1160 out:
1161         return r;
1162 }
1163
1164 static int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
1165                                     struct kvm_cpuid2 *cpuid,
1166                                     struct kvm_cpuid_entry2 __user *entries)
1167 {
1168         int r;
1169
1170         r = -E2BIG;
1171         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1172                 goto out;
1173         r = -EFAULT;
1174         if (copy_from_user(&vcpu->arch.cpuid_entries, entries,
1175                            cpuid->nent * sizeof(struct kvm_cpuid_entry2)))
1176                 goto out;
1177         vcpu->arch.cpuid_nent = cpuid->nent;
1178         return 0;
1179
1180 out:
1181         return r;
1182 }
1183
1184 static int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
1185                                     struct kvm_cpuid2 *cpuid,
1186                                     struct kvm_cpuid_entry2 __user *entries)
1187 {
1188         int r;
1189
1190         r = -E2BIG;
1191         if (cpuid->nent < vcpu->arch.cpuid_nent)
1192                 goto out;
1193         r = -EFAULT;
1194         if (copy_to_user(entries, &vcpu->arch.cpuid_entries,
1195                            vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
1196                 goto out;
1197         return 0;
1198
1199 out:
1200         cpuid->nent = vcpu->arch.cpuid_nent;
1201         return r;
1202 }
1203
1204 static void do_cpuid_1_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1205                           u32 index)
1206 {
1207         entry->function = function;
1208         entry->index = index;
1209         cpuid_count(entry->function, entry->index,
1210                 &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
1211         entry->flags = 0;
1212 }
1213
1214 static void do_cpuid_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1215                          u32 index, int *nent, int maxnent)
1216 {
1217         const u32 kvm_supported_word0_x86_features = bit(X86_FEATURE_FPU) |
1218                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
1219                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
1220                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
1221                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
1222                 bit(X86_FEATURE_SEP) | bit(X86_FEATURE_PGE) |
1223                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
1224                 bit(X86_FEATURE_CLFLSH) | bit(X86_FEATURE_MMX) |
1225                 bit(X86_FEATURE_FXSR) | bit(X86_FEATURE_XMM) |
1226                 bit(X86_FEATURE_XMM2) | bit(X86_FEATURE_SELFSNOOP);
1227         const u32 kvm_supported_word1_x86_features = bit(X86_FEATURE_FPU) |
1228                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
1229                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
1230                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
1231                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
1232                 bit(X86_FEATURE_PGE) |
1233                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
1234                 bit(X86_FEATURE_MMX) | bit(X86_FEATURE_FXSR) |
1235                 bit(X86_FEATURE_SYSCALL) |
1236                 (bit(X86_FEATURE_NX) && is_efer_nx()) |
1237 #ifdef CONFIG_X86_64
1238                 bit(X86_FEATURE_LM) |
1239 #endif
1240                 bit(X86_FEATURE_MMXEXT) |
1241                 bit(X86_FEATURE_3DNOWEXT) |
1242                 bit(X86_FEATURE_3DNOW);
1243         const u32 kvm_supported_word3_x86_features =
1244                 bit(X86_FEATURE_XMM3) | bit(X86_FEATURE_CX16);
1245         const u32 kvm_supported_word6_x86_features =
1246                 bit(X86_FEATURE_LAHF_LM) | bit(X86_FEATURE_CMP_LEGACY) |
1247                 bit(X86_FEATURE_SVM);
1248
1249         /* all func 2 cpuid_count() should be called on the same cpu */
1250         get_cpu();
1251         do_cpuid_1_ent(entry, function, index);
1252         ++*nent;
1253
1254         switch (function) {
1255         case 0:
1256                 entry->eax = min(entry->eax, (u32)0xb);
1257                 break;
1258         case 1:
1259                 entry->edx &= kvm_supported_word0_x86_features;
1260                 entry->ecx &= kvm_supported_word3_x86_features;
1261                 break;
1262         /* function 2 entries are STATEFUL. That is, repeated cpuid commands
1263          * may return different values. This forces us to get_cpu() before
1264          * issuing the first command, and also to emulate this annoying behavior
1265          * in kvm_emulate_cpuid() using KVM_CPUID_FLAG_STATE_READ_NEXT */
1266         case 2: {
1267                 int t, times = entry->eax & 0xff;
1268
1269                 entry->flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1270                 entry->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
1271                 for (t = 1; t < times && *nent < maxnent; ++t) {
1272                         do_cpuid_1_ent(&entry[t], function, 0);
1273                         entry[t].flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1274                         ++*nent;
1275                 }
1276                 break;
1277         }
1278         /* function 4 and 0xb have additional index. */
1279         case 4: {
1280                 int i, cache_type;
1281
1282                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1283                 /* read more entries until cache_type is zero */
1284                 for (i = 1; *nent < maxnent; ++i) {
1285                         cache_type = entry[i - 1].eax & 0x1f;
1286                         if (!cache_type)
1287                                 break;
1288                         do_cpuid_1_ent(&entry[i], function, i);
1289                         entry[i].flags |=
1290                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1291                         ++*nent;
1292                 }
1293                 break;
1294         }
1295         case 0xb: {
1296                 int i, level_type;
1297
1298                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1299                 /* read more entries until level_type is zero */
1300                 for (i = 1; *nent < maxnent; ++i) {
1301                         level_type = entry[i - 1].ecx & 0xff00;
1302                         if (!level_type)
1303                                 break;
1304                         do_cpuid_1_ent(&entry[i], function, i);
1305                         entry[i].flags |=
1306                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1307                         ++*nent;
1308                 }
1309                 break;
1310         }
1311         case 0x80000000:
1312                 entry->eax = min(entry->eax, 0x8000001a);
1313                 break;
1314         case 0x80000001:
1315                 entry->edx &= kvm_supported_word1_x86_features;
1316                 entry->ecx &= kvm_supported_word6_x86_features;
1317                 break;
1318         }
1319         put_cpu();
1320 }
1321
1322 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
1323                                     struct kvm_cpuid_entry2 __user *entries)
1324 {
1325         struct kvm_cpuid_entry2 *cpuid_entries;
1326         int limit, nent = 0, r = -E2BIG;
1327         u32 func;
1328
1329         if (cpuid->nent < 1)
1330                 goto out;
1331         r = -ENOMEM;
1332         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry2) * cpuid->nent);
1333         if (!cpuid_entries)
1334                 goto out;
1335
1336         do_cpuid_ent(&cpuid_entries[0], 0, 0, &nent, cpuid->nent);
1337         limit = cpuid_entries[0].eax;
1338         for (func = 1; func <= limit && nent < cpuid->nent; ++func)
1339                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1340                                 &nent, cpuid->nent);
1341         r = -E2BIG;
1342         if (nent >= cpuid->nent)
1343                 goto out_free;
1344
1345         do_cpuid_ent(&cpuid_entries[nent], 0x80000000, 0, &nent, cpuid->nent);
1346         limit = cpuid_entries[nent - 1].eax;
1347         for (func = 0x80000001; func <= limit && nent < cpuid->nent; ++func)
1348                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1349                                &nent, cpuid->nent);
1350         r = -EFAULT;
1351         if (copy_to_user(entries, cpuid_entries,
1352                         nent * sizeof(struct kvm_cpuid_entry2)))
1353                 goto out_free;
1354         cpuid->nent = nent;
1355         r = 0;
1356
1357 out_free:
1358         vfree(cpuid_entries);
1359 out:
1360         return r;
1361 }
1362
1363 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
1364                                     struct kvm_lapic_state *s)
1365 {
1366         vcpu_load(vcpu);
1367         memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
1368         vcpu_put(vcpu);
1369
1370         return 0;
1371 }
1372
1373 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
1374                                     struct kvm_lapic_state *s)
1375 {
1376         vcpu_load(vcpu);
1377         memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
1378         kvm_apic_post_state_restore(vcpu);
1379         vcpu_put(vcpu);
1380
1381         return 0;
1382 }
1383
1384 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
1385                                     struct kvm_interrupt *irq)
1386 {
1387         if (irq->irq < 0 || irq->irq >= 256)
1388                 return -EINVAL;
1389         if (irqchip_in_kernel(vcpu->kvm))
1390                 return -ENXIO;
1391         vcpu_load(vcpu);
1392
1393         set_bit(irq->irq, vcpu->arch.irq_pending);
1394         set_bit(irq->irq / BITS_PER_LONG, &vcpu->arch.irq_summary);
1395
1396         vcpu_put(vcpu);
1397
1398         return 0;
1399 }
1400
1401 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
1402 {
1403         vcpu_load(vcpu);
1404         kvm_inject_nmi(vcpu);
1405         vcpu_put(vcpu);
1406
1407         return 0;
1408 }
1409
1410 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
1411                                            struct kvm_tpr_access_ctl *tac)
1412 {
1413         if (tac->flags)
1414                 return -EINVAL;
1415         vcpu->arch.tpr_access_reporting = !!tac->enabled;
1416         return 0;
1417 }
1418
1419 long kvm_arch_vcpu_ioctl(struct file *filp,
1420                          unsigned int ioctl, unsigned long arg)
1421 {
1422         struct kvm_vcpu *vcpu = filp->private_data;
1423         void __user *argp = (void __user *)arg;
1424         int r;
1425         struct kvm_lapic_state *lapic = NULL;
1426
1427         switch (ioctl) {
1428         case KVM_GET_LAPIC: {
1429                 lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
1430
1431                 r = -ENOMEM;
1432                 if (!lapic)
1433                         goto out;
1434                 r = kvm_vcpu_ioctl_get_lapic(vcpu, lapic);
1435                 if (r)
1436                         goto out;
1437                 r = -EFAULT;
1438                 if (copy_to_user(argp, lapic, sizeof(struct kvm_lapic_state)))
1439                         goto out;
1440                 r = 0;
1441                 break;
1442         }
1443         case KVM_SET_LAPIC: {
1444                 lapic = kmalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
1445                 r = -ENOMEM;
1446                 if (!lapic)
1447                         goto out;
1448                 r = -EFAULT;
1449                 if (copy_from_user(lapic, argp, sizeof(struct kvm_lapic_state)))
1450                         goto out;
1451                 r = kvm_vcpu_ioctl_set_lapic(vcpu, lapic);
1452                 if (r)
1453                         goto out;
1454                 r = 0;
1455                 break;
1456         }
1457         case KVM_INTERRUPT: {
1458                 struct kvm_interrupt irq;
1459
1460                 r = -EFAULT;
1461                 if (copy_from_user(&irq, argp, sizeof irq))
1462                         goto out;
1463                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
1464                 if (r)
1465                         goto out;
1466                 r = 0;
1467                 break;
1468         }
1469         case KVM_NMI: {
1470                 r = kvm_vcpu_ioctl_nmi(vcpu);
1471                 if (r)
1472                         goto out;
1473                 r = 0;
1474                 break;
1475         }
1476         case KVM_SET_CPUID: {
1477                 struct kvm_cpuid __user *cpuid_arg = argp;
1478                 struct kvm_cpuid cpuid;
1479
1480                 r = -EFAULT;
1481                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1482                         goto out;
1483                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
1484                 if (r)
1485                         goto out;
1486                 break;
1487         }
1488         case KVM_SET_CPUID2: {
1489                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1490                 struct kvm_cpuid2 cpuid;
1491
1492                 r = -EFAULT;
1493                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1494                         goto out;
1495                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
1496                                 cpuid_arg->entries);
1497                 if (r)
1498                         goto out;
1499                 break;
1500         }
1501         case KVM_GET_CPUID2: {
1502                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1503                 struct kvm_cpuid2 cpuid;
1504
1505                 r = -EFAULT;
1506                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1507                         goto out;
1508                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
1509                                 cpuid_arg->entries);
1510                 if (r)
1511                         goto out;
1512                 r = -EFAULT;
1513                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1514                         goto out;
1515                 r = 0;
1516                 break;
1517         }
1518         case KVM_GET_MSRS:
1519                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
1520                 break;
1521         case KVM_SET_MSRS:
1522                 r = msr_io(vcpu, argp, do_set_msr, 0);
1523                 break;
1524         case KVM_TPR_ACCESS_REPORTING: {
1525                 struct kvm_tpr_access_ctl tac;
1526
1527                 r = -EFAULT;
1528                 if (copy_from_user(&tac, argp, sizeof tac))
1529                         goto out;
1530                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
1531                 if (r)
1532                         goto out;
1533                 r = -EFAULT;
1534                 if (copy_to_user(argp, &tac, sizeof tac))
1535                         goto out;
1536                 r = 0;
1537                 break;
1538         };
1539         case KVM_SET_VAPIC_ADDR: {
1540                 struct kvm_vapic_addr va;
1541
1542                 r = -EINVAL;
1543                 if (!irqchip_in_kernel(vcpu->kvm))
1544                         goto out;
1545                 r = -EFAULT;
1546                 if (copy_from_user(&va, argp, sizeof va))
1547                         goto out;
1548                 r = 0;
1549                 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
1550                 break;
1551         }
1552         default:
1553                 r = -EINVAL;
1554         }
1555 out:
1556         if (lapic)
1557                 kfree(lapic);
1558         return r;
1559 }
1560
1561 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
1562 {
1563         int ret;
1564
1565         if (addr > (unsigned int)(-3 * PAGE_SIZE))
1566                 return -1;
1567         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
1568         return ret;
1569 }
1570
1571 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
1572                                           u32 kvm_nr_mmu_pages)
1573 {
1574         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
1575                 return -EINVAL;
1576
1577         down_write(&kvm->slots_lock);
1578
1579         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
1580         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
1581
1582         up_write(&kvm->slots_lock);
1583         return 0;
1584 }
1585
1586 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
1587 {
1588         return kvm->arch.n_alloc_mmu_pages;
1589 }
1590
1591 gfn_t unalias_gfn(struct kvm *kvm, gfn_t gfn)
1592 {
1593         int i;
1594         struct kvm_mem_alias *alias;
1595
1596         for (i = 0; i < kvm->arch.naliases; ++i) {
1597                 alias = &kvm->arch.aliases[i];
1598                 if (gfn >= alias->base_gfn
1599                     && gfn < alias->base_gfn + alias->npages)
1600                         return alias->target_gfn + gfn - alias->base_gfn;
1601         }
1602         return gfn;
1603 }
1604
1605 /*
1606  * Set a new alias region.  Aliases map a portion of physical memory into
1607  * another portion.  This is useful for memory windows, for example the PC
1608  * VGA region.
1609  */
1610 static int kvm_vm_ioctl_set_memory_alias(struct kvm *kvm,
1611                                          struct kvm_memory_alias *alias)
1612 {
1613         int r, n;
1614         struct kvm_mem_alias *p;
1615
1616         r = -EINVAL;
1617         /* General sanity checks */
1618         if (alias->memory_size & (PAGE_SIZE - 1))
1619                 goto out;
1620         if (alias->guest_phys_addr & (PAGE_SIZE - 1))
1621                 goto out;
1622         if (alias->slot >= KVM_ALIAS_SLOTS)
1623                 goto out;
1624         if (alias->guest_phys_addr + alias->memory_size
1625             < alias->guest_phys_addr)
1626                 goto out;
1627         if (alias->target_phys_addr + alias->memory_size
1628             < alias->target_phys_addr)
1629                 goto out;
1630
1631         down_write(&kvm->slots_lock);
1632         spin_lock(&kvm->mmu_lock);
1633
1634         p = &kvm->arch.aliases[alias->slot];
1635         p->base_gfn = alias->guest_phys_addr >> PAGE_SHIFT;
1636         p->npages = alias->memory_size >> PAGE_SHIFT;
1637         p->target_gfn = alias->target_phys_addr >> PAGE_SHIFT;
1638
1639         for (n = KVM_ALIAS_SLOTS; n > 0; --n)
1640                 if (kvm->arch.aliases[n - 1].npages)
1641                         break;
1642         kvm->arch.naliases = n;
1643
1644         spin_unlock(&kvm->mmu_lock);
1645         kvm_mmu_zap_all(kvm);
1646
1647         up_write(&kvm->slots_lock);
1648
1649         return 0;
1650
1651 out:
1652         return r;
1653 }
1654
1655 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1656 {
1657         int r;
1658
1659         r = 0;
1660         switch (chip->chip_id) {
1661         case KVM_IRQCHIP_PIC_MASTER:
1662                 memcpy(&chip->chip.pic,
1663                         &pic_irqchip(kvm)->pics[0],
1664                         sizeof(struct kvm_pic_state));
1665                 break;
1666         case KVM_IRQCHIP_PIC_SLAVE:
1667                 memcpy(&chip->chip.pic,
1668                         &pic_irqchip(kvm)->pics[1],
1669                         sizeof(struct kvm_pic_state));
1670                 break;
1671         case KVM_IRQCHIP_IOAPIC:
1672                 memcpy(&chip->chip.ioapic,
1673                         ioapic_irqchip(kvm),
1674                         sizeof(struct kvm_ioapic_state));
1675                 break;
1676         default:
1677                 r = -EINVAL;
1678                 break;
1679         }
1680         return r;
1681 }
1682
1683 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1684 {
1685         int r;
1686
1687         r = 0;
1688         switch (chip->chip_id) {
1689         case KVM_IRQCHIP_PIC_MASTER:
1690                 memcpy(&pic_irqchip(kvm)->pics[0],
1691                         &chip->chip.pic,
1692                         sizeof(struct kvm_pic_state));
1693                 break;
1694         case KVM_IRQCHIP_PIC_SLAVE:
1695                 memcpy(&pic_irqchip(kvm)->pics[1],
1696                         &chip->chip.pic,
1697                         sizeof(struct kvm_pic_state));
1698                 break;
1699         case KVM_IRQCHIP_IOAPIC:
1700                 memcpy(ioapic_irqchip(kvm),
1701                         &chip->chip.ioapic,
1702                         sizeof(struct kvm_ioapic_state));
1703                 break;
1704         default:
1705                 r = -EINVAL;
1706                 break;
1707         }
1708         kvm_pic_update_irq(pic_irqchip(kvm));
1709         return r;
1710 }
1711
1712 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
1713 {
1714         int r = 0;
1715
1716         memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
1717         return r;
1718 }
1719
1720 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
1721 {
1722         int r = 0;
1723
1724         memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
1725         kvm_pit_load_count(kvm, 0, ps->channels[0].count);
1726         return r;
1727 }
1728
1729 /*
1730  * Get (and clear) the dirty memory log for a memory slot.
1731  */
1732 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1733                                       struct kvm_dirty_log *log)
1734 {
1735         int r;
1736         int n;
1737         struct kvm_memory_slot *memslot;
1738         int is_dirty = 0;
1739
1740         down_write(&kvm->slots_lock);
1741
1742         r = kvm_get_dirty_log(kvm, log, &is_dirty);
1743         if (r)
1744                 goto out;
1745
1746         /* If nothing is dirty, don't bother messing with page tables. */
1747         if (is_dirty) {
1748                 kvm_mmu_slot_remove_write_access(kvm, log->slot);
1749                 kvm_flush_remote_tlbs(kvm);
1750                 memslot = &kvm->memslots[log->slot];
1751                 n = ALIGN(memslot->npages, BITS_PER_LONG) / 8;
1752                 memset(memslot->dirty_bitmap, 0, n);
1753         }
1754         r = 0;
1755 out:
1756         up_write(&kvm->slots_lock);
1757         return r;
1758 }
1759
1760 long kvm_arch_vm_ioctl(struct file *filp,
1761                        unsigned int ioctl, unsigned long arg)
1762 {
1763         struct kvm *kvm = filp->private_data;
1764         void __user *argp = (void __user *)arg;
1765         int r = -EINVAL;
1766         /*
1767          * This union makes it completely explicit to gcc-3.x
1768          * that these two variables' stack usage should be
1769          * combined, not added together.
1770          */
1771         union {
1772                 struct kvm_pit_state ps;
1773                 struct kvm_memory_alias alias;
1774         } u;
1775
1776         switch (ioctl) {
1777         case KVM_SET_TSS_ADDR:
1778                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
1779                 if (r < 0)
1780                         goto out;
1781                 break;
1782         case KVM_SET_MEMORY_REGION: {
1783                 struct kvm_memory_region kvm_mem;
1784                 struct kvm_userspace_memory_region kvm_userspace_mem;
1785
1786                 r = -EFAULT;
1787                 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
1788                         goto out;
1789                 kvm_userspace_mem.slot = kvm_mem.slot;
1790                 kvm_userspace_mem.flags = kvm_mem.flags;
1791                 kvm_userspace_mem.guest_phys_addr = kvm_mem.guest_phys_addr;
1792                 kvm_userspace_mem.memory_size = kvm_mem.memory_size;
1793                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 0);
1794                 if (r)
1795                         goto out;
1796                 break;
1797         }
1798         case KVM_SET_NR_MMU_PAGES:
1799                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
1800                 if (r)
1801                         goto out;
1802                 break;
1803         case KVM_GET_NR_MMU_PAGES:
1804                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
1805                 break;
1806         case KVM_SET_MEMORY_ALIAS:
1807                 r = -EFAULT;
1808                 if (copy_from_user(&u.alias, argp, sizeof(struct kvm_memory_alias)))
1809                         goto out;
1810                 r = kvm_vm_ioctl_set_memory_alias(kvm, &u.alias);
1811                 if (r)
1812                         goto out;
1813                 break;
1814         case KVM_CREATE_IRQCHIP:
1815                 r = -ENOMEM;
1816                 kvm->arch.vpic = kvm_create_pic(kvm);
1817                 if (kvm->arch.vpic) {
1818                         r = kvm_ioapic_init(kvm);
1819                         if (r) {
1820                                 kfree(kvm->arch.vpic);
1821                                 kvm->arch.vpic = NULL;
1822                                 goto out;
1823                         }
1824                 } else
1825                         goto out;
1826                 break;
1827         case KVM_CREATE_PIT:
1828                 r = -ENOMEM;
1829                 kvm->arch.vpit = kvm_create_pit(kvm);
1830                 if (kvm->arch.vpit)
1831                         r = 0;
1832                 break;
1833         case KVM_IRQ_LINE: {
1834                 struct kvm_irq_level irq_event;
1835
1836                 r = -EFAULT;
1837                 if (copy_from_user(&irq_event, argp, sizeof irq_event))
1838                         goto out;
1839                 if (irqchip_in_kernel(kvm)) {
1840                         mutex_lock(&kvm->lock);
1841                         kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
1842                                     irq_event.irq, irq_event.level);
1843                         mutex_unlock(&kvm->lock);
1844                         r = 0;
1845                 }
1846                 break;
1847         }
1848         case KVM_GET_IRQCHIP: {
1849                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1850                 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
1851
1852                 r = -ENOMEM;
1853                 if (!chip)
1854                         goto out;
1855                 r = -EFAULT;
1856                 if (copy_from_user(chip, argp, sizeof *chip))
1857                         goto get_irqchip_out;
1858                 r = -ENXIO;
1859                 if (!irqchip_in_kernel(kvm))
1860                         goto get_irqchip_out;
1861                 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
1862                 if (r)
1863                         goto get_irqchip_out;
1864                 r = -EFAULT;
1865                 if (copy_to_user(argp, chip, sizeof *chip))
1866                         goto get_irqchip_out;
1867                 r = 0;
1868         get_irqchip_out:
1869                 kfree(chip);
1870                 if (r)
1871                         goto out;
1872                 break;
1873         }
1874         case KVM_SET_IRQCHIP: {
1875                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1876                 struct kvm_irqchip *chip = kmalloc(sizeof(*chip), GFP_KERNEL);
1877
1878                 r = -ENOMEM;
1879                 if (!chip)
1880                         goto out;
1881                 r = -EFAULT;
1882                 if (copy_from_user(chip, argp, sizeof *chip))
1883                         goto set_irqchip_out;
1884                 r = -ENXIO;
1885                 if (!irqchip_in_kernel(kvm))
1886                         goto set_irqchip_out;
1887                 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
1888                 if (r)
1889                         goto set_irqchip_out;
1890                 r = 0;
1891         set_irqchip_out:
1892                 kfree(chip);
1893                 if (r)
1894                         goto out;
1895                 break;
1896         }
1897         case KVM_GET_PIT: {
1898                 r = -EFAULT;
1899                 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
1900                         goto out;
1901                 r = -ENXIO;
1902                 if (!kvm->arch.vpit)
1903                         goto out;
1904                 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
1905                 if (r)
1906                         goto out;
1907                 r = -EFAULT;
1908                 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
1909                         goto out;
1910                 r = 0;
1911                 break;
1912         }
1913         case KVM_SET_PIT: {
1914                 r = -EFAULT;
1915                 if (copy_from_user(&u.ps, argp, sizeof u.ps))
1916                         goto out;
1917                 r = -ENXIO;
1918                 if (!kvm->arch.vpit)
1919                         goto out;
1920                 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
1921                 if (r)
1922                         goto out;
1923                 r = 0;
1924                 break;
1925         }
1926         default:
1927                 ;
1928         }
1929 out:
1930         return r;
1931 }
1932
1933 static void kvm_init_msr_list(void)
1934 {
1935         u32 dummy[2];
1936         unsigned i, j;
1937
1938         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
1939                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
1940                         continue;
1941                 if (j < i)
1942                         msrs_to_save[j] = msrs_to_save[i];
1943                 j++;
1944         }
1945         num_msrs_to_save = j;
1946 }
1947
1948 /*
1949  * Only apic need an MMIO device hook, so shortcut now..
1950  */
1951 static struct kvm_io_device *vcpu_find_pervcpu_dev(struct kvm_vcpu *vcpu,
1952                                                 gpa_t addr, int len,
1953                                                 int is_write)
1954 {
1955         struct kvm_io_device *dev;
1956
1957         if (vcpu->arch.apic) {
1958                 dev = &vcpu->arch.apic->dev;
1959                 if (dev->in_range(dev, addr, len, is_write))
1960                         return dev;
1961         }
1962         return NULL;
1963 }
1964
1965
1966 static struct kvm_io_device *vcpu_find_mmio_dev(struct kvm_vcpu *vcpu,
1967                                                 gpa_t addr, int len,
1968                                                 int is_write)
1969 {
1970         struct kvm_io_device *dev;
1971
1972         dev = vcpu_find_pervcpu_dev(vcpu, addr, len, is_write);
1973         if (dev == NULL)
1974                 dev = kvm_io_bus_find_dev(&vcpu->kvm->mmio_bus, addr, len,
1975                                           is_write);
1976         return dev;
1977 }
1978
1979 int emulator_read_std(unsigned long addr,
1980                              void *val,
1981                              unsigned int bytes,
1982                              struct kvm_vcpu *vcpu)
1983 {
1984         void *data = val;
1985         int r = X86EMUL_CONTINUE;
1986
1987         while (bytes) {
1988                 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1989                 unsigned offset = addr & (PAGE_SIZE-1);
1990                 unsigned tocopy = min(bytes, (unsigned)PAGE_SIZE - offset);
1991                 int ret;
1992
1993                 if (gpa == UNMAPPED_GVA) {
1994                         r = X86EMUL_PROPAGATE_FAULT;
1995                         goto out;
1996                 }
1997                 ret = kvm_read_guest(vcpu->kvm, gpa, data, tocopy);
1998                 if (ret < 0) {
1999                         r = X86EMUL_UNHANDLEABLE;
2000                         goto out;
2001                 }
2002
2003                 bytes -= tocopy;
2004                 data += tocopy;
2005                 addr += tocopy;
2006         }
2007 out:
2008         return r;
2009 }
2010 EXPORT_SYMBOL_GPL(emulator_read_std);
2011
2012 static int emulator_read_emulated(unsigned long addr,
2013                                   void *val,
2014                                   unsigned int bytes,
2015                                   struct kvm_vcpu *vcpu)
2016 {
2017         struct kvm_io_device *mmio_dev;
2018         gpa_t                 gpa;
2019
2020         if (vcpu->mmio_read_completed) {
2021                 memcpy(val, vcpu->mmio_data, bytes);
2022                 vcpu->mmio_read_completed = 0;
2023                 return X86EMUL_CONTINUE;
2024         }
2025
2026         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2027
2028         /* For APIC access vmexit */
2029         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
2030                 goto mmio;
2031
2032         if (emulator_read_std(addr, val, bytes, vcpu)
2033                         == X86EMUL_CONTINUE)
2034                 return X86EMUL_CONTINUE;
2035         if (gpa == UNMAPPED_GVA)
2036                 return X86EMUL_PROPAGATE_FAULT;
2037
2038 mmio:
2039         /*
2040          * Is this MMIO handled locally?
2041          */
2042         mutex_lock(&vcpu->kvm->lock);
2043         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa, bytes, 0);
2044         if (mmio_dev) {
2045                 kvm_iodevice_read(mmio_dev, gpa, bytes, val);
2046                 mutex_unlock(&vcpu->kvm->lock);
2047                 return X86EMUL_CONTINUE;
2048         }
2049         mutex_unlock(&vcpu->kvm->lock);
2050
2051         vcpu->mmio_needed = 1;
2052         vcpu->mmio_phys_addr = gpa;
2053         vcpu->mmio_size = bytes;
2054         vcpu->mmio_is_write = 0;
2055
2056         return X86EMUL_UNHANDLEABLE;
2057 }
2058
2059 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
2060                           const void *val, int bytes)
2061 {
2062         int ret;
2063
2064         ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
2065         if (ret < 0)
2066                 return 0;
2067         kvm_mmu_pte_write(vcpu, gpa, val, bytes, 1);
2068         return 1;
2069 }
2070
2071 static int emulator_write_emulated_onepage(unsigned long addr,
2072                                            const void *val,
2073                                            unsigned int bytes,
2074                                            struct kvm_vcpu *vcpu)
2075 {
2076         struct kvm_io_device *mmio_dev;
2077         gpa_t                 gpa;
2078
2079         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2080
2081         if (gpa == UNMAPPED_GVA) {
2082                 kvm_inject_page_fault(vcpu, addr, 2);
2083                 return X86EMUL_PROPAGATE_FAULT;
2084         }
2085
2086         /* For APIC access vmexit */
2087         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
2088                 goto mmio;
2089
2090         if (emulator_write_phys(vcpu, gpa, val, bytes))
2091                 return X86EMUL_CONTINUE;
2092
2093 mmio:
2094         /*
2095          * Is this MMIO handled locally?
2096          */
2097         mutex_lock(&vcpu->kvm->lock);
2098         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa, bytes, 1);
2099         if (mmio_dev) {
2100                 kvm_iodevice_write(mmio_dev, gpa, bytes, val);
2101                 mutex_unlock(&vcpu->kvm->lock);
2102                 return X86EMUL_CONTINUE;
2103         }
2104         mutex_unlock(&vcpu->kvm->lock);
2105
2106         vcpu->mmio_needed = 1;
2107         vcpu->mmio_phys_addr = gpa;
2108         vcpu->mmio_size = bytes;
2109         vcpu->mmio_is_write = 1;
2110         memcpy(vcpu->mmio_data, val, bytes);
2111
2112         return X86EMUL_CONTINUE;
2113 }
2114
2115 int emulator_write_emulated(unsigned long addr,
2116                                    const void *val,
2117                                    unsigned int bytes,
2118                                    struct kvm_vcpu *vcpu)
2119 {
2120         /* Crossing a page boundary? */
2121         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
2122                 int rc, now;
2123
2124                 now = -addr & ~PAGE_MASK;
2125                 rc = emulator_write_emulated_onepage(addr, val, now, vcpu);
2126                 if (rc != X86EMUL_CONTINUE)
2127                         return rc;
2128                 addr += now;
2129                 val += now;
2130                 bytes -= now;
2131         }
2132         return emulator_write_emulated_onepage(addr, val, bytes, vcpu);
2133 }
2134 EXPORT_SYMBOL_GPL(emulator_write_emulated);
2135
2136 static int emulator_cmpxchg_emulated(unsigned long addr,
2137                                      const void *old,
2138                                      const void *new,
2139                                      unsigned int bytes,
2140                                      struct kvm_vcpu *vcpu)
2141 {
2142         static int reported;
2143
2144         if (!reported) {
2145                 reported = 1;
2146                 printk(KERN_WARNING "kvm: emulating exchange as write\n");
2147         }
2148 #ifndef CONFIG_X86_64
2149         /* guests cmpxchg8b have to be emulated atomically */
2150         if (bytes == 8) {
2151                 gpa_t gpa;
2152                 struct page *page;
2153                 char *kaddr;
2154                 u64 val;
2155
2156                 gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
2157
2158                 if (gpa == UNMAPPED_GVA ||
2159                    (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
2160                         goto emul_write;
2161
2162                 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
2163                         goto emul_write;
2164
2165                 val = *(u64 *)new;
2166
2167                 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
2168
2169                 kaddr = kmap_atomic(page, KM_USER0);
2170                 set_64bit((u64 *)(kaddr + offset_in_page(gpa)), val);
2171                 kunmap_atomic(kaddr, KM_USER0);
2172                 kvm_release_page_dirty(page);
2173         }
2174 emul_write:
2175 #endif
2176
2177         return emulator_write_emulated(addr, new, bytes, vcpu);
2178 }
2179
2180 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
2181 {
2182         return kvm_x86_ops->get_segment_base(vcpu, seg);
2183 }
2184
2185 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
2186 {
2187         kvm_mmu_invlpg(vcpu, address);
2188         return X86EMUL_CONTINUE;
2189 }
2190
2191 int emulate_clts(struct kvm_vcpu *vcpu)
2192 {
2193         KVMTRACE_0D(CLTS, vcpu, handler);
2194         kvm_x86_ops->set_cr0(vcpu, vcpu->arch.cr0 & ~X86_CR0_TS);
2195         return X86EMUL_CONTINUE;
2196 }
2197
2198 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
2199 {
2200         struct kvm_vcpu *vcpu = ctxt->vcpu;
2201
2202         switch (dr) {
2203         case 0 ... 3:
2204                 *dest = kvm_x86_ops->get_dr(vcpu, dr);
2205                 return X86EMUL_CONTINUE;
2206         default:
2207                 pr_unimpl(vcpu, "%s: unexpected dr %u\n", __func__, dr);
2208                 return X86EMUL_UNHANDLEABLE;
2209         }
2210 }
2211
2212 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
2213 {
2214         unsigned long mask = (ctxt->mode == X86EMUL_MODE_PROT64) ? ~0ULL : ~0U;
2215         int exception;
2216
2217         kvm_x86_ops->set_dr(ctxt->vcpu, dr, value & mask, &exception);
2218         if (exception) {
2219                 /* FIXME: better handling */
2220                 return X86EMUL_UNHANDLEABLE;
2221         }
2222         return X86EMUL_CONTINUE;
2223 }
2224
2225 void kvm_report_emulation_failure(struct kvm_vcpu *vcpu, const char *context)
2226 {
2227         u8 opcodes[4];
2228         unsigned long rip = kvm_rip_read(vcpu);
2229         unsigned long rip_linear;
2230
2231         if (!printk_ratelimit())
2232                 return;
2233
2234         rip_linear = rip + get_segment_base(vcpu, VCPU_SREG_CS);
2235
2236         emulator_read_std(rip_linear, (void *)opcodes, 4, vcpu);
2237
2238         printk(KERN_ERR "emulation failed (%s) rip %lx %02x %02x %02x %02x\n",
2239                context, rip, opcodes[0], opcodes[1], opcodes[2], opcodes[3]);
2240 }
2241 EXPORT_SYMBOL_GPL(kvm_report_emulation_failure);
2242
2243 static struct x86_emulate_ops emulate_ops = {
2244         .read_std            = emulator_read_std,
2245         .read_emulated       = emulator_read_emulated,
2246         .write_emulated      = emulator_write_emulated,
2247         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
2248 };
2249
2250 static void cache_all_regs(struct kvm_vcpu *vcpu)
2251 {
2252         kvm_register_read(vcpu, VCPU_REGS_RAX);
2253         kvm_register_read(vcpu, VCPU_REGS_RSP);
2254         kvm_register_read(vcpu, VCPU_REGS_RIP);
2255         vcpu->arch.regs_dirty = ~0;
2256 }
2257
2258 int emulate_instruction(struct kvm_vcpu *vcpu,
2259                         struct kvm_run *run,
2260                         unsigned long cr2,
2261                         u16 error_code,
2262                         int emulation_type)
2263 {
2264         int r;
2265         struct decode_cache *c;
2266
2267         kvm_clear_exception_queue(vcpu);
2268         vcpu->arch.mmio_fault_cr2 = cr2;
2269         /*
2270          * TODO: fix x86_emulate.c to use guest_read/write_register
2271          * instead of direct ->regs accesses, can save hundred cycles
2272          * on Intel for instructions that don't read/change RSP, for
2273          * for example.
2274          */
2275         cache_all_regs(vcpu);
2276
2277         vcpu->mmio_is_write = 0;
2278         vcpu->arch.pio.string = 0;
2279
2280         if (!(emulation_type & EMULTYPE_NO_DECODE)) {
2281                 int cs_db, cs_l;
2282                 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
2283
2284                 vcpu->arch.emulate_ctxt.vcpu = vcpu;
2285                 vcpu->arch.emulate_ctxt.eflags = kvm_x86_ops->get_rflags(vcpu);
2286                 vcpu->arch.emulate_ctxt.mode =
2287                         (vcpu->arch.emulate_ctxt.eflags & X86_EFLAGS_VM)
2288                         ? X86EMUL_MODE_REAL : cs_l
2289                         ? X86EMUL_MODE_PROT64 : cs_db
2290                         ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
2291
2292                 r = x86_decode_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
2293
2294                 /* Reject the instructions other than VMCALL/VMMCALL when
2295                  * try to emulate invalid opcode */
2296                 c = &vcpu->arch.emulate_ctxt.decode;
2297                 if ((emulation_type & EMULTYPE_TRAP_UD) &&
2298                     (!(c->twobyte && c->b == 0x01 &&
2299                       (c->modrm_reg == 0 || c->modrm_reg == 3) &&
2300                        c->modrm_mod == 3 && c->modrm_rm == 1)))
2301                         return EMULATE_FAIL;
2302
2303                 ++vcpu->stat.insn_emulation;
2304                 if (r)  {
2305                         ++vcpu->stat.insn_emulation_fail;
2306                         if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
2307                                 return EMULATE_DONE;
2308                         return EMULATE_FAIL;
2309                 }
2310         }
2311
2312         r = x86_emulate_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
2313
2314         if (vcpu->arch.pio.string)
2315                 return EMULATE_DO_MMIO;
2316
2317         if ((r || vcpu->mmio_is_write) && run) {
2318                 run->exit_reason = KVM_EXIT_MMIO;
2319                 run->mmio.phys_addr = vcpu->mmio_phys_addr;
2320                 memcpy(run->mmio.data, vcpu->mmio_data, 8);
2321                 run->mmio.len = vcpu->mmio_size;
2322                 run->mmio.is_write = vcpu->mmio_is_write;
2323         }
2324
2325         if (r) {
2326                 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
2327                         return EMULATE_DONE;
2328                 if (!vcpu->mmio_needed) {
2329                         kvm_report_emulation_failure(vcpu, "mmio");
2330                         return EMULATE_FAIL;
2331                 }
2332                 return EMULATE_DO_MMIO;
2333         }
2334
2335         kvm_x86_ops->set_rflags(vcpu, vcpu->arch.emulate_ctxt.eflags);
2336
2337         if (vcpu->mmio_is_write) {
2338                 vcpu->mmio_needed = 0;
2339                 return EMULATE_DO_MMIO;
2340         }
2341
2342         return EMULATE_DONE;
2343 }
2344 EXPORT_SYMBOL_GPL(emulate_instruction);
2345
2346 static void free_pio_guest_pages(struct kvm_vcpu *vcpu)
2347 {
2348         int i;
2349
2350         for (i = 0; i < ARRAY_SIZE(vcpu->arch.pio.guest_pages); ++i)
2351                 if (vcpu->arch.pio.guest_pages[i]) {
2352                         kvm_release_page_dirty(vcpu->arch.pio.guest_pages[i]);
2353                         vcpu->arch.pio.guest_pages[i] = NULL;
2354                 }
2355 }
2356
2357 static int pio_copy_data(struct kvm_vcpu *vcpu)
2358 {
2359         void *p = vcpu->arch.pio_data;
2360         void *q;
2361         unsigned bytes;
2362         int nr_pages = vcpu->arch.pio.guest_pages[1] ? 2 : 1;
2363
2364         q = vmap(vcpu->arch.pio.guest_pages, nr_pages, VM_READ|VM_WRITE,
2365                  PAGE_KERNEL);
2366         if (!q) {
2367                 free_pio_guest_pages(vcpu);
2368                 return -ENOMEM;
2369         }
2370         q += vcpu->arch.pio.guest_page_offset;
2371         bytes = vcpu->arch.pio.size * vcpu->arch.pio.cur_count;
2372         if (vcpu->arch.pio.in)
2373                 memcpy(q, p, bytes);
2374         else
2375                 memcpy(p, q, bytes);
2376         q -= vcpu->arch.pio.guest_page_offset;
2377         vunmap(q);
2378         free_pio_guest_pages(vcpu);
2379         return 0;
2380 }
2381
2382 int complete_pio(struct kvm_vcpu *vcpu)
2383 {
2384         struct kvm_pio_request *io = &vcpu->arch.pio;
2385         long delta;
2386         int r;
2387         unsigned long val;
2388
2389         if (!io->string) {
2390                 if (io->in) {
2391                         val = kvm_register_read(vcpu, VCPU_REGS_RAX);
2392                         memcpy(&val, vcpu->arch.pio_data, io->size);
2393                         kvm_register_write(vcpu, VCPU_REGS_RAX, val);
2394                 }
2395         } else {
2396                 if (io->in) {
2397                         r = pio_copy_data(vcpu);
2398                         if (r)
2399                                 return r;
2400                 }
2401
2402                 delta = 1;
2403                 if (io->rep) {
2404                         delta *= io->cur_count;
2405                         /*
2406                          * The size of the register should really depend on
2407                          * current address size.
2408                          */
2409                         val = kvm_register_read(vcpu, VCPU_REGS_RCX);
2410                         val -= delta;
2411                         kvm_register_write(vcpu, VCPU_REGS_RCX, val);
2412                 }
2413                 if (io->down)
2414                         delta = -delta;
2415                 delta *= io->size;
2416                 if (io->in) {
2417                         val = kvm_register_read(vcpu, VCPU_REGS_RDI);
2418                         val += delta;
2419                         kvm_register_write(vcpu, VCPU_REGS_RDI, val);
2420                 } else {
2421                         val = kvm_register_read(vcpu, VCPU_REGS_RSI);
2422                         val += delta;
2423                         kvm_register_write(vcpu, VCPU_REGS_RSI, val);
2424                 }
2425         }
2426
2427         io->count -= io->cur_count;
2428         io->cur_count = 0;
2429
2430         return 0;
2431 }
2432
2433 static void kernel_pio(struct kvm_io_device *pio_dev,
2434                        struct kvm_vcpu *vcpu,
2435                        void *pd)
2436 {
2437         /* TODO: String I/O for in kernel device */
2438
2439         mutex_lock(&vcpu->kvm->lock);
2440         if (vcpu->arch.pio.in)
2441                 kvm_iodevice_read(pio_dev, vcpu->arch.pio.port,
2442                                   vcpu->arch.pio.size,
2443                                   pd);
2444         else
2445                 kvm_iodevice_write(pio_dev, vcpu->arch.pio.port,
2446                                    vcpu->arch.pio.size,
2447                                    pd);
2448         mutex_unlock(&vcpu->kvm->lock);
2449 }
2450
2451 static void pio_string_write(struct kvm_io_device *pio_dev,
2452                              struct kvm_vcpu *vcpu)
2453 {
2454         struct kvm_pio_request *io = &vcpu->arch.pio;
2455         void *pd = vcpu->arch.pio_data;
2456         int i;
2457
2458         mutex_lock(&vcpu->kvm->lock);
2459         for (i = 0; i < io->cur_count; i++) {
2460                 kvm_iodevice_write(pio_dev, io->port,
2461                                    io->size,
2462                                    pd);
2463                 pd += io->size;
2464         }
2465         mutex_unlock(&vcpu->kvm->lock);
2466 }
2467
2468 static struct kvm_io_device *vcpu_find_pio_dev(struct kvm_vcpu *vcpu,
2469                                                gpa_t addr, int len,
2470                                                int is_write)
2471 {
2472         return kvm_io_bus_find_dev(&vcpu->kvm->pio_bus, addr, len, is_write);
2473 }
2474
2475 int kvm_emulate_pio(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
2476                   int size, unsigned port)
2477 {
2478         struct kvm_io_device *pio_dev;
2479         unsigned long val;
2480
2481         vcpu->run->exit_reason = KVM_EXIT_IO;
2482         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2483         vcpu->run->io.size = vcpu->arch.pio.size = size;
2484         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2485         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = 1;
2486         vcpu->run->io.port = vcpu->arch.pio.port = port;
2487         vcpu->arch.pio.in = in;
2488         vcpu->arch.pio.string = 0;
2489         vcpu->arch.pio.down = 0;
2490         vcpu->arch.pio.guest_page_offset = 0;
2491         vcpu->arch.pio.rep = 0;
2492
2493         if (vcpu->run->io.direction == KVM_EXIT_IO_IN)
2494                 KVMTRACE_2D(IO_READ, vcpu, vcpu->run->io.port, (u32)size,
2495                             handler);
2496         else
2497                 KVMTRACE_2D(IO_WRITE, vcpu, vcpu->run->io.port, (u32)size,
2498                             handler);
2499
2500         val = kvm_register_read(vcpu, VCPU_REGS_RAX);
2501         memcpy(vcpu->arch.pio_data, &val, 4);
2502
2503         pio_dev = vcpu_find_pio_dev(vcpu, port, size, !in);
2504         if (pio_dev) {
2505                 kernel_pio(pio_dev, vcpu, vcpu->arch.pio_data);
2506                 complete_pio(vcpu);
2507                 return 1;
2508         }
2509         return 0;
2510 }
2511 EXPORT_SYMBOL_GPL(kvm_emulate_pio);
2512
2513 int kvm_emulate_pio_string(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
2514                   int size, unsigned long count, int down,
2515                   gva_t address, int rep, unsigned port)
2516 {
2517         unsigned now, in_page;
2518         int i, ret = 0;
2519         int nr_pages = 1;
2520         struct page *page;
2521         struct kvm_io_device *pio_dev;
2522
2523         vcpu->run->exit_reason = KVM_EXIT_IO;
2524         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2525         vcpu->run->io.size = vcpu->arch.pio.size = size;
2526         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2527         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = count;
2528         vcpu->run->io.port = vcpu->arch.pio.port = port;
2529         vcpu->arch.pio.in = in;
2530         vcpu->arch.pio.string = 1;
2531         vcpu->arch.pio.down = down;
2532         vcpu->arch.pio.guest_page_offset = offset_in_page(address);
2533         vcpu->arch.pio.rep = rep;
2534
2535         if (vcpu->run->io.direction == KVM_EXIT_IO_IN)
2536                 KVMTRACE_2D(IO_READ, vcpu, vcpu->run->io.port, (u32)size,
2537                             handler);
2538         else
2539                 KVMTRACE_2D(IO_WRITE, vcpu, vcpu->run->io.port, (u32)size,
2540                             handler);
2541
2542         if (!count) {
2543                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2544                 return 1;
2545         }
2546
2547         if (!down)
2548                 in_page = PAGE_SIZE - offset_in_page(address);
2549         else
2550                 in_page = offset_in_page(address) + size;
2551         now = min(count, (unsigned long)in_page / size);
2552         if (!now) {
2553                 /*
2554                  * String I/O straddles page boundary.  Pin two guest pages
2555                  * so that we satisfy atomicity constraints.  Do just one
2556                  * transaction to avoid complexity.
2557                  */
2558                 nr_pages = 2;
2559                 now = 1;
2560         }
2561         if (down) {
2562                 /*
2563                  * String I/O in reverse.  Yuck.  Kill the guest, fix later.
2564                  */
2565                 pr_unimpl(vcpu, "guest string pio down\n");
2566                 kvm_inject_gp(vcpu, 0);
2567                 return 1;
2568         }
2569         vcpu->run->io.count = now;
2570         vcpu->arch.pio.cur_count = now;
2571
2572         if (vcpu->arch.pio.cur_count == vcpu->arch.pio.count)
2573                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2574
2575         for (i = 0; i < nr_pages; ++i) {
2576                 page = gva_to_page(vcpu, address + i * PAGE_SIZE);
2577                 vcpu->arch.pio.guest_pages[i] = page;
2578                 if (!page) {
2579                         kvm_inject_gp(vcpu, 0);
2580                         free_pio_guest_pages(vcpu);
2581                         return 1;
2582                 }
2583         }
2584
2585         pio_dev = vcpu_find_pio_dev(vcpu, port,
2586                                     vcpu->arch.pio.cur_count,
2587                                     !vcpu->arch.pio.in);
2588         if (!vcpu->arch.pio.in) {
2589                 /* string PIO write */
2590                 ret = pio_copy_data(vcpu);
2591                 if (ret >= 0 && pio_dev) {
2592                         pio_string_write(pio_dev, vcpu);
2593                         complete_pio(vcpu);
2594                         if (vcpu->arch.pio.count == 0)
2595                                 ret = 1;
2596                 }
2597         } else if (pio_dev)
2598                 pr_unimpl(vcpu, "no string pio read support yet, "
2599                        "port %x size %d count %ld\n",
2600                         port, size, count);
2601
2602         return ret;
2603 }
2604 EXPORT_SYMBOL_GPL(kvm_emulate_pio_string);
2605
2606 int kvm_arch_init(void *opaque)
2607 {
2608         int r;
2609         struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
2610
2611         if (kvm_x86_ops) {
2612                 printk(KERN_ERR "kvm: already loaded the other module\n");
2613                 r = -EEXIST;
2614                 goto out;
2615         }
2616
2617         if (!ops->cpu_has_kvm_support()) {
2618                 printk(KERN_ERR "kvm: no hardware support\n");
2619                 r = -EOPNOTSUPP;
2620                 goto out;
2621         }
2622         if (ops->disabled_by_bios()) {
2623                 printk(KERN_ERR "kvm: disabled by bios\n");
2624                 r = -EOPNOTSUPP;
2625                 goto out;
2626         }
2627
2628         r = kvm_mmu_module_init();
2629         if (r)
2630                 goto out;
2631
2632         kvm_init_msr_list();
2633
2634         kvm_x86_ops = ops;
2635         kvm_mmu_set_nonpresent_ptes(0ull, 0ull);
2636         kvm_mmu_set_base_ptes(PT_PRESENT_MASK);
2637         kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
2638                         PT_DIRTY_MASK, PT64_NX_MASK, 0, 0);
2639         return 0;
2640
2641 out:
2642         return r;
2643 }
2644
2645 void kvm_arch_exit(void)
2646 {
2647         kvm_x86_ops = NULL;
2648         kvm_mmu_module_exit();
2649 }
2650
2651 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
2652 {
2653         ++vcpu->stat.halt_exits;
2654         KVMTRACE_0D(HLT, vcpu, handler);
2655         if (irqchip_in_kernel(vcpu->kvm)) {
2656                 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
2657                 return 1;
2658         } else {
2659                 vcpu->run->exit_reason = KVM_EXIT_HLT;
2660                 return 0;
2661         }
2662 }
2663 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
2664
2665 static inline gpa_t hc_gpa(struct kvm_vcpu *vcpu, unsigned long a0,
2666                            unsigned long a1)
2667 {
2668         if (is_long_mode(vcpu))
2669                 return a0;
2670         else
2671                 return a0 | ((gpa_t)a1 << 32);
2672 }
2673
2674 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
2675 {
2676         unsigned long nr, a0, a1, a2, a3, ret;
2677         int r = 1;
2678
2679         nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
2680         a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
2681         a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
2682         a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
2683         a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
2684
2685         KVMTRACE_1D(VMMCALL, vcpu, (u32)nr, handler);
2686
2687         if (!is_long_mode(vcpu)) {
2688                 nr &= 0xFFFFFFFF;
2689                 a0 &= 0xFFFFFFFF;
2690                 a1 &= 0xFFFFFFFF;
2691                 a2 &= 0xFFFFFFFF;
2692                 a3 &= 0xFFFFFFFF;
2693         }
2694
2695         switch (nr) {
2696         case KVM_HC_VAPIC_POLL_IRQ:
2697                 ret = 0;
2698                 break;
2699         case KVM_HC_MMU_OP:
2700                 r = kvm_pv_mmu_op(vcpu, a0, hc_gpa(vcpu, a1, a2), &ret);
2701                 break;
2702         default:
2703                 ret = -KVM_ENOSYS;
2704                 break;
2705         }
2706         kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
2707         ++vcpu->stat.hypercalls;
2708         return r;
2709 }
2710 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
2711
2712 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
2713 {
2714         char instruction[3];
2715         int ret = 0;
2716         unsigned long rip = kvm_rip_read(vcpu);
2717
2718
2719         /*
2720          * Blow out the MMU to ensure that no other VCPU has an active mapping
2721          * to ensure that the updated hypercall appears atomically across all
2722          * VCPUs.
2723          */
2724         kvm_mmu_zap_all(vcpu->kvm);
2725
2726         kvm_x86_ops->patch_hypercall(vcpu, instruction);
2727         if (emulator_write_emulated(rip, instruction, 3, vcpu)
2728             != X86EMUL_CONTINUE)
2729                 ret = -EFAULT;
2730
2731         return ret;
2732 }
2733
2734 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
2735 {
2736         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
2737 }
2738
2739 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2740 {
2741         struct descriptor_table dt = { limit, base };
2742
2743         kvm_x86_ops->set_gdt(vcpu, &dt);
2744 }
2745
2746 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2747 {
2748         struct descriptor_table dt = { limit, base };
2749
2750         kvm_x86_ops->set_idt(vcpu, &dt);
2751 }
2752
2753 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
2754                    unsigned long *rflags)
2755 {
2756         kvm_lmsw(vcpu, msw);
2757         *rflags = kvm_x86_ops->get_rflags(vcpu);
2758 }
2759
2760 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
2761 {
2762         unsigned long value;
2763
2764         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2765         switch (cr) {
2766         case 0:
2767                 value = vcpu->arch.cr0;
2768                 break;
2769         case 2:
2770                 value = vcpu->arch.cr2;
2771                 break;
2772         case 3:
2773                 value = vcpu->arch.cr3;
2774                 break;
2775         case 4:
2776                 value = vcpu->arch.cr4;
2777                 break;
2778         case 8:
2779                 value = kvm_get_cr8(vcpu);
2780                 break;
2781         default:
2782                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
2783                 return 0;
2784         }
2785         KVMTRACE_3D(CR_READ, vcpu, (u32)cr, (u32)value,
2786                     (u32)((u64)value >> 32), handler);
2787
2788         return value;
2789 }
2790
2791 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
2792                      unsigned long *rflags)
2793 {
2794         KVMTRACE_3D(CR_WRITE, vcpu, (u32)cr, (u32)val,
2795                     (u32)((u64)val >> 32), handler);
2796
2797         switch (cr) {
2798         case 0:
2799                 kvm_set_cr0(vcpu, mk_cr_64(vcpu->arch.cr0, val));
2800                 *rflags = kvm_x86_ops->get_rflags(vcpu);
2801                 break;
2802         case 2:
2803                 vcpu->arch.cr2 = val;
2804                 break;
2805         case 3:
2806                 kvm_set_cr3(vcpu, val);
2807                 break;
2808         case 4:
2809                 kvm_set_cr4(vcpu, mk_cr_64(vcpu->arch.cr4, val));
2810                 break;
2811         case 8:
2812                 kvm_set_cr8(vcpu, val & 0xfUL);
2813                 break;
2814         default:
2815                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
2816         }
2817 }
2818
2819 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
2820 {
2821         struct kvm_cpuid_entry2 *e = &vcpu->arch.cpuid_entries[i];
2822         int j, nent = vcpu->arch.cpuid_nent;
2823
2824         e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
2825         /* when no next entry is found, the current entry[i] is reselected */
2826         for (j = i + 1; ; j = (j + 1) % nent) {
2827                 struct kvm_cpuid_entry2 *ej = &vcpu->arch.cpuid_entries[j];
2828                 if (ej->function == e->function) {
2829                         ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
2830                         return j;
2831                 }
2832         }
2833         return 0; /* silence gcc, even though control never reaches here */
2834 }
2835
2836 /* find an entry with matching function, matching index (if needed), and that
2837  * should be read next (if it's stateful) */
2838 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
2839         u32 function, u32 index)
2840 {
2841         if (e->function != function)
2842                 return 0;
2843         if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
2844                 return 0;
2845         if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
2846                 !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
2847                 return 0;
2848         return 1;
2849 }
2850
2851 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry(struct kvm_vcpu *vcpu,
2852                                               u32 function, u32 index)
2853 {
2854         int i;
2855         struct kvm_cpuid_entry2 *best = NULL;
2856
2857         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
2858                 struct kvm_cpuid_entry2 *e;
2859
2860                 e = &vcpu->arch.cpuid_entries[i];
2861                 if (is_matching_cpuid_entry(e, function, index)) {
2862                         if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
2863                                 move_to_next_stateful_cpuid_entry(vcpu, i);
2864                         best = e;
2865                         break;
2866                 }
2867                 /*
2868                  * Both basic or both extended?
2869                  */
2870                 if (((e->function ^ function) & 0x80000000) == 0)
2871                         if (!best || e->function > best->function)
2872                                 best = e;
2873         }
2874
2875         return best;
2876 }
2877
2878 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
2879 {
2880         u32 function, index;
2881         struct kvm_cpuid_entry2 *best;
2882
2883         function = kvm_register_read(vcpu, VCPU_REGS_RAX);
2884         index = kvm_register_read(vcpu, VCPU_REGS_RCX);
2885         kvm_register_write(vcpu, VCPU_REGS_RAX, 0);
2886         kvm_register_write(vcpu, VCPU_REGS_RBX, 0);
2887         kvm_register_write(vcpu, VCPU_REGS_RCX, 0);
2888         kvm_register_write(vcpu, VCPU_REGS_RDX, 0);
2889         best = kvm_find_cpuid_entry(vcpu, function, index);
2890         if (best) {
2891                 kvm_register_write(vcpu, VCPU_REGS_RAX, best->eax);
2892                 kvm_register_write(vcpu, VCPU_REGS_RBX, best->ebx);
2893                 kvm_register_write(vcpu, VCPU_REGS_RCX, best->ecx);
2894                 kvm_register_write(vcpu, VCPU_REGS_RDX, best->edx);
2895         }
2896         kvm_x86_ops->skip_emulated_instruction(vcpu);
2897         KVMTRACE_5D(CPUID, vcpu, function,
2898                     (u32)kvm_register_read(vcpu, VCPU_REGS_RAX),
2899                     (u32)kvm_register_read(vcpu, VCPU_REGS_RBX),
2900                     (u32)kvm_register_read(vcpu, VCPU_REGS_RCX),
2901                     (u32)kvm_register_read(vcpu, VCPU_REGS_RDX), handler);
2902 }
2903 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
2904
2905 /*
2906  * Check if userspace requested an interrupt window, and that the
2907  * interrupt window is open.
2908  *
2909  * No need to exit to userspace if we already have an interrupt queued.
2910  */
2911 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu,
2912                                           struct kvm_run *kvm_run)
2913 {
2914         return (!vcpu->arch.irq_summary &&
2915                 kvm_run->request_interrupt_window &&
2916                 vcpu->arch.interrupt_window_open &&
2917                 (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF));
2918 }
2919
2920 static void post_kvm_run_save(struct kvm_vcpu *vcpu,
2921                               struct kvm_run *kvm_run)
2922 {
2923         kvm_run->if_flag = (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
2924         kvm_run->cr8 = kvm_get_cr8(vcpu);
2925         kvm_run->apic_base = kvm_get_apic_base(vcpu);
2926         if (irqchip_in_kernel(vcpu->kvm))
2927                 kvm_run->ready_for_interrupt_injection = 1;
2928         else
2929                 kvm_run->ready_for_interrupt_injection =
2930                                         (vcpu->arch.interrupt_window_open &&
2931                                          vcpu->arch.irq_summary == 0);
2932 }
2933
2934 static void vapic_enter(struct kvm_vcpu *vcpu)
2935 {
2936         struct kvm_lapic *apic = vcpu->arch.apic;
2937         struct page *page;
2938
2939         if (!apic || !apic->vapic_addr)
2940                 return;
2941
2942         page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
2943
2944         vcpu->arch.apic->vapic_page = page;
2945 }
2946
2947 static void vapic_exit(struct kvm_vcpu *vcpu)
2948 {
2949         struct kvm_lapic *apic = vcpu->arch.apic;
2950
2951         if (!apic || !apic->vapic_addr)
2952                 return;
2953
2954         down_read(&vcpu->kvm->slots_lock);
2955         kvm_release_page_dirty(apic->vapic_page);
2956         mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
2957         up_read(&vcpu->kvm->slots_lock);
2958 }
2959
2960 static int vcpu_enter_guest(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2961 {
2962         int r;
2963
2964         if (vcpu->requests)
2965                 if (test_and_clear_bit(KVM_REQ_MMU_RELOAD, &vcpu->requests))
2966                         kvm_mmu_unload(vcpu);
2967
2968         r = kvm_mmu_reload(vcpu);
2969         if (unlikely(r))
2970                 goto out;
2971
2972         if (vcpu->requests) {
2973                 if (test_and_clear_bit(KVM_REQ_MIGRATE_TIMER, &vcpu->requests))
2974                         __kvm_migrate_timers(vcpu);
2975                 if (test_and_clear_bit(KVM_REQ_MMU_SYNC, &vcpu->requests))
2976                         kvm_mmu_sync_roots(vcpu);
2977                 if (test_and_clear_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
2978                         kvm_x86_ops->tlb_flush(vcpu);
2979                 if (test_and_clear_bit(KVM_REQ_REPORT_TPR_ACCESS,
2980                                        &vcpu->requests)) {
2981                         kvm_run->exit_reason = KVM_EXIT_TPR_ACCESS;
2982                         r = 0;
2983                         goto out;
2984                 }
2985                 if (test_and_clear_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests)) {
2986                         kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2987                         r = 0;
2988                         goto out;
2989                 }
2990         }
2991
2992         clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
2993         kvm_inject_pending_timer_irqs(vcpu);
2994
2995         preempt_disable();
2996
2997         kvm_x86_ops->prepare_guest_switch(vcpu);
2998         kvm_load_guest_fpu(vcpu);
2999
3000         local_irq_disable();
3001
3002         if (vcpu->requests || need_resched() || signal_pending(current)) {
3003                 local_irq_enable();
3004                 preempt_enable();
3005                 r = 1;
3006                 goto out;
3007         }
3008
3009         vcpu->guest_mode = 1;
3010         /*
3011          * Make sure that guest_mode assignment won't happen after
3012          * testing the pending IRQ vector bitmap.
3013          */
3014         smp_wmb();
3015
3016         if (vcpu->arch.exception.pending)
3017                 __queue_exception(vcpu);
3018         else if (irqchip_in_kernel(vcpu->kvm))
3019                 kvm_x86_ops->inject_pending_irq(vcpu);
3020         else
3021                 kvm_x86_ops->inject_pending_vectors(vcpu, kvm_run);
3022
3023         kvm_lapic_sync_to_vapic(vcpu);
3024
3025         up_read(&vcpu->kvm->slots_lock);
3026
3027         kvm_guest_enter();
3028
3029         get_debugreg(vcpu->arch.host_dr6, 6);
3030         get_debugreg(vcpu->arch.host_dr7, 7);
3031         if (unlikely(vcpu->arch.switch_db_regs)) {
3032                 get_debugreg(vcpu->arch.host_db[0], 0);
3033                 get_debugreg(vcpu->arch.host_db[1], 1);
3034                 get_debugreg(vcpu->arch.host_db[2], 2);
3035                 get_debugreg(vcpu->arch.host_db[3], 3);
3036
3037                 set_debugreg(0, 7);
3038                 set_debugreg(vcpu->arch.eff_db[0], 0);
3039                 set_debugreg(vcpu->arch.eff_db[1], 1);
3040                 set_debugreg(vcpu->arch.eff_db[2], 2);
3041                 set_debugreg(vcpu->arch.eff_db[3], 3);
3042         }
3043
3044         KVMTRACE_0D(VMENTRY, vcpu, entryexit);
3045         kvm_x86_ops->run(vcpu, kvm_run);
3046
3047         if (unlikely(vcpu->arch.switch_db_regs)) {
3048                 set_debugreg(0, 7);
3049                 set_debugreg(vcpu->arch.host_db[0], 0);
3050                 set_debugreg(vcpu->arch.host_db[1], 1);
3051                 set_debugreg(vcpu->arch.host_db[2], 2);
3052                 set_debugreg(vcpu->arch.host_db[3], 3);
3053         }
3054         set_debugreg(vcpu->arch.host_dr6, 6);
3055         set_debugreg(vcpu->arch.host_dr7, 7);
3056
3057         vcpu->guest_mode = 0;
3058         local_irq_enable();
3059
3060         ++vcpu->stat.exits;
3061
3062         /*
3063          * We must have an instruction between local_irq_enable() and
3064          * kvm_guest_exit(), so the timer interrupt isn't delayed by
3065          * the interrupt shadow.  The stat.exits increment will do nicely.
3066          * But we need to prevent reordering, hence this barrier():
3067          */
3068         barrier();
3069
3070         kvm_guest_exit();
3071
3072         preempt_enable();
3073
3074         down_read(&vcpu->kvm->slots_lock);
3075
3076         /*
3077          * Profile KVM exit RIPs:
3078          */
3079         if (unlikely(prof_on == KVM_PROFILING)) {
3080                 unsigned long rip = kvm_rip_read(vcpu);
3081                 profile_hit(KVM_PROFILING, (void *)rip);
3082         }
3083
3084         if (vcpu->arch.exception.pending && kvm_x86_ops->exception_injected(vcpu))
3085                 vcpu->arch.exception.pending = false;
3086
3087         kvm_lapic_sync_from_vapic(vcpu);
3088
3089         r = kvm_x86_ops->handle_exit(kvm_run, vcpu);
3090 out:
3091         return r;
3092 }
3093
3094 static int __vcpu_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
3095 {
3096         int r;
3097
3098         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
3099                 pr_debug("vcpu %d received sipi with vector # %x\n",
3100                          vcpu->vcpu_id, vcpu->arch.sipi_vector);
3101                 kvm_lapic_reset(vcpu);
3102                 r = kvm_arch_vcpu_reset(vcpu);
3103                 if (r)
3104                         return r;
3105                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3106         }
3107
3108         down_read(&vcpu->kvm->slots_lock);
3109         vapic_enter(vcpu);
3110
3111         r = 1;
3112         while (r > 0) {
3113                 if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE)
3114                         r = vcpu_enter_guest(vcpu, kvm_run);
3115                 else {
3116                         up_read(&vcpu->kvm->slots_lock);
3117                         kvm_vcpu_block(vcpu);
3118                         down_read(&vcpu->kvm->slots_lock);
3119                         if (test_and_clear_bit(KVM_REQ_UNHALT, &vcpu->requests))
3120                                 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
3121                                         vcpu->arch.mp_state =
3122                                                         KVM_MP_STATE_RUNNABLE;
3123                         if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE)
3124                                 r = -EINTR;
3125                 }
3126
3127                 if (r > 0) {
3128                         if (dm_request_for_irq_injection(vcpu, kvm_run)) {
3129                                 r = -EINTR;
3130                                 kvm_run->exit_reason = KVM_EXIT_INTR;
3131                                 ++vcpu->stat.request_irq_exits;
3132                         }
3133                         if (signal_pending(current)) {
3134                                 r = -EINTR;
3135                                 kvm_run->exit_reason = KVM_EXIT_INTR;
3136                                 ++vcpu->stat.signal_exits;
3137                         }
3138                         if (need_resched()) {
3139                                 up_read(&vcpu->kvm->slots_lock);
3140                                 kvm_resched(vcpu);
3141                                 down_read(&vcpu->kvm->slots_lock);
3142                         }
3143                 }
3144         }
3145
3146         up_read(&vcpu->kvm->slots_lock);
3147         post_kvm_run_save(vcpu, kvm_run);
3148
3149         vapic_exit(vcpu);
3150
3151         return r;
3152 }
3153
3154 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
3155 {
3156         int r;
3157         sigset_t sigsaved;
3158
3159         vcpu_load(vcpu);
3160
3161         if (vcpu->sigset_active)
3162                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
3163
3164         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
3165                 kvm_vcpu_block(vcpu);
3166                 clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
3167                 r = -EAGAIN;
3168                 goto out;
3169         }
3170
3171         /* re-sync apic's tpr */
3172         if (!irqchip_in_kernel(vcpu->kvm))
3173                 kvm_set_cr8(vcpu, kvm_run->cr8);
3174
3175         if (vcpu->arch.pio.cur_count) {
3176                 r = complete_pio(vcpu);
3177                 if (r)
3178                         goto out;
3179         }
3180 #if CONFIG_HAS_IOMEM
3181         if (vcpu->mmio_needed) {
3182                 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
3183                 vcpu->mmio_read_completed = 1;
3184                 vcpu->mmio_needed = 0;
3185
3186                 down_read(&vcpu->kvm->slots_lock);
3187                 r = emulate_instruction(vcpu, kvm_run,
3188                                         vcpu->arch.mmio_fault_cr2, 0,
3189                                         EMULTYPE_NO_DECODE);
3190                 up_read(&vcpu->kvm->slots_lock);
3191                 if (r == EMULATE_DO_MMIO) {
3192                         /*
3193                          * Read-modify-write.  Back to userspace.
3194                          */
3195                         r = 0;
3196                         goto out;
3197                 }
3198         }
3199 #endif
3200         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL)
3201                 kvm_register_write(vcpu, VCPU_REGS_RAX,
3202                                      kvm_run->hypercall.ret);
3203
3204         r = __vcpu_run(vcpu, kvm_run);
3205
3206 out:
3207         if (vcpu->sigset_active)
3208                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
3209
3210         vcpu_put(vcpu);
3211         return r;
3212 }
3213
3214 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
3215 {
3216         vcpu_load(vcpu);
3217
3218         regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
3219         regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
3220         regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
3221         regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
3222         regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
3223         regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
3224         regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
3225         regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
3226 #ifdef CONFIG_X86_64
3227         regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
3228         regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
3229         regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
3230         regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
3231         regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
3232         regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
3233         regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
3234         regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
3235 #endif
3236
3237         regs->rip = kvm_rip_read(vcpu);
3238         regs->rflags = kvm_x86_ops->get_rflags(vcpu);
3239
3240         /*
3241          * Don't leak debug flags in case they were set for guest debugging
3242          */
3243         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
3244                 regs->rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
3245
3246         vcpu_put(vcpu);
3247
3248         return 0;
3249 }
3250
3251 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
3252 {
3253         vcpu_load(vcpu);
3254
3255         kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
3256         kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
3257         kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
3258         kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
3259         kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
3260         kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
3261         kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
3262         kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
3263 #ifdef CONFIG_X86_64
3264         kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
3265         kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
3266         kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
3267         kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
3268         kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
3269         kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
3270         kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
3271         kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
3272
3273 #endif
3274
3275         kvm_rip_write(vcpu, regs->rip);
3276         kvm_x86_ops->set_rflags(vcpu, regs->rflags);
3277
3278
3279         vcpu->arch.exception.pending = false;
3280
3281         vcpu_put(vcpu);
3282
3283         return 0;
3284 }
3285
3286 void kvm_get_segment(struct kvm_vcpu *vcpu,
3287                      struct kvm_segment *var, int seg)
3288 {
3289         kvm_x86_ops->get_segment(vcpu, var, seg);
3290 }
3291
3292 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3293 {
3294         struct kvm_segment cs;
3295
3296         kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
3297         *db = cs.db;
3298         *l = cs.l;
3299 }
3300 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
3301
3302 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
3303                                   struct kvm_sregs *sregs)
3304 {
3305         struct descriptor_table dt;
3306         int pending_vec;
3307
3308         vcpu_load(vcpu);
3309
3310         kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
3311         kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
3312         kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
3313         kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
3314         kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
3315         kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
3316
3317         kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
3318         kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
3319
3320         kvm_x86_ops->get_idt(vcpu, &dt);
3321         sregs->idt.limit = dt.limit;
3322         sregs->idt.base = dt.base;
3323         kvm_x86_ops->get_gdt(vcpu, &dt);
3324         sregs->gdt.limit = dt.limit;
3325         sregs->gdt.base = dt.base;
3326
3327         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
3328         sregs->cr0 = vcpu->arch.cr0;
3329         sregs->cr2 = vcpu->arch.cr2;
3330         sregs->cr3 = vcpu->arch.cr3;
3331         sregs->cr4 = vcpu->arch.cr4;
3332         sregs->cr8 = kvm_get_cr8(vcpu);
3333         sregs->efer = vcpu->arch.shadow_efer;
3334         sregs->apic_base = kvm_get_apic_base(vcpu);
3335
3336         if (irqchip_in_kernel(vcpu->kvm)) {
3337                 memset(sregs->interrupt_bitmap, 0,
3338                        sizeof sregs->interrupt_bitmap);
3339                 pending_vec = kvm_x86_ops->get_irq(vcpu);
3340                 if (pending_vec >= 0)
3341                         set_bit(pending_vec,
3342                                 (unsigned long *)sregs->interrupt_bitmap);
3343         } else
3344                 memcpy(sregs->interrupt_bitmap, vcpu->arch.irq_pending,
3345                        sizeof sregs->interrupt_bitmap);
3346
3347         vcpu_put(vcpu);
3348
3349         return 0;
3350 }
3351
3352 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
3353                                     struct kvm_mp_state *mp_state)
3354 {
3355         vcpu_load(vcpu);
3356         mp_state->mp_state = vcpu->arch.mp_state;
3357         vcpu_put(vcpu);
3358         return 0;
3359 }
3360
3361 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
3362                                     struct kvm_mp_state *mp_state)
3363 {
3364         vcpu_load(vcpu);
3365         vcpu->arch.mp_state = mp_state->mp_state;
3366         vcpu_put(vcpu);
3367         return 0;
3368 }
3369
3370 static void kvm_set_segment(struct kvm_vcpu *vcpu,
3371                         struct kvm_segment *var, int seg)
3372 {
3373         kvm_x86_ops->set_segment(vcpu, var, seg);
3374 }
3375
3376 static void seg_desct_to_kvm_desct(struct desc_struct *seg_desc, u16 selector,
3377                                    struct kvm_segment *kvm_desct)
3378 {
3379         kvm_desct->base = seg_desc->base0;
3380         kvm_desct->base |= seg_desc->base1 << 16;
3381         kvm_desct->base |= seg_desc->base2 << 24;
3382         kvm_desct->limit = seg_desc->limit0;
3383         kvm_desct->limit |= seg_desc->limit << 16;
3384         if (seg_desc->g) {
3385                 kvm_desct->limit <<= 12;
3386                 kvm_desct->limit |= 0xfff;
3387         }
3388         kvm_desct->selector = selector;
3389         kvm_desct->type = seg_desc->type;
3390         kvm_desct->present = seg_desc->p;
3391         kvm_desct->dpl = seg_desc->dpl;
3392         kvm_desct->db = seg_desc->d;
3393         kvm_desct->s = seg_desc->s;
3394         kvm_desct->l = seg_desc->l;
3395         kvm_desct->g = seg_desc->g;
3396         kvm_desct->avl = seg_desc->avl;
3397         if (!selector)
3398                 kvm_desct->unusable = 1;
3399         else
3400                 kvm_desct->unusable = 0;
3401         kvm_desct->padding = 0;
3402 }
3403
3404 static void get_segment_descriptor_dtable(struct kvm_vcpu *vcpu,
3405                                           u16 selector,
3406                                           struct descriptor_table *dtable)
3407 {
3408         if (selector & 1 << 2) {
3409                 struct kvm_segment kvm_seg;
3410
3411                 kvm_get_segment(vcpu, &kvm_seg, VCPU_SREG_LDTR);
3412
3413                 if (kvm_seg.unusable)
3414                         dtable->limit = 0;
3415                 else
3416                         dtable->limit = kvm_seg.limit;
3417                 dtable->base = kvm_seg.base;
3418         }
3419         else
3420                 kvm_x86_ops->get_gdt(vcpu, dtable);
3421 }
3422
3423 /* allowed just for 8 bytes segments */
3424 static int load_guest_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
3425                                          struct desc_struct *seg_desc)
3426 {
3427         gpa_t gpa;
3428         struct descriptor_table dtable;
3429         u16 index = selector >> 3;
3430
3431         get_segment_descriptor_dtable(vcpu, selector, &dtable);
3432
3433         if (dtable.limit < index * 8 + 7) {
3434                 kvm_queue_exception_e(vcpu, GP_VECTOR, selector & 0xfffc);
3435                 return 1;
3436         }
3437         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, dtable.base);
3438         gpa += index * 8;
3439         return kvm_read_guest(vcpu->kvm, gpa, seg_desc, 8);
3440 }
3441
3442 /* allowed just for 8 bytes segments */
3443 static int save_guest_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
3444                                          struct desc_struct *seg_desc)
3445 {
3446         gpa_t gpa;
3447         struct descriptor_table dtable;
3448         u16 index = selector >> 3;
3449
3450         get_segment_descriptor_dtable(vcpu, selector, &dtable);
3451
3452         if (dtable.limit < index * 8 + 7)
3453                 return 1;
3454         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, dtable.base);
3455         gpa += index * 8;
3456         return kvm_write_guest(vcpu->kvm, gpa, seg_desc, 8);
3457 }
3458
3459 static u32 get_tss_base_addr(struct kvm_vcpu *vcpu,
3460                              struct desc_struct *seg_desc)
3461 {
3462         u32 base_addr;
3463
3464         base_addr = seg_desc->base0;
3465         base_addr |= (seg_desc->base1 << 16);
3466         base_addr |= (seg_desc->base2 << 24);
3467
3468         return vcpu->arch.mmu.gva_to_gpa(vcpu, base_addr);
3469 }
3470
3471 static u16 get_segment_selector(struct kvm_vcpu *vcpu, int seg)
3472 {
3473         struct kvm_segment kvm_seg;
3474
3475         kvm_get_segment(vcpu, &kvm_seg, seg);
3476         return kvm_seg.selector;
3477 }
3478
3479 static int load_segment_descriptor_to_kvm_desct(struct kvm_vcpu *vcpu,
3480                                                 u16 selector,
3481                                                 struct kvm_segment *kvm_seg)
3482 {
3483         struct desc_struct seg_desc;
3484
3485         if (load_guest_segment_descriptor(vcpu, selector, &seg_desc))
3486                 return 1;
3487         seg_desct_to_kvm_desct(&seg_desc, selector, kvm_seg);
3488         return 0;
3489 }
3490
3491 static int kvm_load_realmode_segment(struct kvm_vcpu *vcpu, u16 selector, int seg)
3492 {
3493         struct kvm_segment segvar = {
3494                 .base = selector << 4,
3495                 .limit = 0xffff,
3496                 .selector = selector,
3497                 .type = 3,
3498                 .present = 1,
3499                 .dpl = 3,
3500                 .db = 0,
3501                 .s = 1,
3502                 .l = 0,
3503                 .g = 0,
3504                 .avl = 0,
3505                 .unusable = 0,
3506         };
3507         kvm_x86_ops->set_segment(vcpu, &segvar, seg);
3508         return 0;
3509 }
3510
3511 int kvm_load_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
3512                                 int type_bits, int seg)
3513 {
3514         struct kvm_segment kvm_seg;
3515
3516         if (!(vcpu->arch.cr0 & X86_CR0_PE))
3517                 return kvm_load_realmode_segment(vcpu, selector, seg);
3518         if (load_segment_descriptor_to_kvm_desct(vcpu, selector, &kvm_seg))
3519                 return 1;
3520         kvm_seg.type |= type_bits;
3521
3522         if (seg != VCPU_SREG_SS && seg != VCPU_SREG_CS &&
3523             seg != VCPU_SREG_LDTR)
3524                 if (!kvm_seg.s)
3525                         kvm_seg.unusable = 1;
3526
3527         kvm_set_segment(vcpu, &kvm_seg, seg);
3528         return 0;
3529 }
3530
3531 static void save_state_to_tss32(struct kvm_vcpu *vcpu,
3532                                 struct tss_segment_32 *tss)
3533 {
3534         tss->cr3 = vcpu->arch.cr3;
3535         tss->eip = kvm_rip_read(vcpu);
3536         tss->eflags = kvm_x86_ops->get_rflags(vcpu);
3537         tss->eax = kvm_register_read(vcpu, VCPU_REGS_RAX);
3538         tss->ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
3539         tss->edx = kvm_register_read(vcpu, VCPU_REGS_RDX);
3540         tss->ebx = kvm_register_read(vcpu, VCPU_REGS_RBX);
3541         tss->esp = kvm_register_read(vcpu, VCPU_REGS_RSP);
3542         tss->ebp = kvm_register_read(vcpu, VCPU_REGS_RBP);
3543         tss->esi = kvm_register_read(vcpu, VCPU_REGS_RSI);
3544         tss->edi = kvm_register_read(vcpu, VCPU_REGS_RDI);
3545         tss->es = get_segment_selector(vcpu, VCPU_SREG_ES);
3546         tss->cs = get_segment_selector(vcpu, VCPU_SREG_CS);
3547         tss->ss = get_segment_selector(vcpu, VCPU_SREG_SS);
3548         tss->ds = get_segment_selector(vcpu, VCPU_SREG_DS);
3549         tss->fs = get_segment_selector(vcpu, VCPU_SREG_FS);
3550         tss->gs = get_segment_selector(vcpu, VCPU_SREG_GS);
3551         tss->ldt_selector = get_segment_selector(vcpu, VCPU_SREG_LDTR);
3552         tss->prev_task_link = get_segment_selector(vcpu, VCPU_SREG_TR);
3553 }
3554
3555 static int load_state_from_tss32(struct kvm_vcpu *vcpu,
3556                                   struct tss_segment_32 *tss)
3557 {
3558         kvm_set_cr3(vcpu, tss->cr3);
3559
3560         kvm_rip_write(vcpu, tss->eip);
3561         kvm_x86_ops->set_rflags(vcpu, tss->eflags | 2);
3562
3563         kvm_register_write(vcpu, VCPU_REGS_RAX, tss->eax);
3564         kvm_register_write(vcpu, VCPU_REGS_RCX, tss->ecx);
3565         kvm_register_write(vcpu, VCPU_REGS_RDX, tss->edx);
3566         kvm_register_write(vcpu, VCPU_REGS_RBX, tss->ebx);
3567         kvm_register_write(vcpu, VCPU_REGS_RSP, tss->esp);
3568         kvm_register_write(vcpu, VCPU_REGS_RBP, tss->ebp);
3569         kvm_register_write(vcpu, VCPU_REGS_RSI, tss->esi);
3570         kvm_register_write(vcpu, VCPU_REGS_RDI, tss->edi);
3571
3572         if (kvm_load_segment_descriptor(vcpu, tss->ldt_selector, 0, VCPU_SREG_LDTR))
3573                 return 1;
3574
3575         if (kvm_load_segment_descriptor(vcpu, tss->es, 1, VCPU_SREG_ES))
3576                 return 1;
3577
3578         if (kvm_load_segment_descriptor(vcpu, tss->cs, 9, VCPU_SREG_CS))
3579                 return 1;
3580
3581         if (kvm_load_segment_descriptor(vcpu, tss->ss, 1, VCPU_SREG_SS))
3582                 return 1;
3583
3584         if (kvm_load_segment_descriptor(vcpu, tss->ds, 1, VCPU_SREG_DS))
3585                 return 1;
3586
3587         if (kvm_load_segment_descriptor(vcpu, tss->fs, 1, VCPU_SREG_FS))
3588                 return 1;
3589
3590         if (kvm_load_segment_descriptor(vcpu, tss->gs, 1, VCPU_SREG_GS))
3591                 return 1;
3592         return 0;
3593 }
3594
3595 static void save_state_to_tss16(struct kvm_vcpu *vcpu,
3596                                 struct tss_segment_16 *tss)
3597 {
3598         tss->ip = kvm_rip_read(vcpu);
3599         tss->flag = kvm_x86_ops->get_rflags(vcpu);
3600         tss->ax = kvm_register_read(vcpu, VCPU_REGS_RAX);
3601         tss->cx = kvm_register_read(vcpu, VCPU_REGS_RCX);
3602         tss->dx = kvm_register_read(vcpu, VCPU_REGS_RDX);
3603         tss->bx = kvm_register_read(vcpu, VCPU_REGS_RBX);
3604         tss->sp = kvm_register_read(vcpu, VCPU_REGS_RSP);
3605         tss->bp = kvm_register_read(vcpu, VCPU_REGS_RBP);
3606         tss->si = kvm_register_read(vcpu, VCPU_REGS_RSI);
3607         tss->di = kvm_register_read(vcpu, VCPU_REGS_RDI);
3608
3609         tss->es = get_segment_selector(vcpu, VCPU_SREG_ES);
3610         tss->cs = get_segment_selector(vcpu, VCPU_SREG_CS);
3611         tss->ss = get_segment_selector(vcpu, VCPU_SREG_SS);
3612         tss->ds = get_segment_selector(vcpu, VCPU_SREG_DS);
3613         tss->ldt = get_segment_selector(vcpu, VCPU_SREG_LDTR);
3614         tss->prev_task_link = get_segment_selector(vcpu, VCPU_SREG_TR);
3615 }
3616
3617 static int load_state_from_tss16(struct kvm_vcpu *vcpu,
3618                                  struct tss_segment_16 *tss)
3619 {
3620         kvm_rip_write(vcpu, tss->ip);
3621         kvm_x86_ops->set_rflags(vcpu, tss->flag | 2);
3622         kvm_register_write(vcpu, VCPU_REGS_RAX, tss->ax);
3623         kvm_register_write(vcpu, VCPU_REGS_RCX, tss->cx);
3624         kvm_register_write(vcpu, VCPU_REGS_RDX, tss->dx);
3625         kvm_register_write(vcpu, VCPU_REGS_RBX, tss->bx);
3626         kvm_register_write(vcpu, VCPU_REGS_RSP, tss->sp);
3627         kvm_register_write(vcpu, VCPU_REGS_RBP, tss->bp);
3628         kvm_register_write(vcpu, VCPU_REGS_RSI, tss->si);
3629         kvm_register_write(vcpu, VCPU_REGS_RDI, tss->di);
3630
3631         if (kvm_load_segment_descriptor(vcpu, tss->ldt, 0, VCPU_SREG_LDTR))
3632                 return 1;
3633
3634         if (kvm_load_segment_descriptor(vcpu, tss->es, 1, VCPU_SREG_ES))
3635                 return 1;
3636
3637         if (kvm_load_segment_descriptor(vcpu, tss->cs, 9, VCPU_SREG_CS))
3638                 return 1;
3639
3640         if (kvm_load_segment_descriptor(vcpu, tss->ss, 1, VCPU_SREG_SS))
3641                 return 1;
3642
3643         if (kvm_load_segment_descriptor(vcpu, tss->ds, 1, VCPU_SREG_DS))
3644                 return 1;
3645         return 0;
3646 }
3647
3648 static int kvm_task_switch_16(struct kvm_vcpu *vcpu, u16 tss_selector,
3649                        u32 old_tss_base,
3650                        struct desc_struct *nseg_desc)
3651 {
3652         struct tss_segment_16 tss_segment_16;
3653         int ret = 0;
3654
3655         if (kvm_read_guest(vcpu->kvm, old_tss_base, &tss_segment_16,
3656                            sizeof tss_segment_16))
3657                 goto out;
3658
3659         save_state_to_tss16(vcpu, &tss_segment_16);
3660
3661         if (kvm_write_guest(vcpu->kvm, old_tss_base, &tss_segment_16,
3662                             sizeof tss_segment_16))
3663                 goto out;
3664
3665         if (kvm_read_guest(vcpu->kvm, get_tss_base_addr(vcpu, nseg_desc),
3666                            &tss_segment_16, sizeof tss_segment_16))
3667                 goto out;
3668
3669         if (load_state_from_tss16(vcpu, &tss_segment_16))
3670                 goto out;
3671
3672         ret = 1;
3673 out:
3674         return ret;
3675 }
3676
3677 static int kvm_task_switch_32(struct kvm_vcpu *vcpu, u16 tss_selector,
3678                        u32 old_tss_base,
3679                        struct desc_struct *nseg_desc)
3680 {
3681         struct tss_segment_32 tss_segment_32;
3682         int ret = 0;
3683
3684         if (kvm_read_guest(vcpu->kvm, old_tss_base, &tss_segment_32,
3685                            sizeof tss_segment_32))
3686                 goto out;
3687
3688         save_state_to_tss32(vcpu, &tss_segment_32);
3689
3690         if (kvm_write_guest(vcpu->kvm, old_tss_base, &tss_segment_32,
3691                             sizeof tss_segment_32))
3692                 goto out;
3693
3694         if (kvm_read_guest(vcpu->kvm, get_tss_base_addr(vcpu, nseg_desc),
3695                            &tss_segment_32, sizeof tss_segment_32))
3696                 goto out;
3697
3698         if (load_state_from_tss32(vcpu, &tss_segment_32))
3699                 goto out;
3700
3701         ret = 1;
3702 out:
3703         return ret;
3704 }
3705
3706 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int reason)
3707 {
3708         struct kvm_segment tr_seg;
3709         struct desc_struct cseg_desc;
3710         struct desc_struct nseg_desc;
3711         int ret = 0;
3712         u32 old_tss_base = get_segment_base(vcpu, VCPU_SREG_TR);
3713         u16 old_tss_sel = get_segment_selector(vcpu, VCPU_SREG_TR);
3714
3715         old_tss_base = vcpu->arch.mmu.gva_to_gpa(vcpu, old_tss_base);
3716
3717         /* FIXME: Handle errors. Failure to read either TSS or their
3718          * descriptors should generate a pagefault.
3719          */
3720         if (load_guest_segment_descriptor(vcpu, tss_selector, &nseg_desc))
3721                 goto out;
3722
3723         if (load_guest_segment_descriptor(vcpu, old_tss_sel, &cseg_desc))
3724                 goto out;
3725
3726         if (reason != TASK_SWITCH_IRET) {
3727                 int cpl;
3728
3729                 cpl = kvm_x86_ops->get_cpl(vcpu);
3730                 if ((tss_selector & 3) > nseg_desc.dpl || cpl > nseg_desc.dpl) {
3731                         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
3732                         return 1;
3733                 }
3734         }
3735
3736         if (!nseg_desc.p || (nseg_desc.limit0 | nseg_desc.limit << 16) < 0x67) {
3737                 kvm_queue_exception_e(vcpu, TS_VECTOR, tss_selector & 0xfffc);
3738                 return 1;
3739         }
3740
3741         if (reason == TASK_SWITCH_IRET || reason == TASK_SWITCH_JMP) {
3742                 cseg_desc.type &= ~(1 << 1); //clear the B flag
3743                 save_guest_segment_descriptor(vcpu, old_tss_sel, &cseg_desc);
3744         }
3745
3746         if (reason == TASK_SWITCH_IRET) {
3747                 u32 eflags = kvm_x86_ops->get_rflags(vcpu);
3748                 kvm_x86_ops->set_rflags(vcpu, eflags & ~X86_EFLAGS_NT);
3749         }
3750
3751         kvm_x86_ops->skip_emulated_instruction(vcpu);
3752
3753         if (nseg_desc.type & 8)
3754                 ret = kvm_task_switch_32(vcpu, tss_selector, old_tss_base,
3755                                          &nseg_desc);
3756         else
3757                 ret = kvm_task_switch_16(vcpu, tss_selector, old_tss_base,
3758                                          &nseg_desc);
3759
3760         if (reason == TASK_SWITCH_CALL || reason == TASK_SWITCH_GATE) {
3761                 u32 eflags = kvm_x86_ops->get_rflags(vcpu);
3762                 kvm_x86_ops->set_rflags(vcpu, eflags | X86_EFLAGS_NT);
3763         }
3764
3765         if (reason != TASK_SWITCH_IRET) {
3766                 nseg_desc.type |= (1 << 1);
3767                 save_guest_segment_descriptor(vcpu, tss_selector,
3768                                               &nseg_desc);
3769         }
3770
3771         kvm_x86_ops->set_cr0(vcpu, vcpu->arch.cr0 | X86_CR0_TS);
3772         seg_desct_to_kvm_desct(&nseg_desc, tss_selector, &tr_seg);
3773         tr_seg.type = 11;
3774         kvm_set_segment(vcpu, &tr_seg, VCPU_SREG_TR);
3775 out:
3776         return ret;
3777 }
3778 EXPORT_SYMBOL_GPL(kvm_task_switch);
3779
3780 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
3781                                   struct kvm_sregs *sregs)
3782 {
3783         int mmu_reset_needed = 0;
3784         int i, pending_vec, max_bits;
3785         struct descriptor_table dt;
3786
3787         vcpu_load(vcpu);
3788
3789         dt.limit = sregs->idt.limit;
3790         dt.base = sregs->idt.base;
3791         kvm_x86_ops->set_idt(vcpu, &dt);
3792         dt.limit = sregs->gdt.limit;
3793         dt.base = sregs->gdt.base;
3794         kvm_x86_ops->set_gdt(vcpu, &dt);
3795
3796         vcpu->arch.cr2 = sregs->cr2;
3797         mmu_reset_needed |= vcpu->arch.cr3 != sregs->cr3;
3798         vcpu->arch.cr3 = sregs->cr3;
3799
3800         kvm_set_cr8(vcpu, sregs->cr8);
3801
3802         mmu_reset_needed |= vcpu->arch.shadow_efer != sregs->efer;
3803         kvm_x86_ops->set_efer(vcpu, sregs->efer);
3804         kvm_set_apic_base(vcpu, sregs->apic_base);
3805
3806         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
3807
3808         mmu_reset_needed |= vcpu->arch.cr0 != sregs->cr0;
3809         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
3810         vcpu->arch.cr0 = sregs->cr0;
3811
3812         mmu_reset_needed |= vcpu->arch.cr4 != sregs->cr4;
3813         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
3814         if (!is_long_mode(vcpu) && is_pae(vcpu))
3815                 load_pdptrs(vcpu, vcpu->arch.cr3);
3816
3817         if (mmu_reset_needed)
3818                 kvm_mmu_reset_context(vcpu);
3819
3820         if (!irqchip_in_kernel(vcpu->kvm)) {
3821                 memcpy(vcpu->arch.irq_pending, sregs->interrupt_bitmap,
3822                        sizeof vcpu->arch.irq_pending);
3823                 vcpu->arch.irq_summary = 0;
3824                 for (i = 0; i < ARRAY_SIZE(vcpu->arch.irq_pending); ++i)
3825                         if (vcpu->arch.irq_pending[i])
3826                                 __set_bit(i, &vcpu->arch.irq_summary);
3827         } else {
3828                 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
3829                 pending_vec = find_first_bit(
3830                         (const unsigned long *)sregs->interrupt_bitmap,
3831                         max_bits);
3832                 /* Only pending external irq is handled here */
3833                 if (pending_vec < max_bits) {
3834                         kvm_x86_ops->set_irq(vcpu, pending_vec);
3835                         pr_debug("Set back pending irq %d\n",
3836                                  pending_vec);
3837                 }
3838                 kvm_pic_clear_isr_ack(vcpu->kvm);
3839         }
3840
3841         kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
3842         kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
3843         kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
3844         kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
3845         kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
3846         kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
3847
3848         kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
3849         kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
3850
3851         /* Older userspace won't unhalt the vcpu on reset. */
3852         if (vcpu->vcpu_id == 0 && kvm_rip_read(vcpu) == 0xfff0 &&
3853             sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
3854             !(vcpu->arch.cr0 & X86_CR0_PE))
3855                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3856
3857         vcpu_put(vcpu);
3858
3859         return 0;
3860 }
3861
3862 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
3863                                         struct kvm_guest_debug *dbg)
3864 {
3865         int i, r;
3866
3867         vcpu_load(vcpu);
3868
3869         if ((dbg->control & (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP)) ==
3870             (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP)) {
3871                 for (i = 0; i < KVM_NR_DB_REGS; ++i)
3872                         vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
3873                 vcpu->arch.switch_db_regs =
3874                         (dbg->arch.debugreg[7] & DR7_BP_EN_MASK);
3875         } else {
3876                 for (i = 0; i < KVM_NR_DB_REGS; i++)
3877                         vcpu->arch.eff_db[i] = vcpu->arch.db[i];
3878                 vcpu->arch.switch_db_regs = (vcpu->arch.dr7 & DR7_BP_EN_MASK);
3879         }
3880
3881         r = kvm_x86_ops->set_guest_debug(vcpu, dbg);
3882
3883         if (dbg->control & KVM_GUESTDBG_INJECT_DB)
3884                 kvm_queue_exception(vcpu, DB_VECTOR);
3885         else if (dbg->control & KVM_GUESTDBG_INJECT_BP)
3886                 kvm_queue_exception(vcpu, BP_VECTOR);
3887
3888         vcpu_put(vcpu);
3889
3890         return r;
3891 }
3892
3893 /*
3894  * fxsave fpu state.  Taken from x86_64/processor.h.  To be killed when
3895  * we have asm/x86/processor.h
3896  */
3897 struct fxsave {
3898         u16     cwd;
3899         u16     swd;
3900         u16     twd;
3901         u16     fop;
3902         u64     rip;
3903         u64     rdp;
3904         u32     mxcsr;
3905         u32     mxcsr_mask;
3906         u32     st_space[32];   /* 8*16 bytes for each FP-reg = 128 bytes */
3907 #ifdef CONFIG_X86_64
3908         u32     xmm_space[64];  /* 16*16 bytes for each XMM-reg = 256 bytes */
3909 #else
3910         u32     xmm_space[32];  /* 8*16 bytes for each XMM-reg = 128 bytes */
3911 #endif
3912 };
3913
3914 /*
3915  * Translate a guest virtual address to a guest physical address.
3916  */
3917 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
3918                                     struct kvm_translation *tr)
3919 {
3920         unsigned long vaddr = tr->linear_address;
3921         gpa_t gpa;
3922
3923         vcpu_load(vcpu);
3924         down_read(&vcpu->kvm->slots_lock);
3925         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, vaddr);
3926         up_read(&vcpu->kvm->slots_lock);
3927         tr->physical_address = gpa;
3928         tr->valid = gpa != UNMAPPED_GVA;
3929         tr->writeable = 1;
3930         tr->usermode = 0;
3931         vcpu_put(vcpu);
3932
3933         return 0;
3934 }
3935
3936 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
3937 {
3938         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
3939
3940         vcpu_load(vcpu);
3941
3942         memcpy(fpu->fpr, fxsave->st_space, 128);
3943         fpu->fcw = fxsave->cwd;
3944         fpu->fsw = fxsave->swd;
3945         fpu->ftwx = fxsave->twd;
3946         fpu->last_opcode = fxsave->fop;
3947         fpu->last_ip = fxsave->rip;
3948         fpu->last_dp = fxsave->rdp;
3949         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
3950
3951         vcpu_put(vcpu);
3952
3953         return 0;
3954 }
3955
3956 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
3957 {
3958         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
3959
3960         vcpu_load(vcpu);
3961
3962         memcpy(fxsave->st_space, fpu->fpr, 128);
3963         fxsave->cwd = fpu->fcw;
3964         fxsave->swd = fpu->fsw;
3965         fxsave->twd = fpu->ftwx;
3966         fxsave->fop = fpu->last_opcode;
3967         fxsave->rip = fpu->last_ip;
3968         fxsave->rdp = fpu->last_dp;
3969         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
3970
3971         vcpu_put(vcpu);
3972
3973         return 0;
3974 }
3975
3976 void fx_init(struct kvm_vcpu *vcpu)
3977 {
3978         unsigned after_mxcsr_mask;
3979
3980         /*
3981          * Touch the fpu the first time in non atomic context as if
3982          * this is the first fpu instruction the exception handler
3983          * will fire before the instruction returns and it'll have to
3984          * allocate ram with GFP_KERNEL.
3985          */
3986         if (!used_math())
3987                 kvm_fx_save(&vcpu->arch.host_fx_image);
3988
3989         /* Initialize guest FPU by resetting ours and saving into guest's */
3990         preempt_disable();
3991         kvm_fx_save(&vcpu->arch.host_fx_image);
3992         kvm_fx_finit();
3993         kvm_fx_save(&vcpu->arch.guest_fx_image);
3994         kvm_fx_restore(&vcpu->arch.host_fx_image);
3995         preempt_enable();
3996
3997         vcpu->arch.cr0 |= X86_CR0_ET;
3998         after_mxcsr_mask = offsetof(struct i387_fxsave_struct, st_space);
3999         vcpu->arch.guest_fx_image.mxcsr = 0x1f80;
4000         memset((void *)&vcpu->arch.guest_fx_image + after_mxcsr_mask,
4001                0, sizeof(struct i387_fxsave_struct) - after_mxcsr_mask);
4002 }
4003 EXPORT_SYMBOL_GPL(fx_init);
4004
4005 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
4006 {
4007         if (!vcpu->fpu_active || vcpu->guest_fpu_loaded)
4008                 return;
4009
4010         vcpu->guest_fpu_loaded = 1;
4011         kvm_fx_save(&vcpu->arch.host_fx_image);
4012         kvm_fx_restore(&vcpu->arch.guest_fx_image);
4013 }
4014 EXPORT_SYMBOL_GPL(kvm_load_guest_fpu);
4015
4016 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
4017 {
4018         if (!vcpu->guest_fpu_loaded)
4019                 return;
4020
4021         vcpu->guest_fpu_loaded = 0;
4022         kvm_fx_save(&vcpu->arch.guest_fx_image);
4023         kvm_fx_restore(&vcpu->arch.host_fx_image);
4024         ++vcpu->stat.fpu_reload;
4025 }
4026 EXPORT_SYMBOL_GPL(kvm_put_guest_fpu);
4027
4028 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
4029 {
4030         kvm_x86_ops->vcpu_free(vcpu);
4031 }
4032
4033 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
4034                                                 unsigned int id)
4035 {
4036         return kvm_x86_ops->vcpu_create(kvm, id);
4037 }
4038
4039 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
4040 {
4041         int r;
4042
4043         /* We do fxsave: this must be aligned. */
4044         BUG_ON((unsigned long)&vcpu->arch.host_fx_image & 0xF);
4045
4046         vcpu->arch.mtrr_state.have_fixed = 1;
4047         vcpu_load(vcpu);
4048         r = kvm_arch_vcpu_reset(vcpu);
4049         if (r == 0)
4050                 r = kvm_mmu_setup(vcpu);
4051         vcpu_put(vcpu);
4052         if (r < 0)
4053                 goto free_vcpu;
4054
4055         return 0;
4056 free_vcpu:
4057         kvm_x86_ops->vcpu_free(vcpu);
4058         return r;
4059 }
4060
4061 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
4062 {
4063         vcpu_load(vcpu);
4064         kvm_mmu_unload(vcpu);
4065         vcpu_put(vcpu);
4066
4067         kvm_x86_ops->vcpu_free(vcpu);
4068 }
4069
4070 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
4071 {
4072         vcpu->arch.nmi_pending = false;
4073         vcpu->arch.nmi_injected = false;
4074
4075         vcpu->arch.switch_db_regs = 0;
4076         memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
4077         vcpu->arch.dr6 = DR6_FIXED_1;
4078         vcpu->arch.dr7 = DR7_FIXED_1;
4079
4080         return kvm_x86_ops->vcpu_reset(vcpu);
4081 }
4082
4083 void kvm_arch_hardware_enable(void *garbage)
4084 {
4085         kvm_x86_ops->hardware_enable(garbage);
4086 }
4087
4088 void kvm_arch_hardware_disable(void *garbage)
4089 {
4090         kvm_x86_ops->hardware_disable(garbage);
4091 }
4092
4093 int kvm_arch_hardware_setup(void)
4094 {
4095         return kvm_x86_ops->hardware_setup();
4096 }
4097
4098 void kvm_arch_hardware_unsetup(void)
4099 {
4100         kvm_x86_ops->hardware_unsetup();
4101 }
4102
4103 void kvm_arch_check_processor_compat(void *rtn)
4104 {
4105         kvm_x86_ops->check_processor_compatibility(rtn);
4106 }
4107
4108 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
4109 {
4110         struct page *page;
4111         struct kvm *kvm;
4112         int r;
4113
4114         BUG_ON(vcpu->kvm == NULL);
4115         kvm = vcpu->kvm;
4116
4117         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
4118         if (!irqchip_in_kernel(kvm) || vcpu->vcpu_id == 0)
4119                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
4120         else
4121                 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
4122
4123         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
4124         if (!page) {
4125                 r = -ENOMEM;
4126                 goto fail;
4127         }
4128         vcpu->arch.pio_data = page_address(page);
4129
4130         r = kvm_mmu_create(vcpu);
4131         if (r < 0)
4132                 goto fail_free_pio_data;
4133
4134         if (irqchip_in_kernel(kvm)) {
4135                 r = kvm_create_lapic(vcpu);
4136                 if (r < 0)
4137                         goto fail_mmu_destroy;
4138         }
4139
4140         return 0;
4141
4142 fail_mmu_destroy:
4143         kvm_mmu_destroy(vcpu);
4144 fail_free_pio_data:
4145         free_page((unsigned long)vcpu->arch.pio_data);
4146 fail:
4147         return r;
4148 }
4149
4150 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
4151 {
4152         kvm_free_lapic(vcpu);
4153         down_read(&vcpu->kvm->slots_lock);
4154         kvm_mmu_destroy(vcpu);
4155         up_read(&vcpu->kvm->slots_lock);
4156         free_page((unsigned long)vcpu->arch.pio_data);
4157 }
4158
4159 struct  kvm *kvm_arch_create_vm(void)
4160 {
4161         struct kvm *kvm = kzalloc(sizeof(struct kvm), GFP_KERNEL);
4162
4163         if (!kvm)
4164                 return ERR_PTR(-ENOMEM);
4165
4166         INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
4167         INIT_LIST_HEAD(&kvm->arch.oos_global_pages);
4168         INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
4169
4170         /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
4171         set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
4172
4173         return kvm;
4174 }
4175
4176 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
4177 {
4178         vcpu_load(vcpu);
4179         kvm_mmu_unload(vcpu);
4180         vcpu_put(vcpu);
4181 }
4182
4183 static void kvm_free_vcpus(struct kvm *kvm)
4184 {
4185         unsigned int i;
4186
4187         /*
4188          * Unpin any mmu pages first.
4189          */
4190         for (i = 0; i < KVM_MAX_VCPUS; ++i)
4191                 if (kvm->vcpus[i])
4192                         kvm_unload_vcpu_mmu(kvm->vcpus[i]);
4193         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
4194                 if (kvm->vcpus[i]) {
4195                         kvm_arch_vcpu_free(kvm->vcpus[i]);
4196                         kvm->vcpus[i] = NULL;
4197                 }
4198         }
4199
4200 }
4201
4202 void kvm_arch_sync_events(struct kvm *kvm)
4203 {
4204         kvm_free_all_assigned_devices(kvm);
4205 }
4206
4207 void kvm_arch_destroy_vm(struct kvm *kvm)
4208 {
4209         kvm_iommu_unmap_guest(kvm);
4210         kvm_free_pit(kvm);
4211         kfree(kvm->arch.vpic);
4212         kfree(kvm->arch.vioapic);
4213         kvm_free_vcpus(kvm);
4214         kvm_free_physmem(kvm);
4215         if (kvm->arch.apic_access_page)
4216                 put_page(kvm->arch.apic_access_page);
4217         if (kvm->arch.ept_identity_pagetable)
4218                 put_page(kvm->arch.ept_identity_pagetable);
4219         kfree(kvm);
4220 }
4221
4222 int kvm_arch_set_memory_region(struct kvm *kvm,
4223                                 struct kvm_userspace_memory_region *mem,
4224                                 struct kvm_memory_slot old,
4225                                 int user_alloc)
4226 {
4227         int npages = mem->memory_size >> PAGE_SHIFT;
4228         struct kvm_memory_slot *memslot = &kvm->memslots[mem->slot];
4229
4230         /*To keep backward compatibility with older userspace,
4231          *x86 needs to hanlde !user_alloc case.
4232          */
4233         if (!user_alloc) {
4234                 if (npages && !old.rmap) {
4235                         unsigned long userspace_addr;
4236
4237                         down_write(&current->mm->mmap_sem);
4238                         userspace_addr = do_mmap(NULL, 0,
4239                                                  npages * PAGE_SIZE,
4240                                                  PROT_READ | PROT_WRITE,
4241                                                  MAP_PRIVATE | MAP_ANONYMOUS,
4242                                                  0);
4243                         up_write(&current->mm->mmap_sem);
4244
4245                         if (IS_ERR((void *)userspace_addr))
4246                                 return PTR_ERR((void *)userspace_addr);
4247
4248                         /* set userspace_addr atomically for kvm_hva_to_rmapp */
4249                         spin_lock(&kvm->mmu_lock);
4250                         memslot->userspace_addr = userspace_addr;
4251                         spin_unlock(&kvm->mmu_lock);
4252                 } else {
4253                         if (!old.user_alloc && old.rmap) {
4254                                 int ret;
4255
4256                                 down_write(&current->mm->mmap_sem);
4257                                 ret = do_munmap(current->mm, old.userspace_addr,
4258                                                 old.npages * PAGE_SIZE);
4259                                 up_write(&current->mm->mmap_sem);
4260                                 if (ret < 0)
4261                                         printk(KERN_WARNING
4262                                        "kvm_vm_ioctl_set_memory_region: "
4263                                        "failed to munmap memory\n");
4264                         }
4265                 }
4266         }
4267
4268         if (!kvm->arch.n_requested_mmu_pages) {
4269                 unsigned int nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
4270                 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
4271         }
4272
4273         kvm_mmu_slot_remove_write_access(kvm, mem->slot);
4274         kvm_flush_remote_tlbs(kvm);
4275
4276         return 0;
4277 }
4278
4279 void kvm_arch_flush_shadow(struct kvm *kvm)
4280 {
4281         kvm_mmu_zap_all(kvm);
4282 }
4283
4284 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
4285 {
4286         return vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE
4287                || vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
4288                || vcpu->arch.nmi_pending;
4289 }
4290
4291 static void vcpu_kick_intr(void *info)
4292 {
4293 #ifdef DEBUG
4294         struct kvm_vcpu *vcpu = (struct kvm_vcpu *)info;
4295         printk(KERN_DEBUG "vcpu_kick_intr %p \n", vcpu);
4296 #endif
4297 }
4298
4299 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
4300 {
4301         int ipi_pcpu = vcpu->cpu;
4302         int cpu = get_cpu();
4303
4304         if (waitqueue_active(&vcpu->wq)) {
4305                 wake_up_interruptible(&vcpu->wq);
4306                 ++vcpu->stat.halt_wakeup;
4307         }
4308         /*
4309          * We may be called synchronously with irqs disabled in guest mode,
4310          * So need not to call smp_call_function_single() in that case.
4311          */
4312         if (vcpu->guest_mode && vcpu->cpu != cpu)
4313                 smp_call_function_single(ipi_pcpu, vcpu_kick_intr, vcpu, 0);
4314         put_cpu();
4315 }