KVM: local APIC TPR access reporting facility
[linux-2.6.git] / arch / x86 / kvm / x86.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * derived from drivers/kvm/kvm_main.c
5  *
6  * Copyright (C) 2006 Qumranet, Inc.
7  *
8  * Authors:
9  *   Avi Kivity   <avi@qumranet.com>
10  *   Yaniv Kamay  <yaniv@qumranet.com>
11  *
12  * This work is licensed under the terms of the GNU GPL, version 2.  See
13  * the COPYING file in the top-level directory.
14  *
15  */
16
17 #include <linux/kvm_host.h>
18 #include "segment_descriptor.h"
19 #include "irq.h"
20 #include "mmu.h"
21
22 #include <linux/kvm.h>
23 #include <linux/fs.h>
24 #include <linux/vmalloc.h>
25 #include <linux/module.h>
26 #include <linux/mman.h>
27 #include <linux/highmem.h>
28
29 #include <asm/uaccess.h>
30 #include <asm/msr.h>
31
32 #define MAX_IO_MSRS 256
33 #define CR0_RESERVED_BITS                                               \
34         (~(unsigned long)(X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS \
35                           | X86_CR0_ET | X86_CR0_NE | X86_CR0_WP | X86_CR0_AM \
36                           | X86_CR0_NW | X86_CR0_CD | X86_CR0_PG))
37 #define CR4_RESERVED_BITS                                               \
38         (~(unsigned long)(X86_CR4_VME | X86_CR4_PVI | X86_CR4_TSD | X86_CR4_DE\
39                           | X86_CR4_PSE | X86_CR4_PAE | X86_CR4_MCE     \
40                           | X86_CR4_PGE | X86_CR4_PCE | X86_CR4_OSFXSR  \
41                           | X86_CR4_OSXMMEXCPT | X86_CR4_VMXE))
42
43 #define CR8_RESERVED_BITS (~(unsigned long)X86_CR8_TPR)
44 #define EFER_RESERVED_BITS 0xfffffffffffff2fe
45
46 #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
47 #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
48
49 struct kvm_x86_ops *kvm_x86_ops;
50
51 struct kvm_stats_debugfs_item debugfs_entries[] = {
52         { "pf_fixed", VCPU_STAT(pf_fixed) },
53         { "pf_guest", VCPU_STAT(pf_guest) },
54         { "tlb_flush", VCPU_STAT(tlb_flush) },
55         { "invlpg", VCPU_STAT(invlpg) },
56         { "exits", VCPU_STAT(exits) },
57         { "io_exits", VCPU_STAT(io_exits) },
58         { "mmio_exits", VCPU_STAT(mmio_exits) },
59         { "signal_exits", VCPU_STAT(signal_exits) },
60         { "irq_window", VCPU_STAT(irq_window_exits) },
61         { "halt_exits", VCPU_STAT(halt_exits) },
62         { "halt_wakeup", VCPU_STAT(halt_wakeup) },
63         { "request_irq", VCPU_STAT(request_irq_exits) },
64         { "irq_exits", VCPU_STAT(irq_exits) },
65         { "host_state_reload", VCPU_STAT(host_state_reload) },
66         { "efer_reload", VCPU_STAT(efer_reload) },
67         { "fpu_reload", VCPU_STAT(fpu_reload) },
68         { "insn_emulation", VCPU_STAT(insn_emulation) },
69         { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
70         { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
71         { "mmu_pte_write", VM_STAT(mmu_pte_write) },
72         { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
73         { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
74         { "mmu_flooded", VM_STAT(mmu_flooded) },
75         { "mmu_recycled", VM_STAT(mmu_recycled) },
76         { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
77         { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
78         { NULL }
79 };
80
81
82 unsigned long segment_base(u16 selector)
83 {
84         struct descriptor_table gdt;
85         struct segment_descriptor *d;
86         unsigned long table_base;
87         unsigned long v;
88
89         if (selector == 0)
90                 return 0;
91
92         asm("sgdt %0" : "=m"(gdt));
93         table_base = gdt.base;
94
95         if (selector & 4) {           /* from ldt */
96                 u16 ldt_selector;
97
98                 asm("sldt %0" : "=g"(ldt_selector));
99                 table_base = segment_base(ldt_selector);
100         }
101         d = (struct segment_descriptor *)(table_base + (selector & ~7));
102         v = d->base_low | ((unsigned long)d->base_mid << 16) |
103                 ((unsigned long)d->base_high << 24);
104 #ifdef CONFIG_X86_64
105         if (d->system == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
106                 v |= ((unsigned long) \
107                       ((struct segment_descriptor_64 *)d)->base_higher) << 32;
108 #endif
109         return v;
110 }
111 EXPORT_SYMBOL_GPL(segment_base);
112
113 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
114 {
115         if (irqchip_in_kernel(vcpu->kvm))
116                 return vcpu->arch.apic_base;
117         else
118                 return vcpu->arch.apic_base;
119 }
120 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
121
122 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
123 {
124         /* TODO: reserve bits check */
125         if (irqchip_in_kernel(vcpu->kvm))
126                 kvm_lapic_set_base(vcpu, data);
127         else
128                 vcpu->arch.apic_base = data;
129 }
130 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
131
132 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
133 {
134         WARN_ON(vcpu->arch.exception.pending);
135         vcpu->arch.exception.pending = true;
136         vcpu->arch.exception.has_error_code = false;
137         vcpu->arch.exception.nr = nr;
138 }
139 EXPORT_SYMBOL_GPL(kvm_queue_exception);
140
141 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, unsigned long addr,
142                            u32 error_code)
143 {
144         ++vcpu->stat.pf_guest;
145         if (vcpu->arch.exception.pending && vcpu->arch.exception.nr == PF_VECTOR) {
146                 printk(KERN_DEBUG "kvm: inject_page_fault:"
147                        " double fault 0x%lx\n", addr);
148                 vcpu->arch.exception.nr = DF_VECTOR;
149                 vcpu->arch.exception.error_code = 0;
150                 return;
151         }
152         vcpu->arch.cr2 = addr;
153         kvm_queue_exception_e(vcpu, PF_VECTOR, error_code);
154 }
155
156 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
157 {
158         WARN_ON(vcpu->arch.exception.pending);
159         vcpu->arch.exception.pending = true;
160         vcpu->arch.exception.has_error_code = true;
161         vcpu->arch.exception.nr = nr;
162         vcpu->arch.exception.error_code = error_code;
163 }
164 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
165
166 static void __queue_exception(struct kvm_vcpu *vcpu)
167 {
168         kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
169                                      vcpu->arch.exception.has_error_code,
170                                      vcpu->arch.exception.error_code);
171 }
172
173 /*
174  * Load the pae pdptrs.  Return true is they are all valid.
175  */
176 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
177 {
178         gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
179         unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
180         int i;
181         int ret;
182         u64 pdpte[ARRAY_SIZE(vcpu->arch.pdptrs)];
183
184         mutex_lock(&vcpu->kvm->lock);
185         ret = kvm_read_guest_page(vcpu->kvm, pdpt_gfn, pdpte,
186                                   offset * sizeof(u64), sizeof(pdpte));
187         if (ret < 0) {
188                 ret = 0;
189                 goto out;
190         }
191         for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
192                 if ((pdpte[i] & 1) && (pdpte[i] & 0xfffffff0000001e6ull)) {
193                         ret = 0;
194                         goto out;
195                 }
196         }
197         ret = 1;
198
199         memcpy(vcpu->arch.pdptrs, pdpte, sizeof(vcpu->arch.pdptrs));
200 out:
201         mutex_unlock(&vcpu->kvm->lock);
202
203         return ret;
204 }
205
206 static bool pdptrs_changed(struct kvm_vcpu *vcpu)
207 {
208         u64 pdpte[ARRAY_SIZE(vcpu->arch.pdptrs)];
209         bool changed = true;
210         int r;
211
212         if (is_long_mode(vcpu) || !is_pae(vcpu))
213                 return false;
214
215         mutex_lock(&vcpu->kvm->lock);
216         r = kvm_read_guest(vcpu->kvm, vcpu->arch.cr3 & ~31u, pdpte, sizeof(pdpte));
217         if (r < 0)
218                 goto out;
219         changed = memcmp(pdpte, vcpu->arch.pdptrs, sizeof(pdpte)) != 0;
220 out:
221         mutex_unlock(&vcpu->kvm->lock);
222
223         return changed;
224 }
225
226 void set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
227 {
228         if (cr0 & CR0_RESERVED_BITS) {
229                 printk(KERN_DEBUG "set_cr0: 0x%lx #GP, reserved bits 0x%lx\n",
230                        cr0, vcpu->arch.cr0);
231                 kvm_inject_gp(vcpu, 0);
232                 return;
233         }
234
235         if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD)) {
236                 printk(KERN_DEBUG "set_cr0: #GP, CD == 0 && NW == 1\n");
237                 kvm_inject_gp(vcpu, 0);
238                 return;
239         }
240
241         if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE)) {
242                 printk(KERN_DEBUG "set_cr0: #GP, set PG flag "
243                        "and a clear PE flag\n");
244                 kvm_inject_gp(vcpu, 0);
245                 return;
246         }
247
248         if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
249 #ifdef CONFIG_X86_64
250                 if ((vcpu->arch.shadow_efer & EFER_LME)) {
251                         int cs_db, cs_l;
252
253                         if (!is_pae(vcpu)) {
254                                 printk(KERN_DEBUG "set_cr0: #GP, start paging "
255                                        "in long mode while PAE is disabled\n");
256                                 kvm_inject_gp(vcpu, 0);
257                                 return;
258                         }
259                         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
260                         if (cs_l) {
261                                 printk(KERN_DEBUG "set_cr0: #GP, start paging "
262                                        "in long mode while CS.L == 1\n");
263                                 kvm_inject_gp(vcpu, 0);
264                                 return;
265
266                         }
267                 } else
268 #endif
269                 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.cr3)) {
270                         printk(KERN_DEBUG "set_cr0: #GP, pdptrs "
271                                "reserved bits\n");
272                         kvm_inject_gp(vcpu, 0);
273                         return;
274                 }
275
276         }
277
278         kvm_x86_ops->set_cr0(vcpu, cr0);
279         vcpu->arch.cr0 = cr0;
280
281         mutex_lock(&vcpu->kvm->lock);
282         kvm_mmu_reset_context(vcpu);
283         mutex_unlock(&vcpu->kvm->lock);
284         return;
285 }
286 EXPORT_SYMBOL_GPL(set_cr0);
287
288 void lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
289 {
290         set_cr0(vcpu, (vcpu->arch.cr0 & ~0x0ful) | (msw & 0x0f));
291 }
292 EXPORT_SYMBOL_GPL(lmsw);
293
294 void set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
295 {
296         if (cr4 & CR4_RESERVED_BITS) {
297                 printk(KERN_DEBUG "set_cr4: #GP, reserved bits\n");
298                 kvm_inject_gp(vcpu, 0);
299                 return;
300         }
301
302         if (is_long_mode(vcpu)) {
303                 if (!(cr4 & X86_CR4_PAE)) {
304                         printk(KERN_DEBUG "set_cr4: #GP, clearing PAE while "
305                                "in long mode\n");
306                         kvm_inject_gp(vcpu, 0);
307                         return;
308                 }
309         } else if (is_paging(vcpu) && !is_pae(vcpu) && (cr4 & X86_CR4_PAE)
310                    && !load_pdptrs(vcpu, vcpu->arch.cr3)) {
311                 printk(KERN_DEBUG "set_cr4: #GP, pdptrs reserved bits\n");
312                 kvm_inject_gp(vcpu, 0);
313                 return;
314         }
315
316         if (cr4 & X86_CR4_VMXE) {
317                 printk(KERN_DEBUG "set_cr4: #GP, setting VMXE\n");
318                 kvm_inject_gp(vcpu, 0);
319                 return;
320         }
321         kvm_x86_ops->set_cr4(vcpu, cr4);
322         vcpu->arch.cr4 = cr4;
323         mutex_lock(&vcpu->kvm->lock);
324         kvm_mmu_reset_context(vcpu);
325         mutex_unlock(&vcpu->kvm->lock);
326 }
327 EXPORT_SYMBOL_GPL(set_cr4);
328
329 void set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
330 {
331         if (cr3 == vcpu->arch.cr3 && !pdptrs_changed(vcpu)) {
332                 kvm_mmu_flush_tlb(vcpu);
333                 return;
334         }
335
336         if (is_long_mode(vcpu)) {
337                 if (cr3 & CR3_L_MODE_RESERVED_BITS) {
338                         printk(KERN_DEBUG "set_cr3: #GP, reserved bits\n");
339                         kvm_inject_gp(vcpu, 0);
340                         return;
341                 }
342         } else {
343                 if (is_pae(vcpu)) {
344                         if (cr3 & CR3_PAE_RESERVED_BITS) {
345                                 printk(KERN_DEBUG
346                                        "set_cr3: #GP, reserved bits\n");
347                                 kvm_inject_gp(vcpu, 0);
348                                 return;
349                         }
350                         if (is_paging(vcpu) && !load_pdptrs(vcpu, cr3)) {
351                                 printk(KERN_DEBUG "set_cr3: #GP, pdptrs "
352                                        "reserved bits\n");
353                                 kvm_inject_gp(vcpu, 0);
354                                 return;
355                         }
356                 }
357                 /*
358                  * We don't check reserved bits in nonpae mode, because
359                  * this isn't enforced, and VMware depends on this.
360                  */
361         }
362
363         mutex_lock(&vcpu->kvm->lock);
364         /*
365          * Does the new cr3 value map to physical memory? (Note, we
366          * catch an invalid cr3 even in real-mode, because it would
367          * cause trouble later on when we turn on paging anyway.)
368          *
369          * A real CPU would silently accept an invalid cr3 and would
370          * attempt to use it - with largely undefined (and often hard
371          * to debug) behavior on the guest side.
372          */
373         if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
374                 kvm_inject_gp(vcpu, 0);
375         else {
376                 vcpu->arch.cr3 = cr3;
377                 vcpu->arch.mmu.new_cr3(vcpu);
378         }
379         mutex_unlock(&vcpu->kvm->lock);
380 }
381 EXPORT_SYMBOL_GPL(set_cr3);
382
383 void set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
384 {
385         if (cr8 & CR8_RESERVED_BITS) {
386                 printk(KERN_DEBUG "set_cr8: #GP, reserved bits 0x%lx\n", cr8);
387                 kvm_inject_gp(vcpu, 0);
388                 return;
389         }
390         if (irqchip_in_kernel(vcpu->kvm))
391                 kvm_lapic_set_tpr(vcpu, cr8);
392         else
393                 vcpu->arch.cr8 = cr8;
394 }
395 EXPORT_SYMBOL_GPL(set_cr8);
396
397 unsigned long get_cr8(struct kvm_vcpu *vcpu)
398 {
399         if (irqchip_in_kernel(vcpu->kvm))
400                 return kvm_lapic_get_cr8(vcpu);
401         else
402                 return vcpu->arch.cr8;
403 }
404 EXPORT_SYMBOL_GPL(get_cr8);
405
406 /*
407  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
408  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
409  *
410  * This list is modified at module load time to reflect the
411  * capabilities of the host cpu.
412  */
413 static u32 msrs_to_save[] = {
414         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
415         MSR_K6_STAR,
416 #ifdef CONFIG_X86_64
417         MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
418 #endif
419         MSR_IA32_TIME_STAMP_COUNTER,
420 };
421
422 static unsigned num_msrs_to_save;
423
424 static u32 emulated_msrs[] = {
425         MSR_IA32_MISC_ENABLE,
426 };
427
428 #ifdef CONFIG_X86_64
429
430 static void set_efer(struct kvm_vcpu *vcpu, u64 efer)
431 {
432         if (efer & EFER_RESERVED_BITS) {
433                 printk(KERN_DEBUG "set_efer: 0x%llx #GP, reserved bits\n",
434                        efer);
435                 kvm_inject_gp(vcpu, 0);
436                 return;
437         }
438
439         if (is_paging(vcpu)
440             && (vcpu->arch.shadow_efer & EFER_LME) != (efer & EFER_LME)) {
441                 printk(KERN_DEBUG "set_efer: #GP, change LME while paging\n");
442                 kvm_inject_gp(vcpu, 0);
443                 return;
444         }
445
446         kvm_x86_ops->set_efer(vcpu, efer);
447
448         efer &= ~EFER_LMA;
449         efer |= vcpu->arch.shadow_efer & EFER_LMA;
450
451         vcpu->arch.shadow_efer = efer;
452 }
453
454 #endif
455
456 /*
457  * Writes msr value into into the appropriate "register".
458  * Returns 0 on success, non-0 otherwise.
459  * Assumes vcpu_load() was already called.
460  */
461 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
462 {
463         return kvm_x86_ops->set_msr(vcpu, msr_index, data);
464 }
465
466 /*
467  * Adapt set_msr() to msr_io()'s calling convention
468  */
469 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
470 {
471         return kvm_set_msr(vcpu, index, *data);
472 }
473
474
475 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
476 {
477         switch (msr) {
478 #ifdef CONFIG_X86_64
479         case MSR_EFER:
480                 set_efer(vcpu, data);
481                 break;
482 #endif
483         case MSR_IA32_MC0_STATUS:
484                 pr_unimpl(vcpu, "%s: MSR_IA32_MC0_STATUS 0x%llx, nop\n",
485                        __FUNCTION__, data);
486                 break;
487         case MSR_IA32_MCG_STATUS:
488                 pr_unimpl(vcpu, "%s: MSR_IA32_MCG_STATUS 0x%llx, nop\n",
489                         __FUNCTION__, data);
490                 break;
491         case MSR_IA32_UCODE_REV:
492         case MSR_IA32_UCODE_WRITE:
493         case 0x200 ... 0x2ff: /* MTRRs */
494                 break;
495         case MSR_IA32_APICBASE:
496                 kvm_set_apic_base(vcpu, data);
497                 break;
498         case MSR_IA32_MISC_ENABLE:
499                 vcpu->arch.ia32_misc_enable_msr = data;
500                 break;
501         default:
502                 pr_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n", msr, data);
503                 return 1;
504         }
505         return 0;
506 }
507 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
508
509
510 /*
511  * Reads an msr value (of 'msr_index') into 'pdata'.
512  * Returns 0 on success, non-0 otherwise.
513  * Assumes vcpu_load() was already called.
514  */
515 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
516 {
517         return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
518 }
519
520 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
521 {
522         u64 data;
523
524         switch (msr) {
525         case 0xc0010010: /* SYSCFG */
526         case 0xc0010015: /* HWCR */
527         case MSR_IA32_PLATFORM_ID:
528         case MSR_IA32_P5_MC_ADDR:
529         case MSR_IA32_P5_MC_TYPE:
530         case MSR_IA32_MC0_CTL:
531         case MSR_IA32_MCG_STATUS:
532         case MSR_IA32_MCG_CAP:
533         case MSR_IA32_MC0_MISC:
534         case MSR_IA32_MC0_MISC+4:
535         case MSR_IA32_MC0_MISC+8:
536         case MSR_IA32_MC0_MISC+12:
537         case MSR_IA32_MC0_MISC+16:
538         case MSR_IA32_UCODE_REV:
539         case MSR_IA32_PERF_STATUS:
540         case MSR_IA32_EBL_CR_POWERON:
541                 /* MTRR registers */
542         case 0xfe:
543         case 0x200 ... 0x2ff:
544                 data = 0;
545                 break;
546         case 0xcd: /* fsb frequency */
547                 data = 3;
548                 break;
549         case MSR_IA32_APICBASE:
550                 data = kvm_get_apic_base(vcpu);
551                 break;
552         case MSR_IA32_MISC_ENABLE:
553                 data = vcpu->arch.ia32_misc_enable_msr;
554                 break;
555 #ifdef CONFIG_X86_64
556         case MSR_EFER:
557                 data = vcpu->arch.shadow_efer;
558                 break;
559 #endif
560         default:
561                 pr_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
562                 return 1;
563         }
564         *pdata = data;
565         return 0;
566 }
567 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
568
569 /*
570  * Read or write a bunch of msrs. All parameters are kernel addresses.
571  *
572  * @return number of msrs set successfully.
573  */
574 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
575                     struct kvm_msr_entry *entries,
576                     int (*do_msr)(struct kvm_vcpu *vcpu,
577                                   unsigned index, u64 *data))
578 {
579         int i;
580
581         vcpu_load(vcpu);
582
583         for (i = 0; i < msrs->nmsrs; ++i)
584                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
585                         break;
586
587         vcpu_put(vcpu);
588
589         return i;
590 }
591
592 /*
593  * Read or write a bunch of msrs. Parameters are user addresses.
594  *
595  * @return number of msrs set successfully.
596  */
597 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
598                   int (*do_msr)(struct kvm_vcpu *vcpu,
599                                 unsigned index, u64 *data),
600                   int writeback)
601 {
602         struct kvm_msrs msrs;
603         struct kvm_msr_entry *entries;
604         int r, n;
605         unsigned size;
606
607         r = -EFAULT;
608         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
609                 goto out;
610
611         r = -E2BIG;
612         if (msrs.nmsrs >= MAX_IO_MSRS)
613                 goto out;
614
615         r = -ENOMEM;
616         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
617         entries = vmalloc(size);
618         if (!entries)
619                 goto out;
620
621         r = -EFAULT;
622         if (copy_from_user(entries, user_msrs->entries, size))
623                 goto out_free;
624
625         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
626         if (r < 0)
627                 goto out_free;
628
629         r = -EFAULT;
630         if (writeback && copy_to_user(user_msrs->entries, entries, size))
631                 goto out_free;
632
633         r = n;
634
635 out_free:
636         vfree(entries);
637 out:
638         return r;
639 }
640
641 /*
642  * Make sure that a cpu that is being hot-unplugged does not have any vcpus
643  * cached on it.
644  */
645 void decache_vcpus_on_cpu(int cpu)
646 {
647         struct kvm *vm;
648         struct kvm_vcpu *vcpu;
649         int i;
650
651         spin_lock(&kvm_lock);
652         list_for_each_entry(vm, &vm_list, vm_list)
653                 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
654                         vcpu = vm->vcpus[i];
655                         if (!vcpu)
656                                 continue;
657                         /*
658                          * If the vcpu is locked, then it is running on some
659                          * other cpu and therefore it is not cached on the
660                          * cpu in question.
661                          *
662                          * If it's not locked, check the last cpu it executed
663                          * on.
664                          */
665                         if (mutex_trylock(&vcpu->mutex)) {
666                                 if (vcpu->cpu == cpu) {
667                                         kvm_x86_ops->vcpu_decache(vcpu);
668                                         vcpu->cpu = -1;
669                                 }
670                                 mutex_unlock(&vcpu->mutex);
671                         }
672                 }
673         spin_unlock(&kvm_lock);
674 }
675
676 int kvm_dev_ioctl_check_extension(long ext)
677 {
678         int r;
679
680         switch (ext) {
681         case KVM_CAP_IRQCHIP:
682         case KVM_CAP_HLT:
683         case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
684         case KVM_CAP_USER_MEMORY:
685         case KVM_CAP_SET_TSS_ADDR:
686         case KVM_CAP_EXT_CPUID:
687         case KVM_CAP_VAPIC:
688                 r = 1;
689                 break;
690         default:
691                 r = 0;
692                 break;
693         }
694         return r;
695
696 }
697
698 long kvm_arch_dev_ioctl(struct file *filp,
699                         unsigned int ioctl, unsigned long arg)
700 {
701         void __user *argp = (void __user *)arg;
702         long r;
703
704         switch (ioctl) {
705         case KVM_GET_MSR_INDEX_LIST: {
706                 struct kvm_msr_list __user *user_msr_list = argp;
707                 struct kvm_msr_list msr_list;
708                 unsigned n;
709
710                 r = -EFAULT;
711                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
712                         goto out;
713                 n = msr_list.nmsrs;
714                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
715                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
716                         goto out;
717                 r = -E2BIG;
718                 if (n < num_msrs_to_save)
719                         goto out;
720                 r = -EFAULT;
721                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
722                                  num_msrs_to_save * sizeof(u32)))
723                         goto out;
724                 if (copy_to_user(user_msr_list->indices
725                                  + num_msrs_to_save * sizeof(u32),
726                                  &emulated_msrs,
727                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
728                         goto out;
729                 r = 0;
730                 break;
731         }
732         default:
733                 r = -EINVAL;
734         }
735 out:
736         return r;
737 }
738
739 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
740 {
741         kvm_x86_ops->vcpu_load(vcpu, cpu);
742 }
743
744 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
745 {
746         kvm_x86_ops->vcpu_put(vcpu);
747         kvm_put_guest_fpu(vcpu);
748 }
749
750 static int is_efer_nx(void)
751 {
752         u64 efer;
753
754         rdmsrl(MSR_EFER, efer);
755         return efer & EFER_NX;
756 }
757
758 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
759 {
760         int i;
761         struct kvm_cpuid_entry2 *e, *entry;
762
763         entry = NULL;
764         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
765                 e = &vcpu->arch.cpuid_entries[i];
766                 if (e->function == 0x80000001) {
767                         entry = e;
768                         break;
769                 }
770         }
771         if (entry && (entry->edx & (1 << 20)) && !is_efer_nx()) {
772                 entry->edx &= ~(1 << 20);
773                 printk(KERN_INFO "kvm: guest NX capability removed\n");
774         }
775 }
776
777 /* when an old userspace process fills a new kernel module */
778 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
779                                     struct kvm_cpuid *cpuid,
780                                     struct kvm_cpuid_entry __user *entries)
781 {
782         int r, i;
783         struct kvm_cpuid_entry *cpuid_entries;
784
785         r = -E2BIG;
786         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
787                 goto out;
788         r = -ENOMEM;
789         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry) * cpuid->nent);
790         if (!cpuid_entries)
791                 goto out;
792         r = -EFAULT;
793         if (copy_from_user(cpuid_entries, entries,
794                            cpuid->nent * sizeof(struct kvm_cpuid_entry)))
795                 goto out_free;
796         for (i = 0; i < cpuid->nent; i++) {
797                 vcpu->arch.cpuid_entries[i].function = cpuid_entries[i].function;
798                 vcpu->arch.cpuid_entries[i].eax = cpuid_entries[i].eax;
799                 vcpu->arch.cpuid_entries[i].ebx = cpuid_entries[i].ebx;
800                 vcpu->arch.cpuid_entries[i].ecx = cpuid_entries[i].ecx;
801                 vcpu->arch.cpuid_entries[i].edx = cpuid_entries[i].edx;
802                 vcpu->arch.cpuid_entries[i].index = 0;
803                 vcpu->arch.cpuid_entries[i].flags = 0;
804                 vcpu->arch.cpuid_entries[i].padding[0] = 0;
805                 vcpu->arch.cpuid_entries[i].padding[1] = 0;
806                 vcpu->arch.cpuid_entries[i].padding[2] = 0;
807         }
808         vcpu->arch.cpuid_nent = cpuid->nent;
809         cpuid_fix_nx_cap(vcpu);
810         r = 0;
811
812 out_free:
813         vfree(cpuid_entries);
814 out:
815         return r;
816 }
817
818 static int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
819                                     struct kvm_cpuid2 *cpuid,
820                                     struct kvm_cpuid_entry2 __user *entries)
821 {
822         int r;
823
824         r = -E2BIG;
825         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
826                 goto out;
827         r = -EFAULT;
828         if (copy_from_user(&vcpu->arch.cpuid_entries, entries,
829                            cpuid->nent * sizeof(struct kvm_cpuid_entry2)))
830                 goto out;
831         vcpu->arch.cpuid_nent = cpuid->nent;
832         return 0;
833
834 out:
835         return r;
836 }
837
838 static int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
839                                     struct kvm_cpuid2 *cpuid,
840                                     struct kvm_cpuid_entry2 __user *entries)
841 {
842         int r;
843
844         r = -E2BIG;
845         if (cpuid->nent < vcpu->arch.cpuid_nent)
846                 goto out;
847         r = -EFAULT;
848         if (copy_to_user(entries, &vcpu->arch.cpuid_entries,
849                            vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
850                 goto out;
851         return 0;
852
853 out:
854         cpuid->nent = vcpu->arch.cpuid_nent;
855         return r;
856 }
857
858 static inline u32 bit(int bitno)
859 {
860         return 1 << (bitno & 31);
861 }
862
863 static void do_cpuid_1_ent(struct kvm_cpuid_entry2 *entry, u32 function,
864                           u32 index)
865 {
866         entry->function = function;
867         entry->index = index;
868         cpuid_count(entry->function, entry->index,
869                 &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
870         entry->flags = 0;
871 }
872
873 static void do_cpuid_ent(struct kvm_cpuid_entry2 *entry, u32 function,
874                          u32 index, int *nent, int maxnent)
875 {
876         const u32 kvm_supported_word0_x86_features = bit(X86_FEATURE_FPU) |
877                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
878                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
879                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
880                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
881                 bit(X86_FEATURE_SEP) | bit(X86_FEATURE_PGE) |
882                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
883                 bit(X86_FEATURE_CLFLSH) | bit(X86_FEATURE_MMX) |
884                 bit(X86_FEATURE_FXSR) | bit(X86_FEATURE_XMM) |
885                 bit(X86_FEATURE_XMM2) | bit(X86_FEATURE_SELFSNOOP);
886         const u32 kvm_supported_word1_x86_features = bit(X86_FEATURE_FPU) |
887                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
888                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
889                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
890                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
891                 bit(X86_FEATURE_PGE) |
892                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
893                 bit(X86_FEATURE_MMX) | bit(X86_FEATURE_FXSR) |
894                 bit(X86_FEATURE_SYSCALL) |
895                 (bit(X86_FEATURE_NX) && is_efer_nx()) |
896 #ifdef CONFIG_X86_64
897                 bit(X86_FEATURE_LM) |
898 #endif
899                 bit(X86_FEATURE_MMXEXT) |
900                 bit(X86_FEATURE_3DNOWEXT) |
901                 bit(X86_FEATURE_3DNOW);
902         const u32 kvm_supported_word3_x86_features =
903                 bit(X86_FEATURE_XMM3) | bit(X86_FEATURE_CX16);
904         const u32 kvm_supported_word6_x86_features =
905                 bit(X86_FEATURE_LAHF_LM) | bit(X86_FEATURE_CMP_LEGACY);
906
907         /* all func 2 cpuid_count() should be called on the same cpu */
908         get_cpu();
909         do_cpuid_1_ent(entry, function, index);
910         ++*nent;
911
912         switch (function) {
913         case 0:
914                 entry->eax = min(entry->eax, (u32)0xb);
915                 break;
916         case 1:
917                 entry->edx &= kvm_supported_word0_x86_features;
918                 entry->ecx &= kvm_supported_word3_x86_features;
919                 break;
920         /* function 2 entries are STATEFUL. That is, repeated cpuid commands
921          * may return different values. This forces us to get_cpu() before
922          * issuing the first command, and also to emulate this annoying behavior
923          * in kvm_emulate_cpuid() using KVM_CPUID_FLAG_STATE_READ_NEXT */
924         case 2: {
925                 int t, times = entry->eax & 0xff;
926
927                 entry->flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
928                 for (t = 1; t < times && *nent < maxnent; ++t) {
929                         do_cpuid_1_ent(&entry[t], function, 0);
930                         entry[t].flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
931                         ++*nent;
932                 }
933                 break;
934         }
935         /* function 4 and 0xb have additional index. */
936         case 4: {
937                 int index, cache_type;
938
939                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
940                 /* read more entries until cache_type is zero */
941                 for (index = 1; *nent < maxnent; ++index) {
942                         cache_type = entry[index - 1].eax & 0x1f;
943                         if (!cache_type)
944                                 break;
945                         do_cpuid_1_ent(&entry[index], function, index);
946                         entry[index].flags |=
947                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
948                         ++*nent;
949                 }
950                 break;
951         }
952         case 0xb: {
953                 int index, level_type;
954
955                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
956                 /* read more entries until level_type is zero */
957                 for (index = 1; *nent < maxnent; ++index) {
958                         level_type = entry[index - 1].ecx & 0xff;
959                         if (!level_type)
960                                 break;
961                         do_cpuid_1_ent(&entry[index], function, index);
962                         entry[index].flags |=
963                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
964                         ++*nent;
965                 }
966                 break;
967         }
968         case 0x80000000:
969                 entry->eax = min(entry->eax, 0x8000001a);
970                 break;
971         case 0x80000001:
972                 entry->edx &= kvm_supported_word1_x86_features;
973                 entry->ecx &= kvm_supported_word6_x86_features;
974                 break;
975         }
976         put_cpu();
977 }
978
979 static int kvm_vm_ioctl_get_supported_cpuid(struct kvm *kvm,
980                                     struct kvm_cpuid2 *cpuid,
981                                     struct kvm_cpuid_entry2 __user *entries)
982 {
983         struct kvm_cpuid_entry2 *cpuid_entries;
984         int limit, nent = 0, r = -E2BIG;
985         u32 func;
986
987         if (cpuid->nent < 1)
988                 goto out;
989         r = -ENOMEM;
990         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry2) * cpuid->nent);
991         if (!cpuid_entries)
992                 goto out;
993
994         do_cpuid_ent(&cpuid_entries[0], 0, 0, &nent, cpuid->nent);
995         limit = cpuid_entries[0].eax;
996         for (func = 1; func <= limit && nent < cpuid->nent; ++func)
997                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
998                                 &nent, cpuid->nent);
999         r = -E2BIG;
1000         if (nent >= cpuid->nent)
1001                 goto out_free;
1002
1003         do_cpuid_ent(&cpuid_entries[nent], 0x80000000, 0, &nent, cpuid->nent);
1004         limit = cpuid_entries[nent - 1].eax;
1005         for (func = 0x80000001; func <= limit && nent < cpuid->nent; ++func)
1006                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1007                                &nent, cpuid->nent);
1008         r = -EFAULT;
1009         if (copy_to_user(entries, cpuid_entries,
1010                         nent * sizeof(struct kvm_cpuid_entry2)))
1011                 goto out_free;
1012         cpuid->nent = nent;
1013         r = 0;
1014
1015 out_free:
1016         vfree(cpuid_entries);
1017 out:
1018         return r;
1019 }
1020
1021 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
1022                                     struct kvm_lapic_state *s)
1023 {
1024         vcpu_load(vcpu);
1025         memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
1026         vcpu_put(vcpu);
1027
1028         return 0;
1029 }
1030
1031 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
1032                                     struct kvm_lapic_state *s)
1033 {
1034         vcpu_load(vcpu);
1035         memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
1036         kvm_apic_post_state_restore(vcpu);
1037         vcpu_put(vcpu);
1038
1039         return 0;
1040 }
1041
1042 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
1043                                     struct kvm_interrupt *irq)
1044 {
1045         if (irq->irq < 0 || irq->irq >= 256)
1046                 return -EINVAL;
1047         if (irqchip_in_kernel(vcpu->kvm))
1048                 return -ENXIO;
1049         vcpu_load(vcpu);
1050
1051         set_bit(irq->irq, vcpu->arch.irq_pending);
1052         set_bit(irq->irq / BITS_PER_LONG, &vcpu->arch.irq_summary);
1053
1054         vcpu_put(vcpu);
1055
1056         return 0;
1057 }
1058
1059 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
1060                                            struct kvm_tpr_access_ctl *tac)
1061 {
1062         if (tac->flags)
1063                 return -EINVAL;
1064         vcpu->arch.tpr_access_reporting = !!tac->enabled;
1065         return 0;
1066 }
1067
1068 long kvm_arch_vcpu_ioctl(struct file *filp,
1069                          unsigned int ioctl, unsigned long arg)
1070 {
1071         struct kvm_vcpu *vcpu = filp->private_data;
1072         void __user *argp = (void __user *)arg;
1073         int r;
1074
1075         switch (ioctl) {
1076         case KVM_GET_LAPIC: {
1077                 struct kvm_lapic_state lapic;
1078
1079                 memset(&lapic, 0, sizeof lapic);
1080                 r = kvm_vcpu_ioctl_get_lapic(vcpu, &lapic);
1081                 if (r)
1082                         goto out;
1083                 r = -EFAULT;
1084                 if (copy_to_user(argp, &lapic, sizeof lapic))
1085                         goto out;
1086                 r = 0;
1087                 break;
1088         }
1089         case KVM_SET_LAPIC: {
1090                 struct kvm_lapic_state lapic;
1091
1092                 r = -EFAULT;
1093                 if (copy_from_user(&lapic, argp, sizeof lapic))
1094                         goto out;
1095                 r = kvm_vcpu_ioctl_set_lapic(vcpu, &lapic);;
1096                 if (r)
1097                         goto out;
1098                 r = 0;
1099                 break;
1100         }
1101         case KVM_INTERRUPT: {
1102                 struct kvm_interrupt irq;
1103
1104                 r = -EFAULT;
1105                 if (copy_from_user(&irq, argp, sizeof irq))
1106                         goto out;
1107                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
1108                 if (r)
1109                         goto out;
1110                 r = 0;
1111                 break;
1112         }
1113         case KVM_SET_CPUID: {
1114                 struct kvm_cpuid __user *cpuid_arg = argp;
1115                 struct kvm_cpuid cpuid;
1116
1117                 r = -EFAULT;
1118                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1119                         goto out;
1120                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
1121                 if (r)
1122                         goto out;
1123                 break;
1124         }
1125         case KVM_SET_CPUID2: {
1126                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1127                 struct kvm_cpuid2 cpuid;
1128
1129                 r = -EFAULT;
1130                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1131                         goto out;
1132                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
1133                                 cpuid_arg->entries);
1134                 if (r)
1135                         goto out;
1136                 break;
1137         }
1138         case KVM_GET_CPUID2: {
1139                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1140                 struct kvm_cpuid2 cpuid;
1141
1142                 r = -EFAULT;
1143                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1144                         goto out;
1145                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
1146                                 cpuid_arg->entries);
1147                 if (r)
1148                         goto out;
1149                 r = -EFAULT;
1150                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1151                         goto out;
1152                 r = 0;
1153                 break;
1154         }
1155         case KVM_GET_MSRS:
1156                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
1157                 break;
1158         case KVM_SET_MSRS:
1159                 r = msr_io(vcpu, argp, do_set_msr, 0);
1160                 break;
1161         case KVM_TPR_ACCESS_REPORTING: {
1162                 struct kvm_tpr_access_ctl tac;
1163
1164                 r = -EFAULT;
1165                 if (copy_from_user(&tac, argp, sizeof tac))
1166                         goto out;
1167                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
1168                 if (r)
1169                         goto out;
1170                 r = -EFAULT;
1171                 if (copy_to_user(argp, &tac, sizeof tac))
1172                         goto out;
1173                 r = 0;
1174                 break;
1175         };
1176         default:
1177                 r = -EINVAL;
1178         }
1179 out:
1180         return r;
1181 }
1182
1183 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
1184 {
1185         int ret;
1186
1187         if (addr > (unsigned int)(-3 * PAGE_SIZE))
1188                 return -1;
1189         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
1190         return ret;
1191 }
1192
1193 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
1194                                           u32 kvm_nr_mmu_pages)
1195 {
1196         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
1197                 return -EINVAL;
1198
1199         mutex_lock(&kvm->lock);
1200
1201         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
1202         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
1203
1204         mutex_unlock(&kvm->lock);
1205         return 0;
1206 }
1207
1208 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
1209 {
1210         return kvm->arch.n_alloc_mmu_pages;
1211 }
1212
1213 gfn_t unalias_gfn(struct kvm *kvm, gfn_t gfn)
1214 {
1215         int i;
1216         struct kvm_mem_alias *alias;
1217
1218         for (i = 0; i < kvm->arch.naliases; ++i) {
1219                 alias = &kvm->arch.aliases[i];
1220                 if (gfn >= alias->base_gfn
1221                     && gfn < alias->base_gfn + alias->npages)
1222                         return alias->target_gfn + gfn - alias->base_gfn;
1223         }
1224         return gfn;
1225 }
1226
1227 /*
1228  * Set a new alias region.  Aliases map a portion of physical memory into
1229  * another portion.  This is useful for memory windows, for example the PC
1230  * VGA region.
1231  */
1232 static int kvm_vm_ioctl_set_memory_alias(struct kvm *kvm,
1233                                          struct kvm_memory_alias *alias)
1234 {
1235         int r, n;
1236         struct kvm_mem_alias *p;
1237
1238         r = -EINVAL;
1239         /* General sanity checks */
1240         if (alias->memory_size & (PAGE_SIZE - 1))
1241                 goto out;
1242         if (alias->guest_phys_addr & (PAGE_SIZE - 1))
1243                 goto out;
1244         if (alias->slot >= KVM_ALIAS_SLOTS)
1245                 goto out;
1246         if (alias->guest_phys_addr + alias->memory_size
1247             < alias->guest_phys_addr)
1248                 goto out;
1249         if (alias->target_phys_addr + alias->memory_size
1250             < alias->target_phys_addr)
1251                 goto out;
1252
1253         mutex_lock(&kvm->lock);
1254
1255         p = &kvm->arch.aliases[alias->slot];
1256         p->base_gfn = alias->guest_phys_addr >> PAGE_SHIFT;
1257         p->npages = alias->memory_size >> PAGE_SHIFT;
1258         p->target_gfn = alias->target_phys_addr >> PAGE_SHIFT;
1259
1260         for (n = KVM_ALIAS_SLOTS; n > 0; --n)
1261                 if (kvm->arch.aliases[n - 1].npages)
1262                         break;
1263         kvm->arch.naliases = n;
1264
1265         kvm_mmu_zap_all(kvm);
1266
1267         mutex_unlock(&kvm->lock);
1268
1269         return 0;
1270
1271 out:
1272         return r;
1273 }
1274
1275 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1276 {
1277         int r;
1278
1279         r = 0;
1280         switch (chip->chip_id) {
1281         case KVM_IRQCHIP_PIC_MASTER:
1282                 memcpy(&chip->chip.pic,
1283                         &pic_irqchip(kvm)->pics[0],
1284                         sizeof(struct kvm_pic_state));
1285                 break;
1286         case KVM_IRQCHIP_PIC_SLAVE:
1287                 memcpy(&chip->chip.pic,
1288                         &pic_irqchip(kvm)->pics[1],
1289                         sizeof(struct kvm_pic_state));
1290                 break;
1291         case KVM_IRQCHIP_IOAPIC:
1292                 memcpy(&chip->chip.ioapic,
1293                         ioapic_irqchip(kvm),
1294                         sizeof(struct kvm_ioapic_state));
1295                 break;
1296         default:
1297                 r = -EINVAL;
1298                 break;
1299         }
1300         return r;
1301 }
1302
1303 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1304 {
1305         int r;
1306
1307         r = 0;
1308         switch (chip->chip_id) {
1309         case KVM_IRQCHIP_PIC_MASTER:
1310                 memcpy(&pic_irqchip(kvm)->pics[0],
1311                         &chip->chip.pic,
1312                         sizeof(struct kvm_pic_state));
1313                 break;
1314         case KVM_IRQCHIP_PIC_SLAVE:
1315                 memcpy(&pic_irqchip(kvm)->pics[1],
1316                         &chip->chip.pic,
1317                         sizeof(struct kvm_pic_state));
1318                 break;
1319         case KVM_IRQCHIP_IOAPIC:
1320                 memcpy(ioapic_irqchip(kvm),
1321                         &chip->chip.ioapic,
1322                         sizeof(struct kvm_ioapic_state));
1323                 break;
1324         default:
1325                 r = -EINVAL;
1326                 break;
1327         }
1328         kvm_pic_update_irq(pic_irqchip(kvm));
1329         return r;
1330 }
1331
1332 /*
1333  * Get (and clear) the dirty memory log for a memory slot.
1334  */
1335 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1336                                       struct kvm_dirty_log *log)
1337 {
1338         int r;
1339         int n;
1340         struct kvm_memory_slot *memslot;
1341         int is_dirty = 0;
1342
1343         mutex_lock(&kvm->lock);
1344
1345         r = kvm_get_dirty_log(kvm, log, &is_dirty);
1346         if (r)
1347                 goto out;
1348
1349         /* If nothing is dirty, don't bother messing with page tables. */
1350         if (is_dirty) {
1351                 kvm_mmu_slot_remove_write_access(kvm, log->slot);
1352                 kvm_flush_remote_tlbs(kvm);
1353                 memslot = &kvm->memslots[log->slot];
1354                 n = ALIGN(memslot->npages, BITS_PER_LONG) / 8;
1355                 memset(memslot->dirty_bitmap, 0, n);
1356         }
1357         r = 0;
1358 out:
1359         mutex_unlock(&kvm->lock);
1360         return r;
1361 }
1362
1363 long kvm_arch_vm_ioctl(struct file *filp,
1364                        unsigned int ioctl, unsigned long arg)
1365 {
1366         struct kvm *kvm = filp->private_data;
1367         void __user *argp = (void __user *)arg;
1368         int r = -EINVAL;
1369
1370         switch (ioctl) {
1371         case KVM_SET_TSS_ADDR:
1372                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
1373                 if (r < 0)
1374                         goto out;
1375                 break;
1376         case KVM_SET_MEMORY_REGION: {
1377                 struct kvm_memory_region kvm_mem;
1378                 struct kvm_userspace_memory_region kvm_userspace_mem;
1379
1380                 r = -EFAULT;
1381                 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
1382                         goto out;
1383                 kvm_userspace_mem.slot = kvm_mem.slot;
1384                 kvm_userspace_mem.flags = kvm_mem.flags;
1385                 kvm_userspace_mem.guest_phys_addr = kvm_mem.guest_phys_addr;
1386                 kvm_userspace_mem.memory_size = kvm_mem.memory_size;
1387                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 0);
1388                 if (r)
1389                         goto out;
1390                 break;
1391         }
1392         case KVM_SET_NR_MMU_PAGES:
1393                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
1394                 if (r)
1395                         goto out;
1396                 break;
1397         case KVM_GET_NR_MMU_PAGES:
1398                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
1399                 break;
1400         case KVM_SET_MEMORY_ALIAS: {
1401                 struct kvm_memory_alias alias;
1402
1403                 r = -EFAULT;
1404                 if (copy_from_user(&alias, argp, sizeof alias))
1405                         goto out;
1406                 r = kvm_vm_ioctl_set_memory_alias(kvm, &alias);
1407                 if (r)
1408                         goto out;
1409                 break;
1410         }
1411         case KVM_CREATE_IRQCHIP:
1412                 r = -ENOMEM;
1413                 kvm->arch.vpic = kvm_create_pic(kvm);
1414                 if (kvm->arch.vpic) {
1415                         r = kvm_ioapic_init(kvm);
1416                         if (r) {
1417                                 kfree(kvm->arch.vpic);
1418                                 kvm->arch.vpic = NULL;
1419                                 goto out;
1420                         }
1421                 } else
1422                         goto out;
1423                 break;
1424         case KVM_IRQ_LINE: {
1425                 struct kvm_irq_level irq_event;
1426
1427                 r = -EFAULT;
1428                 if (copy_from_user(&irq_event, argp, sizeof irq_event))
1429                         goto out;
1430                 if (irqchip_in_kernel(kvm)) {
1431                         mutex_lock(&kvm->lock);
1432                         if (irq_event.irq < 16)
1433                                 kvm_pic_set_irq(pic_irqchip(kvm),
1434                                         irq_event.irq,
1435                                         irq_event.level);
1436                         kvm_ioapic_set_irq(kvm->arch.vioapic,
1437                                         irq_event.irq,
1438                                         irq_event.level);
1439                         mutex_unlock(&kvm->lock);
1440                         r = 0;
1441                 }
1442                 break;
1443         }
1444         case KVM_GET_IRQCHIP: {
1445                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1446                 struct kvm_irqchip chip;
1447
1448                 r = -EFAULT;
1449                 if (copy_from_user(&chip, argp, sizeof chip))
1450                         goto out;
1451                 r = -ENXIO;
1452                 if (!irqchip_in_kernel(kvm))
1453                         goto out;
1454                 r = kvm_vm_ioctl_get_irqchip(kvm, &chip);
1455                 if (r)
1456                         goto out;
1457                 r = -EFAULT;
1458                 if (copy_to_user(argp, &chip, sizeof chip))
1459                         goto out;
1460                 r = 0;
1461                 break;
1462         }
1463         case KVM_SET_IRQCHIP: {
1464                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1465                 struct kvm_irqchip chip;
1466
1467                 r = -EFAULT;
1468                 if (copy_from_user(&chip, argp, sizeof chip))
1469                         goto out;
1470                 r = -ENXIO;
1471                 if (!irqchip_in_kernel(kvm))
1472                         goto out;
1473                 r = kvm_vm_ioctl_set_irqchip(kvm, &chip);
1474                 if (r)
1475                         goto out;
1476                 r = 0;
1477                 break;
1478         }
1479         case KVM_GET_SUPPORTED_CPUID: {
1480                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1481                 struct kvm_cpuid2 cpuid;
1482
1483                 r = -EFAULT;
1484                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1485                         goto out;
1486                 r = kvm_vm_ioctl_get_supported_cpuid(kvm, &cpuid,
1487                         cpuid_arg->entries);
1488                 if (r)
1489                         goto out;
1490
1491                 r = -EFAULT;
1492                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1493                         goto out;
1494                 r = 0;
1495                 break;
1496         }
1497         default:
1498                 ;
1499         }
1500 out:
1501         return r;
1502 }
1503
1504 static void kvm_init_msr_list(void)
1505 {
1506         u32 dummy[2];
1507         unsigned i, j;
1508
1509         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
1510                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
1511                         continue;
1512                 if (j < i)
1513                         msrs_to_save[j] = msrs_to_save[i];
1514                 j++;
1515         }
1516         num_msrs_to_save = j;
1517 }
1518
1519 /*
1520  * Only apic need an MMIO device hook, so shortcut now..
1521  */
1522 static struct kvm_io_device *vcpu_find_pervcpu_dev(struct kvm_vcpu *vcpu,
1523                                                 gpa_t addr)
1524 {
1525         struct kvm_io_device *dev;
1526
1527         if (vcpu->arch.apic) {
1528                 dev = &vcpu->arch.apic->dev;
1529                 if (dev->in_range(dev, addr))
1530                         return dev;
1531         }
1532         return NULL;
1533 }
1534
1535
1536 static struct kvm_io_device *vcpu_find_mmio_dev(struct kvm_vcpu *vcpu,
1537                                                 gpa_t addr)
1538 {
1539         struct kvm_io_device *dev;
1540
1541         dev = vcpu_find_pervcpu_dev(vcpu, addr);
1542         if (dev == NULL)
1543                 dev = kvm_io_bus_find_dev(&vcpu->kvm->mmio_bus, addr);
1544         return dev;
1545 }
1546
1547 int emulator_read_std(unsigned long addr,
1548                              void *val,
1549                              unsigned int bytes,
1550                              struct kvm_vcpu *vcpu)
1551 {
1552         void *data = val;
1553
1554         while (bytes) {
1555                 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1556                 unsigned offset = addr & (PAGE_SIZE-1);
1557                 unsigned tocopy = min(bytes, (unsigned)PAGE_SIZE - offset);
1558                 int ret;
1559
1560                 if (gpa == UNMAPPED_GVA)
1561                         return X86EMUL_PROPAGATE_FAULT;
1562                 ret = kvm_read_guest(vcpu->kvm, gpa, data, tocopy);
1563                 if (ret < 0)
1564                         return X86EMUL_UNHANDLEABLE;
1565
1566                 bytes -= tocopy;
1567                 data += tocopy;
1568                 addr += tocopy;
1569         }
1570
1571         return X86EMUL_CONTINUE;
1572 }
1573 EXPORT_SYMBOL_GPL(emulator_read_std);
1574
1575 static int emulator_read_emulated(unsigned long addr,
1576                                   void *val,
1577                                   unsigned int bytes,
1578                                   struct kvm_vcpu *vcpu)
1579 {
1580         struct kvm_io_device *mmio_dev;
1581         gpa_t                 gpa;
1582
1583         if (vcpu->mmio_read_completed) {
1584                 memcpy(val, vcpu->mmio_data, bytes);
1585                 vcpu->mmio_read_completed = 0;
1586                 return X86EMUL_CONTINUE;
1587         }
1588
1589         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1590
1591         /* For APIC access vmexit */
1592         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1593                 goto mmio;
1594
1595         if (emulator_read_std(addr, val, bytes, vcpu)
1596                         == X86EMUL_CONTINUE)
1597                 return X86EMUL_CONTINUE;
1598         if (gpa == UNMAPPED_GVA)
1599                 return X86EMUL_PROPAGATE_FAULT;
1600
1601 mmio:
1602         /*
1603          * Is this MMIO handled locally?
1604          */
1605         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa);
1606         if (mmio_dev) {
1607                 kvm_iodevice_read(mmio_dev, gpa, bytes, val);
1608                 return X86EMUL_CONTINUE;
1609         }
1610
1611         vcpu->mmio_needed = 1;
1612         vcpu->mmio_phys_addr = gpa;
1613         vcpu->mmio_size = bytes;
1614         vcpu->mmio_is_write = 0;
1615
1616         return X86EMUL_UNHANDLEABLE;
1617 }
1618
1619 static int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
1620                                const void *val, int bytes)
1621 {
1622         int ret;
1623
1624         ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
1625         if (ret < 0)
1626                 return 0;
1627         kvm_mmu_pte_write(vcpu, gpa, val, bytes);
1628         return 1;
1629 }
1630
1631 static int emulator_write_emulated_onepage(unsigned long addr,
1632                                            const void *val,
1633                                            unsigned int bytes,
1634                                            struct kvm_vcpu *vcpu)
1635 {
1636         struct kvm_io_device *mmio_dev;
1637         gpa_t                 gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1638
1639         if (gpa == UNMAPPED_GVA) {
1640                 kvm_inject_page_fault(vcpu, addr, 2);
1641                 return X86EMUL_PROPAGATE_FAULT;
1642         }
1643
1644         /* For APIC access vmexit */
1645         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1646                 goto mmio;
1647
1648         if (emulator_write_phys(vcpu, gpa, val, bytes))
1649                 return X86EMUL_CONTINUE;
1650
1651 mmio:
1652         /*
1653          * Is this MMIO handled locally?
1654          */
1655         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa);
1656         if (mmio_dev) {
1657                 kvm_iodevice_write(mmio_dev, gpa, bytes, val);
1658                 return X86EMUL_CONTINUE;
1659         }
1660
1661         vcpu->mmio_needed = 1;
1662         vcpu->mmio_phys_addr = gpa;
1663         vcpu->mmio_size = bytes;
1664         vcpu->mmio_is_write = 1;
1665         memcpy(vcpu->mmio_data, val, bytes);
1666
1667         return X86EMUL_CONTINUE;
1668 }
1669
1670 int emulator_write_emulated(unsigned long addr,
1671                                    const void *val,
1672                                    unsigned int bytes,
1673                                    struct kvm_vcpu *vcpu)
1674 {
1675         /* Crossing a page boundary? */
1676         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
1677                 int rc, now;
1678
1679                 now = -addr & ~PAGE_MASK;
1680                 rc = emulator_write_emulated_onepage(addr, val, now, vcpu);
1681                 if (rc != X86EMUL_CONTINUE)
1682                         return rc;
1683                 addr += now;
1684                 val += now;
1685                 bytes -= now;
1686         }
1687         return emulator_write_emulated_onepage(addr, val, bytes, vcpu);
1688 }
1689 EXPORT_SYMBOL_GPL(emulator_write_emulated);
1690
1691 static int emulator_cmpxchg_emulated(unsigned long addr,
1692                                      const void *old,
1693                                      const void *new,
1694                                      unsigned int bytes,
1695                                      struct kvm_vcpu *vcpu)
1696 {
1697         static int reported;
1698
1699         if (!reported) {
1700                 reported = 1;
1701                 printk(KERN_WARNING "kvm: emulating exchange as write\n");
1702         }
1703 #ifndef CONFIG_X86_64
1704         /* guests cmpxchg8b have to be emulated atomically */
1705         if (bytes == 8) {
1706                 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1707                 struct page *page;
1708                 char *addr;
1709                 u64 val;
1710
1711                 if (gpa == UNMAPPED_GVA ||
1712                    (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1713                         goto emul_write;
1714
1715                 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
1716                         goto emul_write;
1717
1718                 val = *(u64 *)new;
1719                 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
1720                 addr = kmap_atomic(page, KM_USER0);
1721                 set_64bit((u64 *)(addr + offset_in_page(gpa)), val);
1722                 kunmap_atomic(addr, KM_USER0);
1723                 kvm_release_page_dirty(page);
1724         }
1725 emul_write:
1726 #endif
1727
1728         return emulator_write_emulated(addr, new, bytes, vcpu);
1729 }
1730
1731 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
1732 {
1733         return kvm_x86_ops->get_segment_base(vcpu, seg);
1734 }
1735
1736 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
1737 {
1738         return X86EMUL_CONTINUE;
1739 }
1740
1741 int emulate_clts(struct kvm_vcpu *vcpu)
1742 {
1743         kvm_x86_ops->set_cr0(vcpu, vcpu->arch.cr0 & ~X86_CR0_TS);
1744         return X86EMUL_CONTINUE;
1745 }
1746
1747 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
1748 {
1749         struct kvm_vcpu *vcpu = ctxt->vcpu;
1750
1751         switch (dr) {
1752         case 0 ... 3:
1753                 *dest = kvm_x86_ops->get_dr(vcpu, dr);
1754                 return X86EMUL_CONTINUE;
1755         default:
1756                 pr_unimpl(vcpu, "%s: unexpected dr %u\n", __FUNCTION__, dr);
1757                 return X86EMUL_UNHANDLEABLE;
1758         }
1759 }
1760
1761 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
1762 {
1763         unsigned long mask = (ctxt->mode == X86EMUL_MODE_PROT64) ? ~0ULL : ~0U;
1764         int exception;
1765
1766         kvm_x86_ops->set_dr(ctxt->vcpu, dr, value & mask, &exception);
1767         if (exception) {
1768                 /* FIXME: better handling */
1769                 return X86EMUL_UNHANDLEABLE;
1770         }
1771         return X86EMUL_CONTINUE;
1772 }
1773
1774 void kvm_report_emulation_failure(struct kvm_vcpu *vcpu, const char *context)
1775 {
1776         static int reported;
1777         u8 opcodes[4];
1778         unsigned long rip = vcpu->arch.rip;
1779         unsigned long rip_linear;
1780
1781         rip_linear = rip + get_segment_base(vcpu, VCPU_SREG_CS);
1782
1783         if (reported)
1784                 return;
1785
1786         emulator_read_std(rip_linear, (void *)opcodes, 4, vcpu);
1787
1788         printk(KERN_ERR "emulation failed (%s) rip %lx %02x %02x %02x %02x\n",
1789                context, rip, opcodes[0], opcodes[1], opcodes[2], opcodes[3]);
1790         reported = 1;
1791 }
1792 EXPORT_SYMBOL_GPL(kvm_report_emulation_failure);
1793
1794 struct x86_emulate_ops emulate_ops = {
1795         .read_std            = emulator_read_std,
1796         .read_emulated       = emulator_read_emulated,
1797         .write_emulated      = emulator_write_emulated,
1798         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
1799 };
1800
1801 int emulate_instruction(struct kvm_vcpu *vcpu,
1802                         struct kvm_run *run,
1803                         unsigned long cr2,
1804                         u16 error_code,
1805                         int no_decode)
1806 {
1807         int r;
1808
1809         vcpu->arch.mmio_fault_cr2 = cr2;
1810         kvm_x86_ops->cache_regs(vcpu);
1811
1812         vcpu->mmio_is_write = 0;
1813         vcpu->arch.pio.string = 0;
1814
1815         if (!no_decode) {
1816                 int cs_db, cs_l;
1817                 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
1818
1819                 vcpu->arch.emulate_ctxt.vcpu = vcpu;
1820                 vcpu->arch.emulate_ctxt.eflags = kvm_x86_ops->get_rflags(vcpu);
1821                 vcpu->arch.emulate_ctxt.mode =
1822                         (vcpu->arch.emulate_ctxt.eflags & X86_EFLAGS_VM)
1823                         ? X86EMUL_MODE_REAL : cs_l
1824                         ? X86EMUL_MODE_PROT64 : cs_db
1825                         ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
1826
1827                 if (vcpu->arch.emulate_ctxt.mode == X86EMUL_MODE_PROT64) {
1828                         vcpu->arch.emulate_ctxt.cs_base = 0;
1829                         vcpu->arch.emulate_ctxt.ds_base = 0;
1830                         vcpu->arch.emulate_ctxt.es_base = 0;
1831                         vcpu->arch.emulate_ctxt.ss_base = 0;
1832                 } else {
1833                         vcpu->arch.emulate_ctxt.cs_base =
1834                                         get_segment_base(vcpu, VCPU_SREG_CS);
1835                         vcpu->arch.emulate_ctxt.ds_base =
1836                                         get_segment_base(vcpu, VCPU_SREG_DS);
1837                         vcpu->arch.emulate_ctxt.es_base =
1838                                         get_segment_base(vcpu, VCPU_SREG_ES);
1839                         vcpu->arch.emulate_ctxt.ss_base =
1840                                         get_segment_base(vcpu, VCPU_SREG_SS);
1841                 }
1842
1843                 vcpu->arch.emulate_ctxt.gs_base =
1844                                         get_segment_base(vcpu, VCPU_SREG_GS);
1845                 vcpu->arch.emulate_ctxt.fs_base =
1846                                         get_segment_base(vcpu, VCPU_SREG_FS);
1847
1848                 r = x86_decode_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
1849                 ++vcpu->stat.insn_emulation;
1850                 if (r)  {
1851                         ++vcpu->stat.insn_emulation_fail;
1852                         if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
1853                                 return EMULATE_DONE;
1854                         return EMULATE_FAIL;
1855                 }
1856         }
1857
1858         r = x86_emulate_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
1859
1860         if (vcpu->arch.pio.string)
1861                 return EMULATE_DO_MMIO;
1862
1863         if ((r || vcpu->mmio_is_write) && run) {
1864                 run->exit_reason = KVM_EXIT_MMIO;
1865                 run->mmio.phys_addr = vcpu->mmio_phys_addr;
1866                 memcpy(run->mmio.data, vcpu->mmio_data, 8);
1867                 run->mmio.len = vcpu->mmio_size;
1868                 run->mmio.is_write = vcpu->mmio_is_write;
1869         }
1870
1871         if (r) {
1872                 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
1873                         return EMULATE_DONE;
1874                 if (!vcpu->mmio_needed) {
1875                         kvm_report_emulation_failure(vcpu, "mmio");
1876                         return EMULATE_FAIL;
1877                 }
1878                 return EMULATE_DO_MMIO;
1879         }
1880
1881         kvm_x86_ops->decache_regs(vcpu);
1882         kvm_x86_ops->set_rflags(vcpu, vcpu->arch.emulate_ctxt.eflags);
1883
1884         if (vcpu->mmio_is_write) {
1885                 vcpu->mmio_needed = 0;
1886                 return EMULATE_DO_MMIO;
1887         }
1888
1889         return EMULATE_DONE;
1890 }
1891 EXPORT_SYMBOL_GPL(emulate_instruction);
1892
1893 static void free_pio_guest_pages(struct kvm_vcpu *vcpu)
1894 {
1895         int i;
1896
1897         for (i = 0; i < ARRAY_SIZE(vcpu->arch.pio.guest_pages); ++i)
1898                 if (vcpu->arch.pio.guest_pages[i]) {
1899                         kvm_release_page_dirty(vcpu->arch.pio.guest_pages[i]);
1900                         vcpu->arch.pio.guest_pages[i] = NULL;
1901                 }
1902 }
1903
1904 static int pio_copy_data(struct kvm_vcpu *vcpu)
1905 {
1906         void *p = vcpu->arch.pio_data;
1907         void *q;
1908         unsigned bytes;
1909         int nr_pages = vcpu->arch.pio.guest_pages[1] ? 2 : 1;
1910
1911         q = vmap(vcpu->arch.pio.guest_pages, nr_pages, VM_READ|VM_WRITE,
1912                  PAGE_KERNEL);
1913         if (!q) {
1914                 free_pio_guest_pages(vcpu);
1915                 return -ENOMEM;
1916         }
1917         q += vcpu->arch.pio.guest_page_offset;
1918         bytes = vcpu->arch.pio.size * vcpu->arch.pio.cur_count;
1919         if (vcpu->arch.pio.in)
1920                 memcpy(q, p, bytes);
1921         else
1922                 memcpy(p, q, bytes);
1923         q -= vcpu->arch.pio.guest_page_offset;
1924         vunmap(q);
1925         free_pio_guest_pages(vcpu);
1926         return 0;
1927 }
1928
1929 int complete_pio(struct kvm_vcpu *vcpu)
1930 {
1931         struct kvm_pio_request *io = &vcpu->arch.pio;
1932         long delta;
1933         int r;
1934
1935         kvm_x86_ops->cache_regs(vcpu);
1936
1937         if (!io->string) {
1938                 if (io->in)
1939                         memcpy(&vcpu->arch.regs[VCPU_REGS_RAX], vcpu->arch.pio_data,
1940                                io->size);
1941         } else {
1942                 if (io->in) {
1943                         r = pio_copy_data(vcpu);
1944                         if (r) {
1945                                 kvm_x86_ops->cache_regs(vcpu);
1946                                 return r;
1947                         }
1948                 }
1949
1950                 delta = 1;
1951                 if (io->rep) {
1952                         delta *= io->cur_count;
1953                         /*
1954                          * The size of the register should really depend on
1955                          * current address size.
1956                          */
1957                         vcpu->arch.regs[VCPU_REGS_RCX] -= delta;
1958                 }
1959                 if (io->down)
1960                         delta = -delta;
1961                 delta *= io->size;
1962                 if (io->in)
1963                         vcpu->arch.regs[VCPU_REGS_RDI] += delta;
1964                 else
1965                         vcpu->arch.regs[VCPU_REGS_RSI] += delta;
1966         }
1967
1968         kvm_x86_ops->decache_regs(vcpu);
1969
1970         io->count -= io->cur_count;
1971         io->cur_count = 0;
1972
1973         return 0;
1974 }
1975
1976 static void kernel_pio(struct kvm_io_device *pio_dev,
1977                        struct kvm_vcpu *vcpu,
1978                        void *pd)
1979 {
1980         /* TODO: String I/O for in kernel device */
1981
1982         mutex_lock(&vcpu->kvm->lock);
1983         if (vcpu->arch.pio.in)
1984                 kvm_iodevice_read(pio_dev, vcpu->arch.pio.port,
1985                                   vcpu->arch.pio.size,
1986                                   pd);
1987         else
1988                 kvm_iodevice_write(pio_dev, vcpu->arch.pio.port,
1989                                    vcpu->arch.pio.size,
1990                                    pd);
1991         mutex_unlock(&vcpu->kvm->lock);
1992 }
1993
1994 static void pio_string_write(struct kvm_io_device *pio_dev,
1995                              struct kvm_vcpu *vcpu)
1996 {
1997         struct kvm_pio_request *io = &vcpu->arch.pio;
1998         void *pd = vcpu->arch.pio_data;
1999         int i;
2000
2001         mutex_lock(&vcpu->kvm->lock);
2002         for (i = 0; i < io->cur_count; i++) {
2003                 kvm_iodevice_write(pio_dev, io->port,
2004                                    io->size,
2005                                    pd);
2006                 pd += io->size;
2007         }
2008         mutex_unlock(&vcpu->kvm->lock);
2009 }
2010
2011 static struct kvm_io_device *vcpu_find_pio_dev(struct kvm_vcpu *vcpu,
2012                                                gpa_t addr)
2013 {
2014         return kvm_io_bus_find_dev(&vcpu->kvm->pio_bus, addr);
2015 }
2016
2017 int kvm_emulate_pio(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
2018                   int size, unsigned port)
2019 {
2020         struct kvm_io_device *pio_dev;
2021
2022         vcpu->run->exit_reason = KVM_EXIT_IO;
2023         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2024         vcpu->run->io.size = vcpu->arch.pio.size = size;
2025         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2026         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = 1;
2027         vcpu->run->io.port = vcpu->arch.pio.port = port;
2028         vcpu->arch.pio.in = in;
2029         vcpu->arch.pio.string = 0;
2030         vcpu->arch.pio.down = 0;
2031         vcpu->arch.pio.guest_page_offset = 0;
2032         vcpu->arch.pio.rep = 0;
2033
2034         kvm_x86_ops->cache_regs(vcpu);
2035         memcpy(vcpu->arch.pio_data, &vcpu->arch.regs[VCPU_REGS_RAX], 4);
2036         kvm_x86_ops->decache_regs(vcpu);
2037
2038         kvm_x86_ops->skip_emulated_instruction(vcpu);
2039
2040         pio_dev = vcpu_find_pio_dev(vcpu, port);
2041         if (pio_dev) {
2042                 kernel_pio(pio_dev, vcpu, vcpu->arch.pio_data);
2043                 complete_pio(vcpu);
2044                 return 1;
2045         }
2046         return 0;
2047 }
2048 EXPORT_SYMBOL_GPL(kvm_emulate_pio);
2049
2050 int kvm_emulate_pio_string(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
2051                   int size, unsigned long count, int down,
2052                   gva_t address, int rep, unsigned port)
2053 {
2054         unsigned now, in_page;
2055         int i, ret = 0;
2056         int nr_pages = 1;
2057         struct page *page;
2058         struct kvm_io_device *pio_dev;
2059
2060         vcpu->run->exit_reason = KVM_EXIT_IO;
2061         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2062         vcpu->run->io.size = vcpu->arch.pio.size = size;
2063         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2064         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = count;
2065         vcpu->run->io.port = vcpu->arch.pio.port = port;
2066         vcpu->arch.pio.in = in;
2067         vcpu->arch.pio.string = 1;
2068         vcpu->arch.pio.down = down;
2069         vcpu->arch.pio.guest_page_offset = offset_in_page(address);
2070         vcpu->arch.pio.rep = rep;
2071
2072         if (!count) {
2073                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2074                 return 1;
2075         }
2076
2077         if (!down)
2078                 in_page = PAGE_SIZE - offset_in_page(address);
2079         else
2080                 in_page = offset_in_page(address) + size;
2081         now = min(count, (unsigned long)in_page / size);
2082         if (!now) {
2083                 /*
2084                  * String I/O straddles page boundary.  Pin two guest pages
2085                  * so that we satisfy atomicity constraints.  Do just one
2086                  * transaction to avoid complexity.
2087                  */
2088                 nr_pages = 2;
2089                 now = 1;
2090         }
2091         if (down) {
2092                 /*
2093                  * String I/O in reverse.  Yuck.  Kill the guest, fix later.
2094                  */
2095                 pr_unimpl(vcpu, "guest string pio down\n");
2096                 kvm_inject_gp(vcpu, 0);
2097                 return 1;
2098         }
2099         vcpu->run->io.count = now;
2100         vcpu->arch.pio.cur_count = now;
2101
2102         if (vcpu->arch.pio.cur_count == vcpu->arch.pio.count)
2103                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2104
2105         for (i = 0; i < nr_pages; ++i) {
2106                 mutex_lock(&vcpu->kvm->lock);
2107                 page = gva_to_page(vcpu, address + i * PAGE_SIZE);
2108                 vcpu->arch.pio.guest_pages[i] = page;
2109                 mutex_unlock(&vcpu->kvm->lock);
2110                 if (!page) {
2111                         kvm_inject_gp(vcpu, 0);
2112                         free_pio_guest_pages(vcpu);
2113                         return 1;
2114                 }
2115         }
2116
2117         pio_dev = vcpu_find_pio_dev(vcpu, port);
2118         if (!vcpu->arch.pio.in) {
2119                 /* string PIO write */
2120                 ret = pio_copy_data(vcpu);
2121                 if (ret >= 0 && pio_dev) {
2122                         pio_string_write(pio_dev, vcpu);
2123                         complete_pio(vcpu);
2124                         if (vcpu->arch.pio.count == 0)
2125                                 ret = 1;
2126                 }
2127         } else if (pio_dev)
2128                 pr_unimpl(vcpu, "no string pio read support yet, "
2129                        "port %x size %d count %ld\n",
2130                         port, size, count);
2131
2132         return ret;
2133 }
2134 EXPORT_SYMBOL_GPL(kvm_emulate_pio_string);
2135
2136 int kvm_arch_init(void *opaque)
2137 {
2138         int r;
2139         struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
2140
2141         r = kvm_mmu_module_init();
2142         if (r)
2143                 goto out_fail;
2144
2145         kvm_init_msr_list();
2146
2147         if (kvm_x86_ops) {
2148                 printk(KERN_ERR "kvm: already loaded the other module\n");
2149                 r = -EEXIST;
2150                 goto out;
2151         }
2152
2153         if (!ops->cpu_has_kvm_support()) {
2154                 printk(KERN_ERR "kvm: no hardware support\n");
2155                 r = -EOPNOTSUPP;
2156                 goto out;
2157         }
2158         if (ops->disabled_by_bios()) {
2159                 printk(KERN_ERR "kvm: disabled by bios\n");
2160                 r = -EOPNOTSUPP;
2161                 goto out;
2162         }
2163
2164         kvm_x86_ops = ops;
2165         kvm_mmu_set_nonpresent_ptes(0ull, 0ull);
2166         return 0;
2167
2168 out:
2169         kvm_mmu_module_exit();
2170 out_fail:
2171         return r;
2172 }
2173
2174 void kvm_arch_exit(void)
2175 {
2176         kvm_x86_ops = NULL;
2177         kvm_mmu_module_exit();
2178 }
2179
2180 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
2181 {
2182         ++vcpu->stat.halt_exits;
2183         if (irqchip_in_kernel(vcpu->kvm)) {
2184                 vcpu->arch.mp_state = VCPU_MP_STATE_HALTED;
2185                 kvm_vcpu_block(vcpu);
2186                 if (vcpu->arch.mp_state != VCPU_MP_STATE_RUNNABLE)
2187                         return -EINTR;
2188                 return 1;
2189         } else {
2190                 vcpu->run->exit_reason = KVM_EXIT_HLT;
2191                 return 0;
2192         }
2193 }
2194 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
2195
2196 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
2197 {
2198         unsigned long nr, a0, a1, a2, a3, ret;
2199
2200         kvm_x86_ops->cache_regs(vcpu);
2201
2202         nr = vcpu->arch.regs[VCPU_REGS_RAX];
2203         a0 = vcpu->arch.regs[VCPU_REGS_RBX];
2204         a1 = vcpu->arch.regs[VCPU_REGS_RCX];
2205         a2 = vcpu->arch.regs[VCPU_REGS_RDX];
2206         a3 = vcpu->arch.regs[VCPU_REGS_RSI];
2207
2208         if (!is_long_mode(vcpu)) {
2209                 nr &= 0xFFFFFFFF;
2210                 a0 &= 0xFFFFFFFF;
2211                 a1 &= 0xFFFFFFFF;
2212                 a2 &= 0xFFFFFFFF;
2213                 a3 &= 0xFFFFFFFF;
2214         }
2215
2216         switch (nr) {
2217         default:
2218                 ret = -KVM_ENOSYS;
2219                 break;
2220         }
2221         vcpu->arch.regs[VCPU_REGS_RAX] = ret;
2222         kvm_x86_ops->decache_regs(vcpu);
2223         return 0;
2224 }
2225 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
2226
2227 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
2228 {
2229         char instruction[3];
2230         int ret = 0;
2231
2232         mutex_lock(&vcpu->kvm->lock);
2233
2234         /*
2235          * Blow out the MMU to ensure that no other VCPU has an active mapping
2236          * to ensure that the updated hypercall appears atomically across all
2237          * VCPUs.
2238          */
2239         kvm_mmu_zap_all(vcpu->kvm);
2240
2241         kvm_x86_ops->cache_regs(vcpu);
2242         kvm_x86_ops->patch_hypercall(vcpu, instruction);
2243         if (emulator_write_emulated(vcpu->arch.rip, instruction, 3, vcpu)
2244             != X86EMUL_CONTINUE)
2245                 ret = -EFAULT;
2246
2247         mutex_unlock(&vcpu->kvm->lock);
2248
2249         return ret;
2250 }
2251
2252 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
2253 {
2254         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
2255 }
2256
2257 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2258 {
2259         struct descriptor_table dt = { limit, base };
2260
2261         kvm_x86_ops->set_gdt(vcpu, &dt);
2262 }
2263
2264 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2265 {
2266         struct descriptor_table dt = { limit, base };
2267
2268         kvm_x86_ops->set_idt(vcpu, &dt);
2269 }
2270
2271 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
2272                    unsigned long *rflags)
2273 {
2274         lmsw(vcpu, msw);
2275         *rflags = kvm_x86_ops->get_rflags(vcpu);
2276 }
2277
2278 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
2279 {
2280         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2281         switch (cr) {
2282         case 0:
2283                 return vcpu->arch.cr0;
2284         case 2:
2285                 return vcpu->arch.cr2;
2286         case 3:
2287                 return vcpu->arch.cr3;
2288         case 4:
2289                 return vcpu->arch.cr4;
2290         case 8:
2291                 return get_cr8(vcpu);
2292         default:
2293                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __FUNCTION__, cr);
2294                 return 0;
2295         }
2296 }
2297
2298 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
2299                      unsigned long *rflags)
2300 {
2301         switch (cr) {
2302         case 0:
2303                 set_cr0(vcpu, mk_cr_64(vcpu->arch.cr0, val));
2304                 *rflags = kvm_x86_ops->get_rflags(vcpu);
2305                 break;
2306         case 2:
2307                 vcpu->arch.cr2 = val;
2308                 break;
2309         case 3:
2310                 set_cr3(vcpu, val);
2311                 break;
2312         case 4:
2313                 set_cr4(vcpu, mk_cr_64(vcpu->arch.cr4, val));
2314                 break;
2315         case 8:
2316                 set_cr8(vcpu, val & 0xfUL);
2317                 break;
2318         default:
2319                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __FUNCTION__, cr);
2320         }
2321 }
2322
2323 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
2324 {
2325         struct kvm_cpuid_entry2 *e = &vcpu->arch.cpuid_entries[i];
2326         int j, nent = vcpu->arch.cpuid_nent;
2327
2328         e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
2329         /* when no next entry is found, the current entry[i] is reselected */
2330         for (j = i + 1; j == i; j = (j + 1) % nent) {
2331                 struct kvm_cpuid_entry2 *ej = &vcpu->arch.cpuid_entries[j];
2332                 if (ej->function == e->function) {
2333                         ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
2334                         return j;
2335                 }
2336         }
2337         return 0; /* silence gcc, even though control never reaches here */
2338 }
2339
2340 /* find an entry with matching function, matching index (if needed), and that
2341  * should be read next (if it's stateful) */
2342 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
2343         u32 function, u32 index)
2344 {
2345         if (e->function != function)
2346                 return 0;
2347         if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
2348                 return 0;
2349         if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
2350                 !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
2351                 return 0;
2352         return 1;
2353 }
2354
2355 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
2356 {
2357         int i;
2358         u32 function, index;
2359         struct kvm_cpuid_entry2 *e, *best;
2360
2361         kvm_x86_ops->cache_regs(vcpu);
2362         function = vcpu->arch.regs[VCPU_REGS_RAX];
2363         index = vcpu->arch.regs[VCPU_REGS_RCX];
2364         vcpu->arch.regs[VCPU_REGS_RAX] = 0;
2365         vcpu->arch.regs[VCPU_REGS_RBX] = 0;
2366         vcpu->arch.regs[VCPU_REGS_RCX] = 0;
2367         vcpu->arch.regs[VCPU_REGS_RDX] = 0;
2368         best = NULL;
2369         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
2370                 e = &vcpu->arch.cpuid_entries[i];
2371                 if (is_matching_cpuid_entry(e, function, index)) {
2372                         if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
2373                                 move_to_next_stateful_cpuid_entry(vcpu, i);
2374                         best = e;
2375                         break;
2376                 }
2377                 /*
2378                  * Both basic or both extended?
2379                  */
2380                 if (((e->function ^ function) & 0x80000000) == 0)
2381                         if (!best || e->function > best->function)
2382                                 best = e;
2383         }
2384         if (best) {
2385                 vcpu->arch.regs[VCPU_REGS_RAX] = best->eax;
2386                 vcpu->arch.regs[VCPU_REGS_RBX] = best->ebx;
2387                 vcpu->arch.regs[VCPU_REGS_RCX] = best->ecx;
2388                 vcpu->arch.regs[VCPU_REGS_RDX] = best->edx;
2389         }
2390         kvm_x86_ops->decache_regs(vcpu);
2391         kvm_x86_ops->skip_emulated_instruction(vcpu);
2392 }
2393 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
2394
2395 /*
2396  * Check if userspace requested an interrupt window, and that the
2397  * interrupt window is open.
2398  *
2399  * No need to exit to userspace if we already have an interrupt queued.
2400  */
2401 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu,
2402                                           struct kvm_run *kvm_run)
2403 {
2404         return (!vcpu->arch.irq_summary &&
2405                 kvm_run->request_interrupt_window &&
2406                 vcpu->arch.interrupt_window_open &&
2407                 (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF));
2408 }
2409
2410 static void post_kvm_run_save(struct kvm_vcpu *vcpu,
2411                               struct kvm_run *kvm_run)
2412 {
2413         kvm_run->if_flag = (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
2414         kvm_run->cr8 = get_cr8(vcpu);
2415         kvm_run->apic_base = kvm_get_apic_base(vcpu);
2416         if (irqchip_in_kernel(vcpu->kvm))
2417                 kvm_run->ready_for_interrupt_injection = 1;
2418         else
2419                 kvm_run->ready_for_interrupt_injection =
2420                                         (vcpu->arch.interrupt_window_open &&
2421                                          vcpu->arch.irq_summary == 0);
2422 }
2423
2424 static int __vcpu_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2425 {
2426         int r;
2427
2428         if (unlikely(vcpu->arch.mp_state == VCPU_MP_STATE_SIPI_RECEIVED)) {
2429                 pr_debug("vcpu %d received sipi with vector # %x\n",
2430                        vcpu->vcpu_id, vcpu->arch.sipi_vector);
2431                 kvm_lapic_reset(vcpu);
2432                 r = kvm_x86_ops->vcpu_reset(vcpu);
2433                 if (r)
2434                         return r;
2435                 vcpu->arch.mp_state = VCPU_MP_STATE_RUNNABLE;
2436         }
2437
2438 preempted:
2439         if (vcpu->guest_debug.enabled)
2440                 kvm_x86_ops->guest_debug_pre(vcpu);
2441
2442 again:
2443         r = kvm_mmu_reload(vcpu);
2444         if (unlikely(r))
2445                 goto out;
2446
2447         kvm_inject_pending_timer_irqs(vcpu);
2448
2449         preempt_disable();
2450
2451         kvm_x86_ops->prepare_guest_switch(vcpu);
2452         kvm_load_guest_fpu(vcpu);
2453
2454         local_irq_disable();
2455
2456         if (signal_pending(current)) {
2457                 local_irq_enable();
2458                 preempt_enable();
2459                 r = -EINTR;
2460                 kvm_run->exit_reason = KVM_EXIT_INTR;
2461                 ++vcpu->stat.signal_exits;
2462                 goto out;
2463         }
2464
2465         if (vcpu->arch.exception.pending)
2466                 __queue_exception(vcpu);
2467         else if (irqchip_in_kernel(vcpu->kvm))
2468                 kvm_x86_ops->inject_pending_irq(vcpu);
2469         else
2470                 kvm_x86_ops->inject_pending_vectors(vcpu, kvm_run);
2471
2472         vcpu->guest_mode = 1;
2473         kvm_guest_enter();
2474
2475         if (vcpu->requests)
2476                 if (test_and_clear_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
2477                         kvm_x86_ops->tlb_flush(vcpu);
2478
2479         kvm_x86_ops->run(vcpu, kvm_run);
2480
2481         vcpu->guest_mode = 0;
2482         local_irq_enable();
2483
2484         ++vcpu->stat.exits;
2485
2486         /*
2487          * We must have an instruction between local_irq_enable() and
2488          * kvm_guest_exit(), so the timer interrupt isn't delayed by
2489          * the interrupt shadow.  The stat.exits increment will do nicely.
2490          * But we need to prevent reordering, hence this barrier():
2491          */
2492         barrier();
2493
2494         kvm_guest_exit();
2495
2496         preempt_enable();
2497
2498         /*
2499          * Profile KVM exit RIPs:
2500          */
2501         if (unlikely(prof_on == KVM_PROFILING)) {
2502                 kvm_x86_ops->cache_regs(vcpu);
2503                 profile_hit(KVM_PROFILING, (void *)vcpu->arch.rip);
2504         }
2505
2506         if (vcpu->arch.exception.pending && kvm_x86_ops->exception_injected(vcpu))
2507                 vcpu->arch.exception.pending = false;
2508
2509         r = kvm_x86_ops->handle_exit(kvm_run, vcpu);
2510
2511         if (r > 0) {
2512                 if (dm_request_for_irq_injection(vcpu, kvm_run)) {
2513                         r = -EINTR;
2514                         kvm_run->exit_reason = KVM_EXIT_INTR;
2515                         ++vcpu->stat.request_irq_exits;
2516                         goto out;
2517                 }
2518                 if (!need_resched())
2519                         goto again;
2520         }
2521
2522 out:
2523         if (r > 0) {
2524                 kvm_resched(vcpu);
2525                 goto preempted;
2526         }
2527
2528         post_kvm_run_save(vcpu, kvm_run);
2529
2530         return r;
2531 }
2532
2533 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2534 {
2535         int r;
2536         sigset_t sigsaved;
2537
2538         vcpu_load(vcpu);
2539
2540         if (unlikely(vcpu->arch.mp_state == VCPU_MP_STATE_UNINITIALIZED)) {
2541                 kvm_vcpu_block(vcpu);
2542                 vcpu_put(vcpu);
2543                 return -EAGAIN;
2544         }
2545
2546         if (vcpu->sigset_active)
2547                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
2548
2549         /* re-sync apic's tpr */
2550         if (!irqchip_in_kernel(vcpu->kvm))
2551                 set_cr8(vcpu, kvm_run->cr8);
2552
2553         if (vcpu->arch.pio.cur_count) {
2554                 r = complete_pio(vcpu);
2555                 if (r)
2556                         goto out;
2557         }
2558 #if CONFIG_HAS_IOMEM
2559         if (vcpu->mmio_needed) {
2560                 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
2561                 vcpu->mmio_read_completed = 1;
2562                 vcpu->mmio_needed = 0;
2563                 r = emulate_instruction(vcpu, kvm_run,
2564                                         vcpu->arch.mmio_fault_cr2, 0, 1);
2565                 if (r == EMULATE_DO_MMIO) {
2566                         /*
2567                          * Read-modify-write.  Back to userspace.
2568                          */
2569                         r = 0;
2570                         goto out;
2571                 }
2572         }
2573 #endif
2574         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL) {
2575                 kvm_x86_ops->cache_regs(vcpu);
2576                 vcpu->arch.regs[VCPU_REGS_RAX] = kvm_run->hypercall.ret;
2577                 kvm_x86_ops->decache_regs(vcpu);
2578         }
2579
2580         r = __vcpu_run(vcpu, kvm_run);
2581
2582 out:
2583         if (vcpu->sigset_active)
2584                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
2585
2586         vcpu_put(vcpu);
2587         return r;
2588 }
2589
2590 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
2591 {
2592         vcpu_load(vcpu);
2593
2594         kvm_x86_ops->cache_regs(vcpu);
2595
2596         regs->rax = vcpu->arch.regs[VCPU_REGS_RAX];
2597         regs->rbx = vcpu->arch.regs[VCPU_REGS_RBX];
2598         regs->rcx = vcpu->arch.regs[VCPU_REGS_RCX];
2599         regs->rdx = vcpu->arch.regs[VCPU_REGS_RDX];
2600         regs->rsi = vcpu->arch.regs[VCPU_REGS_RSI];
2601         regs->rdi = vcpu->arch.regs[VCPU_REGS_RDI];
2602         regs->rsp = vcpu->arch.regs[VCPU_REGS_RSP];
2603         regs->rbp = vcpu->arch.regs[VCPU_REGS_RBP];
2604 #ifdef CONFIG_X86_64
2605         regs->r8 = vcpu->arch.regs[VCPU_REGS_R8];
2606         regs->r9 = vcpu->arch.regs[VCPU_REGS_R9];
2607         regs->r10 = vcpu->arch.regs[VCPU_REGS_R10];
2608         regs->r11 = vcpu->arch.regs[VCPU_REGS_R11];
2609         regs->r12 = vcpu->arch.regs[VCPU_REGS_R12];
2610         regs->r13 = vcpu->arch.regs[VCPU_REGS_R13];
2611         regs->r14 = vcpu->arch.regs[VCPU_REGS_R14];
2612         regs->r15 = vcpu->arch.regs[VCPU_REGS_R15];
2613 #endif
2614
2615         regs->rip = vcpu->arch.rip;
2616         regs->rflags = kvm_x86_ops->get_rflags(vcpu);
2617
2618         /*
2619          * Don't leak debug flags in case they were set for guest debugging
2620          */
2621         if (vcpu->guest_debug.enabled && vcpu->guest_debug.singlestep)
2622                 regs->rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
2623
2624         vcpu_put(vcpu);
2625
2626         return 0;
2627 }
2628
2629 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
2630 {
2631         vcpu_load(vcpu);
2632
2633         vcpu->arch.regs[VCPU_REGS_RAX] = regs->rax;
2634         vcpu->arch.regs[VCPU_REGS_RBX] = regs->rbx;
2635         vcpu->arch.regs[VCPU_REGS_RCX] = regs->rcx;
2636         vcpu->arch.regs[VCPU_REGS_RDX] = regs->rdx;
2637         vcpu->arch.regs[VCPU_REGS_RSI] = regs->rsi;
2638         vcpu->arch.regs[VCPU_REGS_RDI] = regs->rdi;
2639         vcpu->arch.regs[VCPU_REGS_RSP] = regs->rsp;
2640         vcpu->arch.regs[VCPU_REGS_RBP] = regs->rbp;
2641 #ifdef CONFIG_X86_64
2642         vcpu->arch.regs[VCPU_REGS_R8] = regs->r8;
2643         vcpu->arch.regs[VCPU_REGS_R9] = regs->r9;
2644         vcpu->arch.regs[VCPU_REGS_R10] = regs->r10;
2645         vcpu->arch.regs[VCPU_REGS_R11] = regs->r11;
2646         vcpu->arch.regs[VCPU_REGS_R12] = regs->r12;
2647         vcpu->arch.regs[VCPU_REGS_R13] = regs->r13;
2648         vcpu->arch.regs[VCPU_REGS_R14] = regs->r14;
2649         vcpu->arch.regs[VCPU_REGS_R15] = regs->r15;
2650 #endif
2651
2652         vcpu->arch.rip = regs->rip;
2653         kvm_x86_ops->set_rflags(vcpu, regs->rflags);
2654
2655         kvm_x86_ops->decache_regs(vcpu);
2656
2657         vcpu_put(vcpu);
2658
2659         return 0;
2660 }
2661
2662 static void get_segment(struct kvm_vcpu *vcpu,
2663                         struct kvm_segment *var, int seg)
2664 {
2665         return kvm_x86_ops->get_segment(vcpu, var, seg);
2666 }
2667
2668 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
2669 {
2670         struct kvm_segment cs;
2671
2672         get_segment(vcpu, &cs, VCPU_SREG_CS);
2673         *db = cs.db;
2674         *l = cs.l;
2675 }
2676 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
2677
2678 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
2679                                   struct kvm_sregs *sregs)
2680 {
2681         struct descriptor_table dt;
2682         int pending_vec;
2683
2684         vcpu_load(vcpu);
2685
2686         get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
2687         get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
2688         get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
2689         get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
2690         get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
2691         get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
2692
2693         get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
2694         get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
2695
2696         kvm_x86_ops->get_idt(vcpu, &dt);
2697         sregs->idt.limit = dt.limit;
2698         sregs->idt.base = dt.base;
2699         kvm_x86_ops->get_gdt(vcpu, &dt);
2700         sregs->gdt.limit = dt.limit;
2701         sregs->gdt.base = dt.base;
2702
2703         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2704         sregs->cr0 = vcpu->arch.cr0;
2705         sregs->cr2 = vcpu->arch.cr2;
2706         sregs->cr3 = vcpu->arch.cr3;
2707         sregs->cr4 = vcpu->arch.cr4;
2708         sregs->cr8 = get_cr8(vcpu);
2709         sregs->efer = vcpu->arch.shadow_efer;
2710         sregs->apic_base = kvm_get_apic_base(vcpu);
2711
2712         if (irqchip_in_kernel(vcpu->kvm)) {
2713                 memset(sregs->interrupt_bitmap, 0,
2714                        sizeof sregs->interrupt_bitmap);
2715                 pending_vec = kvm_x86_ops->get_irq(vcpu);
2716                 if (pending_vec >= 0)
2717                         set_bit(pending_vec,
2718                                 (unsigned long *)sregs->interrupt_bitmap);
2719         } else
2720                 memcpy(sregs->interrupt_bitmap, vcpu->arch.irq_pending,
2721                        sizeof sregs->interrupt_bitmap);
2722
2723         vcpu_put(vcpu);
2724
2725         return 0;
2726 }
2727
2728 static void set_segment(struct kvm_vcpu *vcpu,
2729                         struct kvm_segment *var, int seg)
2730 {
2731         return kvm_x86_ops->set_segment(vcpu, var, seg);
2732 }
2733
2734 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
2735                                   struct kvm_sregs *sregs)
2736 {
2737         int mmu_reset_needed = 0;
2738         int i, pending_vec, max_bits;
2739         struct descriptor_table dt;
2740
2741         vcpu_load(vcpu);
2742
2743         dt.limit = sregs->idt.limit;
2744         dt.base = sregs->idt.base;
2745         kvm_x86_ops->set_idt(vcpu, &dt);
2746         dt.limit = sregs->gdt.limit;
2747         dt.base = sregs->gdt.base;
2748         kvm_x86_ops->set_gdt(vcpu, &dt);
2749
2750         vcpu->arch.cr2 = sregs->cr2;
2751         mmu_reset_needed |= vcpu->arch.cr3 != sregs->cr3;
2752         vcpu->arch.cr3 = sregs->cr3;
2753
2754         set_cr8(vcpu, sregs->cr8);
2755
2756         mmu_reset_needed |= vcpu->arch.shadow_efer != sregs->efer;
2757 #ifdef CONFIG_X86_64
2758         kvm_x86_ops->set_efer(vcpu, sregs->efer);
2759 #endif
2760         kvm_set_apic_base(vcpu, sregs->apic_base);
2761
2762         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2763
2764         mmu_reset_needed |= vcpu->arch.cr0 != sregs->cr0;
2765         vcpu->arch.cr0 = sregs->cr0;
2766         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
2767
2768         mmu_reset_needed |= vcpu->arch.cr4 != sregs->cr4;
2769         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
2770         if (!is_long_mode(vcpu) && is_pae(vcpu))
2771                 load_pdptrs(vcpu, vcpu->arch.cr3);
2772
2773         if (mmu_reset_needed)
2774                 kvm_mmu_reset_context(vcpu);
2775
2776         if (!irqchip_in_kernel(vcpu->kvm)) {
2777                 memcpy(vcpu->arch.irq_pending, sregs->interrupt_bitmap,
2778                        sizeof vcpu->arch.irq_pending);
2779                 vcpu->arch.irq_summary = 0;
2780                 for (i = 0; i < ARRAY_SIZE(vcpu->arch.irq_pending); ++i)
2781                         if (vcpu->arch.irq_pending[i])
2782                                 __set_bit(i, &vcpu->arch.irq_summary);
2783         } else {
2784                 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
2785                 pending_vec = find_first_bit(
2786                         (const unsigned long *)sregs->interrupt_bitmap,
2787                         max_bits);
2788                 /* Only pending external irq is handled here */
2789                 if (pending_vec < max_bits) {
2790                         kvm_x86_ops->set_irq(vcpu, pending_vec);
2791                         pr_debug("Set back pending irq %d\n",
2792                                  pending_vec);
2793                 }
2794         }
2795
2796         set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
2797         set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
2798         set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
2799         set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
2800         set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
2801         set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
2802
2803         set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
2804         set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
2805
2806         vcpu_put(vcpu);
2807
2808         return 0;
2809 }
2810
2811 int kvm_arch_vcpu_ioctl_debug_guest(struct kvm_vcpu *vcpu,
2812                                     struct kvm_debug_guest *dbg)
2813 {
2814         int r;
2815
2816         vcpu_load(vcpu);
2817
2818         r = kvm_x86_ops->set_guest_debug(vcpu, dbg);
2819
2820         vcpu_put(vcpu);
2821
2822         return r;
2823 }
2824
2825 /*
2826  * fxsave fpu state.  Taken from x86_64/processor.h.  To be killed when
2827  * we have asm/x86/processor.h
2828  */
2829 struct fxsave {
2830         u16     cwd;
2831         u16     swd;
2832         u16     twd;
2833         u16     fop;
2834         u64     rip;
2835         u64     rdp;
2836         u32     mxcsr;
2837         u32     mxcsr_mask;
2838         u32     st_space[32];   /* 8*16 bytes for each FP-reg = 128 bytes */
2839 #ifdef CONFIG_X86_64
2840         u32     xmm_space[64];  /* 16*16 bytes for each XMM-reg = 256 bytes */
2841 #else
2842         u32     xmm_space[32];  /* 8*16 bytes for each XMM-reg = 128 bytes */
2843 #endif
2844 };
2845
2846 /*
2847  * Translate a guest virtual address to a guest physical address.
2848  */
2849 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
2850                                     struct kvm_translation *tr)
2851 {
2852         unsigned long vaddr = tr->linear_address;
2853         gpa_t gpa;
2854
2855         vcpu_load(vcpu);
2856         mutex_lock(&vcpu->kvm->lock);
2857         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, vaddr);
2858         tr->physical_address = gpa;
2859         tr->valid = gpa != UNMAPPED_GVA;
2860         tr->writeable = 1;
2861         tr->usermode = 0;
2862         mutex_unlock(&vcpu->kvm->lock);
2863         vcpu_put(vcpu);
2864
2865         return 0;
2866 }
2867
2868 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2869 {
2870         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
2871
2872         vcpu_load(vcpu);
2873
2874         memcpy(fpu->fpr, fxsave->st_space, 128);
2875         fpu->fcw = fxsave->cwd;
2876         fpu->fsw = fxsave->swd;
2877         fpu->ftwx = fxsave->twd;
2878         fpu->last_opcode = fxsave->fop;
2879         fpu->last_ip = fxsave->rip;
2880         fpu->last_dp = fxsave->rdp;
2881         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
2882
2883         vcpu_put(vcpu);
2884
2885         return 0;
2886 }
2887
2888 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2889 {
2890         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
2891
2892         vcpu_load(vcpu);
2893
2894         memcpy(fxsave->st_space, fpu->fpr, 128);
2895         fxsave->cwd = fpu->fcw;
2896         fxsave->swd = fpu->fsw;
2897         fxsave->twd = fpu->ftwx;
2898         fxsave->fop = fpu->last_opcode;
2899         fxsave->rip = fpu->last_ip;
2900         fxsave->rdp = fpu->last_dp;
2901         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
2902
2903         vcpu_put(vcpu);
2904
2905         return 0;
2906 }
2907
2908 void fx_init(struct kvm_vcpu *vcpu)
2909 {
2910         unsigned after_mxcsr_mask;
2911
2912         /* Initialize guest FPU by resetting ours and saving into guest's */
2913         preempt_disable();
2914         fx_save(&vcpu->arch.host_fx_image);
2915         fpu_init();
2916         fx_save(&vcpu->arch.guest_fx_image);
2917         fx_restore(&vcpu->arch.host_fx_image);
2918         preempt_enable();
2919
2920         vcpu->arch.cr0 |= X86_CR0_ET;
2921         after_mxcsr_mask = offsetof(struct i387_fxsave_struct, st_space);
2922         vcpu->arch.guest_fx_image.mxcsr = 0x1f80;
2923         memset((void *)&vcpu->arch.guest_fx_image + after_mxcsr_mask,
2924                0, sizeof(struct i387_fxsave_struct) - after_mxcsr_mask);
2925 }
2926 EXPORT_SYMBOL_GPL(fx_init);
2927
2928 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
2929 {
2930         if (!vcpu->fpu_active || vcpu->guest_fpu_loaded)
2931                 return;
2932
2933         vcpu->guest_fpu_loaded = 1;
2934         fx_save(&vcpu->arch.host_fx_image);
2935         fx_restore(&vcpu->arch.guest_fx_image);
2936 }
2937 EXPORT_SYMBOL_GPL(kvm_load_guest_fpu);
2938
2939 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
2940 {
2941         if (!vcpu->guest_fpu_loaded)
2942                 return;
2943
2944         vcpu->guest_fpu_loaded = 0;
2945         fx_save(&vcpu->arch.guest_fx_image);
2946         fx_restore(&vcpu->arch.host_fx_image);
2947         ++vcpu->stat.fpu_reload;
2948 }
2949 EXPORT_SYMBOL_GPL(kvm_put_guest_fpu);
2950
2951 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
2952 {
2953         kvm_x86_ops->vcpu_free(vcpu);
2954 }
2955
2956 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
2957                                                 unsigned int id)
2958 {
2959         return kvm_x86_ops->vcpu_create(kvm, id);
2960 }
2961
2962 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
2963 {
2964         int r;
2965
2966         /* We do fxsave: this must be aligned. */
2967         BUG_ON((unsigned long)&vcpu->arch.host_fx_image & 0xF);
2968
2969         vcpu_load(vcpu);
2970         r = kvm_arch_vcpu_reset(vcpu);
2971         if (r == 0)
2972                 r = kvm_mmu_setup(vcpu);
2973         vcpu_put(vcpu);
2974         if (r < 0)
2975                 goto free_vcpu;
2976
2977         return 0;
2978 free_vcpu:
2979         kvm_x86_ops->vcpu_free(vcpu);
2980         return r;
2981 }
2982
2983 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
2984 {
2985         vcpu_load(vcpu);
2986         kvm_mmu_unload(vcpu);
2987         vcpu_put(vcpu);
2988
2989         kvm_x86_ops->vcpu_free(vcpu);
2990 }
2991
2992 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
2993 {
2994         return kvm_x86_ops->vcpu_reset(vcpu);
2995 }
2996
2997 void kvm_arch_hardware_enable(void *garbage)
2998 {
2999         kvm_x86_ops->hardware_enable(garbage);
3000 }
3001
3002 void kvm_arch_hardware_disable(void *garbage)
3003 {
3004         kvm_x86_ops->hardware_disable(garbage);
3005 }
3006
3007 int kvm_arch_hardware_setup(void)
3008 {
3009         return kvm_x86_ops->hardware_setup();
3010 }
3011
3012 void kvm_arch_hardware_unsetup(void)
3013 {
3014         kvm_x86_ops->hardware_unsetup();
3015 }
3016
3017 void kvm_arch_check_processor_compat(void *rtn)
3018 {
3019         kvm_x86_ops->check_processor_compatibility(rtn);
3020 }
3021
3022 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
3023 {
3024         struct page *page;
3025         struct kvm *kvm;
3026         int r;
3027
3028         BUG_ON(vcpu->kvm == NULL);
3029         kvm = vcpu->kvm;
3030
3031         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
3032         if (!irqchip_in_kernel(kvm) || vcpu->vcpu_id == 0)
3033                 vcpu->arch.mp_state = VCPU_MP_STATE_RUNNABLE;
3034         else
3035                 vcpu->arch.mp_state = VCPU_MP_STATE_UNINITIALIZED;
3036
3037         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
3038         if (!page) {
3039                 r = -ENOMEM;
3040                 goto fail;
3041         }
3042         vcpu->arch.pio_data = page_address(page);
3043
3044         r = kvm_mmu_create(vcpu);
3045         if (r < 0)
3046                 goto fail_free_pio_data;
3047
3048         if (irqchip_in_kernel(kvm)) {
3049                 r = kvm_create_lapic(vcpu);
3050                 if (r < 0)
3051                         goto fail_mmu_destroy;
3052         }
3053
3054         return 0;
3055
3056 fail_mmu_destroy:
3057         kvm_mmu_destroy(vcpu);
3058 fail_free_pio_data:
3059         free_page((unsigned long)vcpu->arch.pio_data);
3060 fail:
3061         return r;
3062 }
3063
3064 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
3065 {
3066         kvm_free_lapic(vcpu);
3067         kvm_mmu_destroy(vcpu);
3068         free_page((unsigned long)vcpu->arch.pio_data);
3069 }
3070
3071 struct  kvm *kvm_arch_create_vm(void)
3072 {
3073         struct kvm *kvm = kzalloc(sizeof(struct kvm), GFP_KERNEL);
3074
3075         if (!kvm)
3076                 return ERR_PTR(-ENOMEM);
3077
3078         INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
3079
3080         return kvm;
3081 }
3082
3083 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
3084 {
3085         vcpu_load(vcpu);
3086         kvm_mmu_unload(vcpu);
3087         vcpu_put(vcpu);
3088 }
3089
3090 static void kvm_free_vcpus(struct kvm *kvm)
3091 {
3092         unsigned int i;
3093
3094         /*
3095          * Unpin any mmu pages first.
3096          */
3097         for (i = 0; i < KVM_MAX_VCPUS; ++i)
3098                 if (kvm->vcpus[i])
3099                         kvm_unload_vcpu_mmu(kvm->vcpus[i]);
3100         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
3101                 if (kvm->vcpus[i]) {
3102                         kvm_arch_vcpu_free(kvm->vcpus[i]);
3103                         kvm->vcpus[i] = NULL;
3104                 }
3105         }
3106
3107 }
3108
3109 void kvm_arch_destroy_vm(struct kvm *kvm)
3110 {
3111         kfree(kvm->arch.vpic);
3112         kfree(kvm->arch.vioapic);
3113         kvm_free_vcpus(kvm);
3114         kvm_free_physmem(kvm);
3115         kfree(kvm);
3116 }
3117
3118 int kvm_arch_set_memory_region(struct kvm *kvm,
3119                                 struct kvm_userspace_memory_region *mem,
3120                                 struct kvm_memory_slot old,
3121                                 int user_alloc)
3122 {
3123         int npages = mem->memory_size >> PAGE_SHIFT;
3124         struct kvm_memory_slot *memslot = &kvm->memslots[mem->slot];
3125
3126         /*To keep backward compatibility with older userspace,
3127          *x86 needs to hanlde !user_alloc case.
3128          */
3129         if (!user_alloc) {
3130                 if (npages && !old.rmap) {
3131                         down_write(&current->mm->mmap_sem);
3132                         memslot->userspace_addr = do_mmap(NULL, 0,
3133                                                      npages * PAGE_SIZE,
3134                                                      PROT_READ | PROT_WRITE,
3135                                                      MAP_SHARED | MAP_ANONYMOUS,
3136                                                      0);
3137                         up_write(&current->mm->mmap_sem);
3138
3139                         if (IS_ERR((void *)memslot->userspace_addr))
3140                                 return PTR_ERR((void *)memslot->userspace_addr);
3141                 } else {
3142                         if (!old.user_alloc && old.rmap) {
3143                                 int ret;
3144
3145                                 down_write(&current->mm->mmap_sem);
3146                                 ret = do_munmap(current->mm, old.userspace_addr,
3147                                                 old.npages * PAGE_SIZE);
3148                                 up_write(&current->mm->mmap_sem);
3149                                 if (ret < 0)
3150                                         printk(KERN_WARNING
3151                                        "kvm_vm_ioctl_set_memory_region: "
3152                                        "failed to munmap memory\n");
3153                         }
3154                 }
3155         }
3156
3157         if (!kvm->arch.n_requested_mmu_pages) {
3158                 unsigned int nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
3159                 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
3160         }
3161
3162         kvm_mmu_slot_remove_write_access(kvm, mem->slot);
3163         kvm_flush_remote_tlbs(kvm);
3164
3165         return 0;
3166 }
3167
3168 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
3169 {
3170         return vcpu->arch.mp_state == VCPU_MP_STATE_RUNNABLE
3171                || vcpu->arch.mp_state == VCPU_MP_STATE_SIPI_RECEIVED;
3172 }
3173
3174 static void vcpu_kick_intr(void *info)
3175 {
3176 #ifdef DEBUG
3177         struct kvm_vcpu *vcpu = (struct kvm_vcpu *)info;
3178         printk(KERN_DEBUG "vcpu_kick_intr %p \n", vcpu);
3179 #endif
3180 }
3181
3182 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
3183 {
3184         int ipi_pcpu = vcpu->cpu;
3185
3186         if (waitqueue_active(&vcpu->wq)) {
3187                 wake_up_interruptible(&vcpu->wq);
3188                 ++vcpu->stat.halt_wakeup;
3189         }
3190         if (vcpu->guest_mode)
3191                 smp_call_function_single(ipi_pcpu, vcpu_kick_intr, vcpu, 0, 0);
3192 }