KVM: Print data for unimplemented wrmsr
[safe/jmp/linux-2.6] / arch / x86 / kvm / x86.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * derived from drivers/kvm/kvm_main.c
5  *
6  * Copyright (C) 2006 Qumranet, Inc.
7  *
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                 r = 1;
688                 break;
689         default:
690                 r = 0;
691                 break;
692         }
693         return r;
694
695 }
696
697 long kvm_arch_dev_ioctl(struct file *filp,
698                         unsigned int ioctl, unsigned long arg)
699 {
700         void __user *argp = (void __user *)arg;
701         long r;
702
703         switch (ioctl) {
704         case KVM_GET_MSR_INDEX_LIST: {
705                 struct kvm_msr_list __user *user_msr_list = argp;
706                 struct kvm_msr_list msr_list;
707                 unsigned n;
708
709                 r = -EFAULT;
710                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
711                         goto out;
712                 n = msr_list.nmsrs;
713                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
714                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
715                         goto out;
716                 r = -E2BIG;
717                 if (n < num_msrs_to_save)
718                         goto out;
719                 r = -EFAULT;
720                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
721                                  num_msrs_to_save * sizeof(u32)))
722                         goto out;
723                 if (copy_to_user(user_msr_list->indices
724                                  + num_msrs_to_save * sizeof(u32),
725                                  &emulated_msrs,
726                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
727                         goto out;
728                 r = 0;
729                 break;
730         }
731         default:
732                 r = -EINVAL;
733         }
734 out:
735         return r;
736 }
737
738 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
739 {
740         kvm_x86_ops->vcpu_load(vcpu, cpu);
741 }
742
743 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
744 {
745         kvm_x86_ops->vcpu_put(vcpu);
746         kvm_put_guest_fpu(vcpu);
747 }
748
749 static int is_efer_nx(void)
750 {
751         u64 efer;
752
753         rdmsrl(MSR_EFER, efer);
754         return efer & EFER_NX;
755 }
756
757 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
758 {
759         int i;
760         struct kvm_cpuid_entry2 *e, *entry;
761
762         entry = NULL;
763         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
764                 e = &vcpu->arch.cpuid_entries[i];
765                 if (e->function == 0x80000001) {
766                         entry = e;
767                         break;
768                 }
769         }
770         if (entry && (entry->edx & (1 << 20)) && !is_efer_nx()) {
771                 entry->edx &= ~(1 << 20);
772                 printk(KERN_INFO "kvm: guest NX capability removed\n");
773         }
774 }
775
776 /* when an old userspace process fills a new kernel module */
777 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
778                                     struct kvm_cpuid *cpuid,
779                                     struct kvm_cpuid_entry __user *entries)
780 {
781         int r, i;
782         struct kvm_cpuid_entry *cpuid_entries;
783
784         r = -E2BIG;
785         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
786                 goto out;
787         r = -ENOMEM;
788         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry) * cpuid->nent);
789         if (!cpuid_entries)
790                 goto out;
791         r = -EFAULT;
792         if (copy_from_user(cpuid_entries, entries,
793                            cpuid->nent * sizeof(struct kvm_cpuid_entry)))
794                 goto out_free;
795         for (i = 0; i < cpuid->nent; i++) {
796                 vcpu->arch.cpuid_entries[i].function = cpuid_entries[i].function;
797                 vcpu->arch.cpuid_entries[i].eax = cpuid_entries[i].eax;
798                 vcpu->arch.cpuid_entries[i].ebx = cpuid_entries[i].ebx;
799                 vcpu->arch.cpuid_entries[i].ecx = cpuid_entries[i].ecx;
800                 vcpu->arch.cpuid_entries[i].edx = cpuid_entries[i].edx;
801                 vcpu->arch.cpuid_entries[i].index = 0;
802                 vcpu->arch.cpuid_entries[i].flags = 0;
803                 vcpu->arch.cpuid_entries[i].padding[0] = 0;
804                 vcpu->arch.cpuid_entries[i].padding[1] = 0;
805                 vcpu->arch.cpuid_entries[i].padding[2] = 0;
806         }
807         vcpu->arch.cpuid_nent = cpuid->nent;
808         cpuid_fix_nx_cap(vcpu);
809         r = 0;
810
811 out_free:
812         vfree(cpuid_entries);
813 out:
814         return r;
815 }
816
817 static int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
818                                     struct kvm_cpuid2 *cpuid,
819                                     struct kvm_cpuid_entry2 __user *entries)
820 {
821         int r;
822
823         r = -E2BIG;
824         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
825                 goto out;
826         r = -EFAULT;
827         if (copy_from_user(&vcpu->arch.cpuid_entries, entries,
828                            cpuid->nent * sizeof(struct kvm_cpuid_entry2)))
829                 goto out;
830         vcpu->arch.cpuid_nent = cpuid->nent;
831         return 0;
832
833 out:
834         return r;
835 }
836
837 static int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
838                                     struct kvm_cpuid2 *cpuid,
839                                     struct kvm_cpuid_entry2 __user *entries)
840 {
841         int r;
842
843         r = -E2BIG;
844         if (cpuid->nent < vcpu->arch.cpuid_nent)
845                 goto out;
846         r = -EFAULT;
847         if (copy_to_user(entries, &vcpu->arch.cpuid_entries,
848                            vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
849                 goto out;
850         return 0;
851
852 out:
853         cpuid->nent = vcpu->arch.cpuid_nent;
854         return r;
855 }
856
857 static inline u32 bit(int bitno)
858 {
859         return 1 << (bitno & 31);
860 }
861
862 static void do_cpuid_1_ent(struct kvm_cpuid_entry2 *entry, u32 function,
863                           u32 index)
864 {
865         entry->function = function;
866         entry->index = index;
867         cpuid_count(entry->function, entry->index,
868                 &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
869         entry->flags = 0;
870 }
871
872 static void do_cpuid_ent(struct kvm_cpuid_entry2 *entry, u32 function,
873                          u32 index, int *nent, int maxnent)
874 {
875         const u32 kvm_supported_word0_x86_features = bit(X86_FEATURE_FPU) |
876                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
877                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
878                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
879                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
880                 bit(X86_FEATURE_SEP) | bit(X86_FEATURE_PGE) |
881                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
882                 bit(X86_FEATURE_CLFLSH) | bit(X86_FEATURE_MMX) |
883                 bit(X86_FEATURE_FXSR) | bit(X86_FEATURE_XMM) |
884                 bit(X86_FEATURE_XMM2) | bit(X86_FEATURE_SELFSNOOP);
885         const u32 kvm_supported_word1_x86_features = bit(X86_FEATURE_FPU) |
886                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
887                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
888                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
889                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
890                 bit(X86_FEATURE_PGE) |
891                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
892                 bit(X86_FEATURE_MMX) | bit(X86_FEATURE_FXSR) |
893                 bit(X86_FEATURE_SYSCALL) |
894                 (bit(X86_FEATURE_NX) && is_efer_nx()) |
895 #ifdef CONFIG_X86_64
896                 bit(X86_FEATURE_LM) |
897 #endif
898                 bit(X86_FEATURE_MMXEXT) |
899                 bit(X86_FEATURE_3DNOWEXT) |
900                 bit(X86_FEATURE_3DNOW);
901         const u32 kvm_supported_word3_x86_features =
902                 bit(X86_FEATURE_XMM3) | bit(X86_FEATURE_CX16);
903         const u32 kvm_supported_word6_x86_features =
904                 bit(X86_FEATURE_LAHF_LM) | bit(X86_FEATURE_CMP_LEGACY);
905
906         /* all func 2 cpuid_count() should be called on the same cpu */
907         get_cpu();
908         do_cpuid_1_ent(entry, function, index);
909         ++*nent;
910
911         switch (function) {
912         case 0:
913                 entry->eax = min(entry->eax, (u32)0xb);
914                 break;
915         case 1:
916                 entry->edx &= kvm_supported_word0_x86_features;
917                 entry->ecx &= kvm_supported_word3_x86_features;
918                 break;
919         /* function 2 entries are STATEFUL. That is, repeated cpuid commands
920          * may return different values. This forces us to get_cpu() before
921          * issuing the first command, and also to emulate this annoying behavior
922          * in kvm_emulate_cpuid() using KVM_CPUID_FLAG_STATE_READ_NEXT */
923         case 2: {
924                 int t, times = entry->eax & 0xff;
925
926                 entry->flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
927                 for (t = 1; t < times && *nent < maxnent; ++t) {
928                         do_cpuid_1_ent(&entry[t], function, 0);
929                         entry[t].flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
930                         ++*nent;
931                 }
932                 break;
933         }
934         /* function 4 and 0xb have additional index. */
935         case 4: {
936                 int index, cache_type;
937
938                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
939                 /* read more entries until cache_type is zero */
940                 for (index = 1; *nent < maxnent; ++index) {
941                         cache_type = entry[index - 1].eax & 0x1f;
942                         if (!cache_type)
943                                 break;
944                         do_cpuid_1_ent(&entry[index], function, index);
945                         entry[index].flags |=
946                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
947                         ++*nent;
948                 }
949                 break;
950         }
951         case 0xb: {
952                 int index, level_type;
953
954                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
955                 /* read more entries until level_type is zero */
956                 for (index = 1; *nent < maxnent; ++index) {
957                         level_type = entry[index - 1].ecx & 0xff;
958                         if (!level_type)
959                                 break;
960                         do_cpuid_1_ent(&entry[index], function, index);
961                         entry[index].flags |=
962                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
963                         ++*nent;
964                 }
965                 break;
966         }
967         case 0x80000000:
968                 entry->eax = min(entry->eax, 0x8000001a);
969                 break;
970         case 0x80000001:
971                 entry->edx &= kvm_supported_word1_x86_features;
972                 entry->ecx &= kvm_supported_word6_x86_features;
973                 break;
974         }
975         put_cpu();
976 }
977
978 static int kvm_vm_ioctl_get_supported_cpuid(struct kvm *kvm,
979                                     struct kvm_cpuid2 *cpuid,
980                                     struct kvm_cpuid_entry2 __user *entries)
981 {
982         struct kvm_cpuid_entry2 *cpuid_entries;
983         int limit, nent = 0, r = -E2BIG;
984         u32 func;
985
986         if (cpuid->nent < 1)
987                 goto out;
988         r = -ENOMEM;
989         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry2) * cpuid->nent);
990         if (!cpuid_entries)
991                 goto out;
992
993         do_cpuid_ent(&cpuid_entries[0], 0, 0, &nent, cpuid->nent);
994         limit = cpuid_entries[0].eax;
995         for (func = 1; func <= limit && nent < cpuid->nent; ++func)
996                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
997                                 &nent, cpuid->nent);
998         r = -E2BIG;
999         if (nent >= cpuid->nent)
1000                 goto out_free;
1001
1002         do_cpuid_ent(&cpuid_entries[nent], 0x80000000, 0, &nent, cpuid->nent);
1003         limit = cpuid_entries[nent - 1].eax;
1004         for (func = 0x80000001; func <= limit && nent < cpuid->nent; ++func)
1005                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1006                                &nent, cpuid->nent);
1007         r = -EFAULT;
1008         if (copy_to_user(entries, cpuid_entries,
1009                         nent * sizeof(struct kvm_cpuid_entry2)))
1010                 goto out_free;
1011         cpuid->nent = nent;
1012         r = 0;
1013
1014 out_free:
1015         vfree(cpuid_entries);
1016 out:
1017         return r;
1018 }
1019
1020 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
1021                                     struct kvm_lapic_state *s)
1022 {
1023         vcpu_load(vcpu);
1024         memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
1025         vcpu_put(vcpu);
1026
1027         return 0;
1028 }
1029
1030 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
1031                                     struct kvm_lapic_state *s)
1032 {
1033         vcpu_load(vcpu);
1034         memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
1035         kvm_apic_post_state_restore(vcpu);
1036         vcpu_put(vcpu);
1037
1038         return 0;
1039 }
1040
1041 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
1042                                     struct kvm_interrupt *irq)
1043 {
1044         if (irq->irq < 0 || irq->irq >= 256)
1045                 return -EINVAL;
1046         if (irqchip_in_kernel(vcpu->kvm))
1047                 return -ENXIO;
1048         vcpu_load(vcpu);
1049
1050         set_bit(irq->irq, vcpu->arch.irq_pending);
1051         set_bit(irq->irq / BITS_PER_LONG, &vcpu->arch.irq_summary);
1052
1053         vcpu_put(vcpu);
1054
1055         return 0;
1056 }
1057
1058 long kvm_arch_vcpu_ioctl(struct file *filp,
1059                          unsigned int ioctl, unsigned long arg)
1060 {
1061         struct kvm_vcpu *vcpu = filp->private_data;
1062         void __user *argp = (void __user *)arg;
1063         int r;
1064
1065         switch (ioctl) {
1066         case KVM_GET_LAPIC: {
1067                 struct kvm_lapic_state lapic;
1068
1069                 memset(&lapic, 0, sizeof lapic);
1070                 r = kvm_vcpu_ioctl_get_lapic(vcpu, &lapic);
1071                 if (r)
1072                         goto out;
1073                 r = -EFAULT;
1074                 if (copy_to_user(argp, &lapic, sizeof lapic))
1075                         goto out;
1076                 r = 0;
1077                 break;
1078         }
1079         case KVM_SET_LAPIC: {
1080                 struct kvm_lapic_state lapic;
1081
1082                 r = -EFAULT;
1083                 if (copy_from_user(&lapic, argp, sizeof lapic))
1084                         goto out;
1085                 r = kvm_vcpu_ioctl_set_lapic(vcpu, &lapic);;
1086                 if (r)
1087                         goto out;
1088                 r = 0;
1089                 break;
1090         }
1091         case KVM_INTERRUPT: {
1092                 struct kvm_interrupt irq;
1093
1094                 r = -EFAULT;
1095                 if (copy_from_user(&irq, argp, sizeof irq))
1096                         goto out;
1097                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
1098                 if (r)
1099                         goto out;
1100                 r = 0;
1101                 break;
1102         }
1103         case KVM_SET_CPUID: {
1104                 struct kvm_cpuid __user *cpuid_arg = argp;
1105                 struct kvm_cpuid cpuid;
1106
1107                 r = -EFAULT;
1108                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1109                         goto out;
1110                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
1111                 if (r)
1112                         goto out;
1113                 break;
1114         }
1115         case KVM_SET_CPUID2: {
1116                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1117                 struct kvm_cpuid2 cpuid;
1118
1119                 r = -EFAULT;
1120                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1121                         goto out;
1122                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
1123                                 cpuid_arg->entries);
1124                 if (r)
1125                         goto out;
1126                 break;
1127         }
1128         case KVM_GET_CPUID2: {
1129                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1130                 struct kvm_cpuid2 cpuid;
1131
1132                 r = -EFAULT;
1133                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1134                         goto out;
1135                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
1136                                 cpuid_arg->entries);
1137                 if (r)
1138                         goto out;
1139                 r = -EFAULT;
1140                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1141                         goto out;
1142                 r = 0;
1143                 break;
1144         }
1145         case KVM_GET_MSRS:
1146                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
1147                 break;
1148         case KVM_SET_MSRS:
1149                 r = msr_io(vcpu, argp, do_set_msr, 0);
1150                 break;
1151         default:
1152                 r = -EINVAL;
1153         }
1154 out:
1155         return r;
1156 }
1157
1158 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
1159 {
1160         int ret;
1161
1162         if (addr > (unsigned int)(-3 * PAGE_SIZE))
1163                 return -1;
1164         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
1165         return ret;
1166 }
1167
1168 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
1169                                           u32 kvm_nr_mmu_pages)
1170 {
1171         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
1172                 return -EINVAL;
1173
1174         mutex_lock(&kvm->lock);
1175
1176         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
1177         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
1178
1179         mutex_unlock(&kvm->lock);
1180         return 0;
1181 }
1182
1183 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
1184 {
1185         return kvm->arch.n_alloc_mmu_pages;
1186 }
1187
1188 gfn_t unalias_gfn(struct kvm *kvm, gfn_t gfn)
1189 {
1190         int i;
1191         struct kvm_mem_alias *alias;
1192
1193         for (i = 0; i < kvm->arch.naliases; ++i) {
1194                 alias = &kvm->arch.aliases[i];
1195                 if (gfn >= alias->base_gfn
1196                     && gfn < alias->base_gfn + alias->npages)
1197                         return alias->target_gfn + gfn - alias->base_gfn;
1198         }
1199         return gfn;
1200 }
1201
1202 /*
1203  * Set a new alias region.  Aliases map a portion of physical memory into
1204  * another portion.  This is useful for memory windows, for example the PC
1205  * VGA region.
1206  */
1207 static int kvm_vm_ioctl_set_memory_alias(struct kvm *kvm,
1208                                          struct kvm_memory_alias *alias)
1209 {
1210         int r, n;
1211         struct kvm_mem_alias *p;
1212
1213         r = -EINVAL;
1214         /* General sanity checks */
1215         if (alias->memory_size & (PAGE_SIZE - 1))
1216                 goto out;
1217         if (alias->guest_phys_addr & (PAGE_SIZE - 1))
1218                 goto out;
1219         if (alias->slot >= KVM_ALIAS_SLOTS)
1220                 goto out;
1221         if (alias->guest_phys_addr + alias->memory_size
1222             < alias->guest_phys_addr)
1223                 goto out;
1224         if (alias->target_phys_addr + alias->memory_size
1225             < alias->target_phys_addr)
1226                 goto out;
1227
1228         mutex_lock(&kvm->lock);
1229
1230         p = &kvm->arch.aliases[alias->slot];
1231         p->base_gfn = alias->guest_phys_addr >> PAGE_SHIFT;
1232         p->npages = alias->memory_size >> PAGE_SHIFT;
1233         p->target_gfn = alias->target_phys_addr >> PAGE_SHIFT;
1234
1235         for (n = KVM_ALIAS_SLOTS; n > 0; --n)
1236                 if (kvm->arch.aliases[n - 1].npages)
1237                         break;
1238         kvm->arch.naliases = n;
1239
1240         kvm_mmu_zap_all(kvm);
1241
1242         mutex_unlock(&kvm->lock);
1243
1244         return 0;
1245
1246 out:
1247         return r;
1248 }
1249
1250 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1251 {
1252         int r;
1253
1254         r = 0;
1255         switch (chip->chip_id) {
1256         case KVM_IRQCHIP_PIC_MASTER:
1257                 memcpy(&chip->chip.pic,
1258                         &pic_irqchip(kvm)->pics[0],
1259                         sizeof(struct kvm_pic_state));
1260                 break;
1261         case KVM_IRQCHIP_PIC_SLAVE:
1262                 memcpy(&chip->chip.pic,
1263                         &pic_irqchip(kvm)->pics[1],
1264                         sizeof(struct kvm_pic_state));
1265                 break;
1266         case KVM_IRQCHIP_IOAPIC:
1267                 memcpy(&chip->chip.ioapic,
1268                         ioapic_irqchip(kvm),
1269                         sizeof(struct kvm_ioapic_state));
1270                 break;
1271         default:
1272                 r = -EINVAL;
1273                 break;
1274         }
1275         return r;
1276 }
1277
1278 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1279 {
1280         int r;
1281
1282         r = 0;
1283         switch (chip->chip_id) {
1284         case KVM_IRQCHIP_PIC_MASTER:
1285                 memcpy(&pic_irqchip(kvm)->pics[0],
1286                         &chip->chip.pic,
1287                         sizeof(struct kvm_pic_state));
1288                 break;
1289         case KVM_IRQCHIP_PIC_SLAVE:
1290                 memcpy(&pic_irqchip(kvm)->pics[1],
1291                         &chip->chip.pic,
1292                         sizeof(struct kvm_pic_state));
1293                 break;
1294         case KVM_IRQCHIP_IOAPIC:
1295                 memcpy(ioapic_irqchip(kvm),
1296                         &chip->chip.ioapic,
1297                         sizeof(struct kvm_ioapic_state));
1298                 break;
1299         default:
1300                 r = -EINVAL;
1301                 break;
1302         }
1303         kvm_pic_update_irq(pic_irqchip(kvm));
1304         return r;
1305 }
1306
1307 /*
1308  * Get (and clear) the dirty memory log for a memory slot.
1309  */
1310 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1311                                       struct kvm_dirty_log *log)
1312 {
1313         int r;
1314         int n;
1315         struct kvm_memory_slot *memslot;
1316         int is_dirty = 0;
1317
1318         mutex_lock(&kvm->lock);
1319
1320         r = kvm_get_dirty_log(kvm, log, &is_dirty);
1321         if (r)
1322                 goto out;
1323
1324         /* If nothing is dirty, don't bother messing with page tables. */
1325         if (is_dirty) {
1326                 kvm_mmu_slot_remove_write_access(kvm, log->slot);
1327                 kvm_flush_remote_tlbs(kvm);
1328                 memslot = &kvm->memslots[log->slot];
1329                 n = ALIGN(memslot->npages, BITS_PER_LONG) / 8;
1330                 memset(memslot->dirty_bitmap, 0, n);
1331         }
1332         r = 0;
1333 out:
1334         mutex_unlock(&kvm->lock);
1335         return r;
1336 }
1337
1338 long kvm_arch_vm_ioctl(struct file *filp,
1339                        unsigned int ioctl, unsigned long arg)
1340 {
1341         struct kvm *kvm = filp->private_data;
1342         void __user *argp = (void __user *)arg;
1343         int r = -EINVAL;
1344
1345         switch (ioctl) {
1346         case KVM_SET_TSS_ADDR:
1347                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
1348                 if (r < 0)
1349                         goto out;
1350                 break;
1351         case KVM_SET_MEMORY_REGION: {
1352                 struct kvm_memory_region kvm_mem;
1353                 struct kvm_userspace_memory_region kvm_userspace_mem;
1354
1355                 r = -EFAULT;
1356                 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
1357                         goto out;
1358                 kvm_userspace_mem.slot = kvm_mem.slot;
1359                 kvm_userspace_mem.flags = kvm_mem.flags;
1360                 kvm_userspace_mem.guest_phys_addr = kvm_mem.guest_phys_addr;
1361                 kvm_userspace_mem.memory_size = kvm_mem.memory_size;
1362                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 0);
1363                 if (r)
1364                         goto out;
1365                 break;
1366         }
1367         case KVM_SET_NR_MMU_PAGES:
1368                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
1369                 if (r)
1370                         goto out;
1371                 break;
1372         case KVM_GET_NR_MMU_PAGES:
1373                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
1374                 break;
1375         case KVM_SET_MEMORY_ALIAS: {
1376                 struct kvm_memory_alias alias;
1377
1378                 r = -EFAULT;
1379                 if (copy_from_user(&alias, argp, sizeof alias))
1380                         goto out;
1381                 r = kvm_vm_ioctl_set_memory_alias(kvm, &alias);
1382                 if (r)
1383                         goto out;
1384                 break;
1385         }
1386         case KVM_CREATE_IRQCHIP:
1387                 r = -ENOMEM;
1388                 kvm->arch.vpic = kvm_create_pic(kvm);
1389                 if (kvm->arch.vpic) {
1390                         r = kvm_ioapic_init(kvm);
1391                         if (r) {
1392                                 kfree(kvm->arch.vpic);
1393                                 kvm->arch.vpic = NULL;
1394                                 goto out;
1395                         }
1396                 } else
1397                         goto out;
1398                 break;
1399         case KVM_IRQ_LINE: {
1400                 struct kvm_irq_level irq_event;
1401
1402                 r = -EFAULT;
1403                 if (copy_from_user(&irq_event, argp, sizeof irq_event))
1404                         goto out;
1405                 if (irqchip_in_kernel(kvm)) {
1406                         mutex_lock(&kvm->lock);
1407                         if (irq_event.irq < 16)
1408                                 kvm_pic_set_irq(pic_irqchip(kvm),
1409                                         irq_event.irq,
1410                                         irq_event.level);
1411                         kvm_ioapic_set_irq(kvm->arch.vioapic,
1412                                         irq_event.irq,
1413                                         irq_event.level);
1414                         mutex_unlock(&kvm->lock);
1415                         r = 0;
1416                 }
1417                 break;
1418         }
1419         case KVM_GET_IRQCHIP: {
1420                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1421                 struct kvm_irqchip chip;
1422
1423                 r = -EFAULT;
1424                 if (copy_from_user(&chip, argp, sizeof chip))
1425                         goto out;
1426                 r = -ENXIO;
1427                 if (!irqchip_in_kernel(kvm))
1428                         goto out;
1429                 r = kvm_vm_ioctl_get_irqchip(kvm, &chip);
1430                 if (r)
1431                         goto out;
1432                 r = -EFAULT;
1433                 if (copy_to_user(argp, &chip, sizeof chip))
1434                         goto out;
1435                 r = 0;
1436                 break;
1437         }
1438         case KVM_SET_IRQCHIP: {
1439                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1440                 struct kvm_irqchip chip;
1441
1442                 r = -EFAULT;
1443                 if (copy_from_user(&chip, argp, sizeof chip))
1444                         goto out;
1445                 r = -ENXIO;
1446                 if (!irqchip_in_kernel(kvm))
1447                         goto out;
1448                 r = kvm_vm_ioctl_set_irqchip(kvm, &chip);
1449                 if (r)
1450                         goto out;
1451                 r = 0;
1452                 break;
1453         }
1454         case KVM_GET_SUPPORTED_CPUID: {
1455                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1456                 struct kvm_cpuid2 cpuid;
1457
1458                 r = -EFAULT;
1459                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1460                         goto out;
1461                 r = kvm_vm_ioctl_get_supported_cpuid(kvm, &cpuid,
1462                         cpuid_arg->entries);
1463                 if (r)
1464                         goto out;
1465
1466                 r = -EFAULT;
1467                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1468                         goto out;
1469                 r = 0;
1470                 break;
1471         }
1472         default:
1473                 ;
1474         }
1475 out:
1476         return r;
1477 }
1478
1479 static void kvm_init_msr_list(void)
1480 {
1481         u32 dummy[2];
1482         unsigned i, j;
1483
1484         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
1485                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
1486                         continue;
1487                 if (j < i)
1488                         msrs_to_save[j] = msrs_to_save[i];
1489                 j++;
1490         }
1491         num_msrs_to_save = j;
1492 }
1493
1494 /*
1495  * Only apic need an MMIO device hook, so shortcut now..
1496  */
1497 static struct kvm_io_device *vcpu_find_pervcpu_dev(struct kvm_vcpu *vcpu,
1498                                                 gpa_t addr)
1499 {
1500         struct kvm_io_device *dev;
1501
1502         if (vcpu->arch.apic) {
1503                 dev = &vcpu->arch.apic->dev;
1504                 if (dev->in_range(dev, addr))
1505                         return dev;
1506         }
1507         return NULL;
1508 }
1509
1510
1511 static struct kvm_io_device *vcpu_find_mmio_dev(struct kvm_vcpu *vcpu,
1512                                                 gpa_t addr)
1513 {
1514         struct kvm_io_device *dev;
1515
1516         dev = vcpu_find_pervcpu_dev(vcpu, addr);
1517         if (dev == NULL)
1518                 dev = kvm_io_bus_find_dev(&vcpu->kvm->mmio_bus, addr);
1519         return dev;
1520 }
1521
1522 int emulator_read_std(unsigned long addr,
1523                              void *val,
1524                              unsigned int bytes,
1525                              struct kvm_vcpu *vcpu)
1526 {
1527         void *data = val;
1528
1529         while (bytes) {
1530                 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1531                 unsigned offset = addr & (PAGE_SIZE-1);
1532                 unsigned tocopy = min(bytes, (unsigned)PAGE_SIZE - offset);
1533                 int ret;
1534
1535                 if (gpa == UNMAPPED_GVA)
1536                         return X86EMUL_PROPAGATE_FAULT;
1537                 ret = kvm_read_guest(vcpu->kvm, gpa, data, tocopy);
1538                 if (ret < 0)
1539                         return X86EMUL_UNHANDLEABLE;
1540
1541                 bytes -= tocopy;
1542                 data += tocopy;
1543                 addr += tocopy;
1544         }
1545
1546         return X86EMUL_CONTINUE;
1547 }
1548 EXPORT_SYMBOL_GPL(emulator_read_std);
1549
1550 static int emulator_read_emulated(unsigned long addr,
1551                                   void *val,
1552                                   unsigned int bytes,
1553                                   struct kvm_vcpu *vcpu)
1554 {
1555         struct kvm_io_device *mmio_dev;
1556         gpa_t                 gpa;
1557
1558         if (vcpu->mmio_read_completed) {
1559                 memcpy(val, vcpu->mmio_data, bytes);
1560                 vcpu->mmio_read_completed = 0;
1561                 return X86EMUL_CONTINUE;
1562         }
1563
1564         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1565
1566         /* For APIC access vmexit */
1567         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1568                 goto mmio;
1569
1570         if (emulator_read_std(addr, val, bytes, vcpu)
1571                         == X86EMUL_CONTINUE)
1572                 return X86EMUL_CONTINUE;
1573         if (gpa == UNMAPPED_GVA)
1574                 return X86EMUL_PROPAGATE_FAULT;
1575
1576 mmio:
1577         /*
1578          * Is this MMIO handled locally?
1579          */
1580         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa);
1581         if (mmio_dev) {
1582                 kvm_iodevice_read(mmio_dev, gpa, bytes, val);
1583                 return X86EMUL_CONTINUE;
1584         }
1585
1586         vcpu->mmio_needed = 1;
1587         vcpu->mmio_phys_addr = gpa;
1588         vcpu->mmio_size = bytes;
1589         vcpu->mmio_is_write = 0;
1590
1591         return X86EMUL_UNHANDLEABLE;
1592 }
1593
1594 static int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
1595                                const void *val, int bytes)
1596 {
1597         int ret;
1598
1599         ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
1600         if (ret < 0)
1601                 return 0;
1602         kvm_mmu_pte_write(vcpu, gpa, val, bytes);
1603         return 1;
1604 }
1605
1606 static int emulator_write_emulated_onepage(unsigned long addr,
1607                                            const void *val,
1608                                            unsigned int bytes,
1609                                            struct kvm_vcpu *vcpu)
1610 {
1611         struct kvm_io_device *mmio_dev;
1612         gpa_t                 gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1613
1614         if (gpa == UNMAPPED_GVA) {
1615                 kvm_inject_page_fault(vcpu, addr, 2);
1616                 return X86EMUL_PROPAGATE_FAULT;
1617         }
1618
1619         /* For APIC access vmexit */
1620         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1621                 goto mmio;
1622
1623         if (emulator_write_phys(vcpu, gpa, val, bytes))
1624                 return X86EMUL_CONTINUE;
1625
1626 mmio:
1627         /*
1628          * Is this MMIO handled locally?
1629          */
1630         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa);
1631         if (mmio_dev) {
1632                 kvm_iodevice_write(mmio_dev, gpa, bytes, val);
1633                 return X86EMUL_CONTINUE;
1634         }
1635
1636         vcpu->mmio_needed = 1;
1637         vcpu->mmio_phys_addr = gpa;
1638         vcpu->mmio_size = bytes;
1639         vcpu->mmio_is_write = 1;
1640         memcpy(vcpu->mmio_data, val, bytes);
1641
1642         return X86EMUL_CONTINUE;
1643 }
1644
1645 int emulator_write_emulated(unsigned long addr,
1646                                    const void *val,
1647                                    unsigned int bytes,
1648                                    struct kvm_vcpu *vcpu)
1649 {
1650         /* Crossing a page boundary? */
1651         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
1652                 int rc, now;
1653
1654                 now = -addr & ~PAGE_MASK;
1655                 rc = emulator_write_emulated_onepage(addr, val, now, vcpu);
1656                 if (rc != X86EMUL_CONTINUE)
1657                         return rc;
1658                 addr += now;
1659                 val += now;
1660                 bytes -= now;
1661         }
1662         return emulator_write_emulated_onepage(addr, val, bytes, vcpu);
1663 }
1664 EXPORT_SYMBOL_GPL(emulator_write_emulated);
1665
1666 static int emulator_cmpxchg_emulated(unsigned long addr,
1667                                      const void *old,
1668                                      const void *new,
1669                                      unsigned int bytes,
1670                                      struct kvm_vcpu *vcpu)
1671 {
1672         static int reported;
1673
1674         if (!reported) {
1675                 reported = 1;
1676                 printk(KERN_WARNING "kvm: emulating exchange as write\n");
1677         }
1678 #ifndef CONFIG_X86_64
1679         /* guests cmpxchg8b have to be emulated atomically */
1680         if (bytes == 8) {
1681                 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1682                 struct page *page;
1683                 char *addr;
1684                 u64 val;
1685
1686                 if (gpa == UNMAPPED_GVA ||
1687                    (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1688                         goto emul_write;
1689
1690                 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
1691                         goto emul_write;
1692
1693                 val = *(u64 *)new;
1694                 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
1695                 addr = kmap_atomic(page, KM_USER0);
1696                 set_64bit((u64 *)(addr + offset_in_page(gpa)), val);
1697                 kunmap_atomic(addr, KM_USER0);
1698                 kvm_release_page_dirty(page);
1699         }
1700 emul_write:
1701 #endif
1702
1703         return emulator_write_emulated(addr, new, bytes, vcpu);
1704 }
1705
1706 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
1707 {
1708         return kvm_x86_ops->get_segment_base(vcpu, seg);
1709 }
1710
1711 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
1712 {
1713         return X86EMUL_CONTINUE;
1714 }
1715
1716 int emulate_clts(struct kvm_vcpu *vcpu)
1717 {
1718         kvm_x86_ops->set_cr0(vcpu, vcpu->arch.cr0 & ~X86_CR0_TS);
1719         return X86EMUL_CONTINUE;
1720 }
1721
1722 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
1723 {
1724         struct kvm_vcpu *vcpu = ctxt->vcpu;
1725
1726         switch (dr) {
1727         case 0 ... 3:
1728                 *dest = kvm_x86_ops->get_dr(vcpu, dr);
1729                 return X86EMUL_CONTINUE;
1730         default:
1731                 pr_unimpl(vcpu, "%s: unexpected dr %u\n", __FUNCTION__, dr);
1732                 return X86EMUL_UNHANDLEABLE;
1733         }
1734 }
1735
1736 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
1737 {
1738         unsigned long mask = (ctxt->mode == X86EMUL_MODE_PROT64) ? ~0ULL : ~0U;
1739         int exception;
1740
1741         kvm_x86_ops->set_dr(ctxt->vcpu, dr, value & mask, &exception);
1742         if (exception) {
1743                 /* FIXME: better handling */
1744                 return X86EMUL_UNHANDLEABLE;
1745         }
1746         return X86EMUL_CONTINUE;
1747 }
1748
1749 void kvm_report_emulation_failure(struct kvm_vcpu *vcpu, const char *context)
1750 {
1751         static int reported;
1752         u8 opcodes[4];
1753         unsigned long rip = vcpu->arch.rip;
1754         unsigned long rip_linear;
1755
1756         rip_linear = rip + get_segment_base(vcpu, VCPU_SREG_CS);
1757
1758         if (reported)
1759                 return;
1760
1761         emulator_read_std(rip_linear, (void *)opcodes, 4, vcpu);
1762
1763         printk(KERN_ERR "emulation failed (%s) rip %lx %02x %02x %02x %02x\n",
1764                context, rip, opcodes[0], opcodes[1], opcodes[2], opcodes[3]);
1765         reported = 1;
1766 }
1767 EXPORT_SYMBOL_GPL(kvm_report_emulation_failure);
1768
1769 struct x86_emulate_ops emulate_ops = {
1770         .read_std            = emulator_read_std,
1771         .read_emulated       = emulator_read_emulated,
1772         .write_emulated      = emulator_write_emulated,
1773         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
1774 };
1775
1776 int emulate_instruction(struct kvm_vcpu *vcpu,
1777                         struct kvm_run *run,
1778                         unsigned long cr2,
1779                         u16 error_code,
1780                         int no_decode)
1781 {
1782         int r;
1783
1784         vcpu->arch.mmio_fault_cr2 = cr2;
1785         kvm_x86_ops->cache_regs(vcpu);
1786
1787         vcpu->mmio_is_write = 0;
1788         vcpu->arch.pio.string = 0;
1789
1790         if (!no_decode) {
1791                 int cs_db, cs_l;
1792                 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
1793
1794                 vcpu->arch.emulate_ctxt.vcpu = vcpu;
1795                 vcpu->arch.emulate_ctxt.eflags = kvm_x86_ops->get_rflags(vcpu);
1796                 vcpu->arch.emulate_ctxt.mode =
1797                         (vcpu->arch.emulate_ctxt.eflags & X86_EFLAGS_VM)
1798                         ? X86EMUL_MODE_REAL : cs_l
1799                         ? X86EMUL_MODE_PROT64 : cs_db
1800                         ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
1801
1802                 if (vcpu->arch.emulate_ctxt.mode == X86EMUL_MODE_PROT64) {
1803                         vcpu->arch.emulate_ctxt.cs_base = 0;
1804                         vcpu->arch.emulate_ctxt.ds_base = 0;
1805                         vcpu->arch.emulate_ctxt.es_base = 0;
1806                         vcpu->arch.emulate_ctxt.ss_base = 0;
1807                 } else {
1808                         vcpu->arch.emulate_ctxt.cs_base =
1809                                         get_segment_base(vcpu, VCPU_SREG_CS);
1810                         vcpu->arch.emulate_ctxt.ds_base =
1811                                         get_segment_base(vcpu, VCPU_SREG_DS);
1812                         vcpu->arch.emulate_ctxt.es_base =
1813                                         get_segment_base(vcpu, VCPU_SREG_ES);
1814                         vcpu->arch.emulate_ctxt.ss_base =
1815                                         get_segment_base(vcpu, VCPU_SREG_SS);
1816                 }
1817
1818                 vcpu->arch.emulate_ctxt.gs_base =
1819                                         get_segment_base(vcpu, VCPU_SREG_GS);
1820                 vcpu->arch.emulate_ctxt.fs_base =
1821                                         get_segment_base(vcpu, VCPU_SREG_FS);
1822
1823                 r = x86_decode_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
1824                 ++vcpu->stat.insn_emulation;
1825                 if (r)  {
1826                         ++vcpu->stat.insn_emulation_fail;
1827                         if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
1828                                 return EMULATE_DONE;
1829                         return EMULATE_FAIL;
1830                 }
1831         }
1832
1833         r = x86_emulate_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
1834
1835         if (vcpu->arch.pio.string)
1836                 return EMULATE_DO_MMIO;
1837
1838         if ((r || vcpu->mmio_is_write) && run) {
1839                 run->exit_reason = KVM_EXIT_MMIO;
1840                 run->mmio.phys_addr = vcpu->mmio_phys_addr;
1841                 memcpy(run->mmio.data, vcpu->mmio_data, 8);
1842                 run->mmio.len = vcpu->mmio_size;
1843                 run->mmio.is_write = vcpu->mmio_is_write;
1844         }
1845
1846         if (r) {
1847                 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
1848                         return EMULATE_DONE;
1849                 if (!vcpu->mmio_needed) {
1850                         kvm_report_emulation_failure(vcpu, "mmio");
1851                         return EMULATE_FAIL;
1852                 }
1853                 return EMULATE_DO_MMIO;
1854         }
1855
1856         kvm_x86_ops->decache_regs(vcpu);
1857         kvm_x86_ops->set_rflags(vcpu, vcpu->arch.emulate_ctxt.eflags);
1858
1859         if (vcpu->mmio_is_write) {
1860                 vcpu->mmio_needed = 0;
1861                 return EMULATE_DO_MMIO;
1862         }
1863
1864         return EMULATE_DONE;
1865 }
1866 EXPORT_SYMBOL_GPL(emulate_instruction);
1867
1868 static void free_pio_guest_pages(struct kvm_vcpu *vcpu)
1869 {
1870         int i;
1871
1872         for (i = 0; i < ARRAY_SIZE(vcpu->arch.pio.guest_pages); ++i)
1873                 if (vcpu->arch.pio.guest_pages[i]) {
1874                         kvm_release_page_dirty(vcpu->arch.pio.guest_pages[i]);
1875                         vcpu->arch.pio.guest_pages[i] = NULL;
1876                 }
1877 }
1878
1879 static int pio_copy_data(struct kvm_vcpu *vcpu)
1880 {
1881         void *p = vcpu->arch.pio_data;
1882         void *q;
1883         unsigned bytes;
1884         int nr_pages = vcpu->arch.pio.guest_pages[1] ? 2 : 1;
1885
1886         q = vmap(vcpu->arch.pio.guest_pages, nr_pages, VM_READ|VM_WRITE,
1887                  PAGE_KERNEL);
1888         if (!q) {
1889                 free_pio_guest_pages(vcpu);
1890                 return -ENOMEM;
1891         }
1892         q += vcpu->arch.pio.guest_page_offset;
1893         bytes = vcpu->arch.pio.size * vcpu->arch.pio.cur_count;
1894         if (vcpu->arch.pio.in)
1895                 memcpy(q, p, bytes);
1896         else
1897                 memcpy(p, q, bytes);
1898         q -= vcpu->arch.pio.guest_page_offset;
1899         vunmap(q);
1900         free_pio_guest_pages(vcpu);
1901         return 0;
1902 }
1903
1904 int complete_pio(struct kvm_vcpu *vcpu)
1905 {
1906         struct kvm_pio_request *io = &vcpu->arch.pio;
1907         long delta;
1908         int r;
1909
1910         kvm_x86_ops->cache_regs(vcpu);
1911
1912         if (!io->string) {
1913                 if (io->in)
1914                         memcpy(&vcpu->arch.regs[VCPU_REGS_RAX], vcpu->arch.pio_data,
1915                                io->size);
1916         } else {
1917                 if (io->in) {
1918                         r = pio_copy_data(vcpu);
1919                         if (r) {
1920                                 kvm_x86_ops->cache_regs(vcpu);
1921                                 return r;
1922                         }
1923                 }
1924
1925                 delta = 1;
1926                 if (io->rep) {
1927                         delta *= io->cur_count;
1928                         /*
1929                          * The size of the register should really depend on
1930                          * current address size.
1931                          */
1932                         vcpu->arch.regs[VCPU_REGS_RCX] -= delta;
1933                 }
1934                 if (io->down)
1935                         delta = -delta;
1936                 delta *= io->size;
1937                 if (io->in)
1938                         vcpu->arch.regs[VCPU_REGS_RDI] += delta;
1939                 else
1940                         vcpu->arch.regs[VCPU_REGS_RSI] += delta;
1941         }
1942
1943         kvm_x86_ops->decache_regs(vcpu);
1944
1945         io->count -= io->cur_count;
1946         io->cur_count = 0;
1947
1948         return 0;
1949 }
1950
1951 static void kernel_pio(struct kvm_io_device *pio_dev,
1952                        struct kvm_vcpu *vcpu,
1953                        void *pd)
1954 {
1955         /* TODO: String I/O for in kernel device */
1956
1957         mutex_lock(&vcpu->kvm->lock);
1958         if (vcpu->arch.pio.in)
1959                 kvm_iodevice_read(pio_dev, vcpu->arch.pio.port,
1960                                   vcpu->arch.pio.size,
1961                                   pd);
1962         else
1963                 kvm_iodevice_write(pio_dev, vcpu->arch.pio.port,
1964                                    vcpu->arch.pio.size,
1965                                    pd);
1966         mutex_unlock(&vcpu->kvm->lock);
1967 }
1968
1969 static void pio_string_write(struct kvm_io_device *pio_dev,
1970                              struct kvm_vcpu *vcpu)
1971 {
1972         struct kvm_pio_request *io = &vcpu->arch.pio;
1973         void *pd = vcpu->arch.pio_data;
1974         int i;
1975
1976         mutex_lock(&vcpu->kvm->lock);
1977         for (i = 0; i < io->cur_count; i++) {
1978                 kvm_iodevice_write(pio_dev, io->port,
1979                                    io->size,
1980                                    pd);
1981                 pd += io->size;
1982         }
1983         mutex_unlock(&vcpu->kvm->lock);
1984 }
1985
1986 static struct kvm_io_device *vcpu_find_pio_dev(struct kvm_vcpu *vcpu,
1987                                                gpa_t addr)
1988 {
1989         return kvm_io_bus_find_dev(&vcpu->kvm->pio_bus, addr);
1990 }
1991
1992 int kvm_emulate_pio(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
1993                   int size, unsigned port)
1994 {
1995         struct kvm_io_device *pio_dev;
1996
1997         vcpu->run->exit_reason = KVM_EXIT_IO;
1998         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
1999         vcpu->run->io.size = vcpu->arch.pio.size = size;
2000         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2001         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = 1;
2002         vcpu->run->io.port = vcpu->arch.pio.port = port;
2003         vcpu->arch.pio.in = in;
2004         vcpu->arch.pio.string = 0;
2005         vcpu->arch.pio.down = 0;
2006         vcpu->arch.pio.guest_page_offset = 0;
2007         vcpu->arch.pio.rep = 0;
2008
2009         kvm_x86_ops->cache_regs(vcpu);
2010         memcpy(vcpu->arch.pio_data, &vcpu->arch.regs[VCPU_REGS_RAX], 4);
2011         kvm_x86_ops->decache_regs(vcpu);
2012
2013         kvm_x86_ops->skip_emulated_instruction(vcpu);
2014
2015         pio_dev = vcpu_find_pio_dev(vcpu, port);
2016         if (pio_dev) {
2017                 kernel_pio(pio_dev, vcpu, vcpu->arch.pio_data);
2018                 complete_pio(vcpu);
2019                 return 1;
2020         }
2021         return 0;
2022 }
2023 EXPORT_SYMBOL_GPL(kvm_emulate_pio);
2024
2025 int kvm_emulate_pio_string(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
2026                   int size, unsigned long count, int down,
2027                   gva_t address, int rep, unsigned port)
2028 {
2029         unsigned now, in_page;
2030         int i, ret = 0;
2031         int nr_pages = 1;
2032         struct page *page;
2033         struct kvm_io_device *pio_dev;
2034
2035         vcpu->run->exit_reason = KVM_EXIT_IO;
2036         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2037         vcpu->run->io.size = vcpu->arch.pio.size = size;
2038         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2039         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = count;
2040         vcpu->run->io.port = vcpu->arch.pio.port = port;
2041         vcpu->arch.pio.in = in;
2042         vcpu->arch.pio.string = 1;
2043         vcpu->arch.pio.down = down;
2044         vcpu->arch.pio.guest_page_offset = offset_in_page(address);
2045         vcpu->arch.pio.rep = rep;
2046
2047         if (!count) {
2048                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2049                 return 1;
2050         }
2051
2052         if (!down)
2053                 in_page = PAGE_SIZE - offset_in_page(address);
2054         else
2055                 in_page = offset_in_page(address) + size;
2056         now = min(count, (unsigned long)in_page / size);
2057         if (!now) {
2058                 /*
2059                  * String I/O straddles page boundary.  Pin two guest pages
2060                  * so that we satisfy atomicity constraints.  Do just one
2061                  * transaction to avoid complexity.
2062                  */
2063                 nr_pages = 2;
2064                 now = 1;
2065         }
2066         if (down) {
2067                 /*
2068                  * String I/O in reverse.  Yuck.  Kill the guest, fix later.
2069                  */
2070                 pr_unimpl(vcpu, "guest string pio down\n");
2071                 kvm_inject_gp(vcpu, 0);
2072                 return 1;
2073         }
2074         vcpu->run->io.count = now;
2075         vcpu->arch.pio.cur_count = now;
2076
2077         if (vcpu->arch.pio.cur_count == vcpu->arch.pio.count)
2078                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2079
2080         for (i = 0; i < nr_pages; ++i) {
2081                 mutex_lock(&vcpu->kvm->lock);
2082                 page = gva_to_page(vcpu, address + i * PAGE_SIZE);
2083                 vcpu->arch.pio.guest_pages[i] = page;
2084                 mutex_unlock(&vcpu->kvm->lock);
2085                 if (!page) {
2086                         kvm_inject_gp(vcpu, 0);
2087                         free_pio_guest_pages(vcpu);
2088                         return 1;
2089                 }
2090         }
2091
2092         pio_dev = vcpu_find_pio_dev(vcpu, port);
2093         if (!vcpu->arch.pio.in) {
2094                 /* string PIO write */
2095                 ret = pio_copy_data(vcpu);
2096                 if (ret >= 0 && pio_dev) {
2097                         pio_string_write(pio_dev, vcpu);
2098                         complete_pio(vcpu);
2099                         if (vcpu->arch.pio.count == 0)
2100                                 ret = 1;
2101                 }
2102         } else if (pio_dev)
2103                 pr_unimpl(vcpu, "no string pio read support yet, "
2104                        "port %x size %d count %ld\n",
2105                         port, size, count);
2106
2107         return ret;
2108 }
2109 EXPORT_SYMBOL_GPL(kvm_emulate_pio_string);
2110
2111 int kvm_arch_init(void *opaque)
2112 {
2113         int r;
2114         struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
2115
2116         r = kvm_mmu_module_init();
2117         if (r)
2118                 goto out_fail;
2119
2120         kvm_init_msr_list();
2121
2122         if (kvm_x86_ops) {
2123                 printk(KERN_ERR "kvm: already loaded the other module\n");
2124                 r = -EEXIST;
2125                 goto out;
2126         }
2127
2128         if (!ops->cpu_has_kvm_support()) {
2129                 printk(KERN_ERR "kvm: no hardware support\n");
2130                 r = -EOPNOTSUPP;
2131                 goto out;
2132         }
2133         if (ops->disabled_by_bios()) {
2134                 printk(KERN_ERR "kvm: disabled by bios\n");
2135                 r = -EOPNOTSUPP;
2136                 goto out;
2137         }
2138
2139         kvm_x86_ops = ops;
2140         kvm_mmu_set_nonpresent_ptes(0ull, 0ull);
2141         return 0;
2142
2143 out:
2144         kvm_mmu_module_exit();
2145 out_fail:
2146         return r;
2147 }
2148
2149 void kvm_arch_exit(void)
2150 {
2151         kvm_x86_ops = NULL;
2152         kvm_mmu_module_exit();
2153 }
2154
2155 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
2156 {
2157         ++vcpu->stat.halt_exits;
2158         if (irqchip_in_kernel(vcpu->kvm)) {
2159                 vcpu->arch.mp_state = VCPU_MP_STATE_HALTED;
2160                 kvm_vcpu_block(vcpu);
2161                 if (vcpu->arch.mp_state != VCPU_MP_STATE_RUNNABLE)
2162                         return -EINTR;
2163                 return 1;
2164         } else {
2165                 vcpu->run->exit_reason = KVM_EXIT_HLT;
2166                 return 0;
2167         }
2168 }
2169 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
2170
2171 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
2172 {
2173         unsigned long nr, a0, a1, a2, a3, ret;
2174
2175         kvm_x86_ops->cache_regs(vcpu);
2176
2177         nr = vcpu->arch.regs[VCPU_REGS_RAX];
2178         a0 = vcpu->arch.regs[VCPU_REGS_RBX];
2179         a1 = vcpu->arch.regs[VCPU_REGS_RCX];
2180         a2 = vcpu->arch.regs[VCPU_REGS_RDX];
2181         a3 = vcpu->arch.regs[VCPU_REGS_RSI];
2182
2183         if (!is_long_mode(vcpu)) {
2184                 nr &= 0xFFFFFFFF;
2185                 a0 &= 0xFFFFFFFF;
2186                 a1 &= 0xFFFFFFFF;
2187                 a2 &= 0xFFFFFFFF;
2188                 a3 &= 0xFFFFFFFF;
2189         }
2190
2191         switch (nr) {
2192         default:
2193                 ret = -KVM_ENOSYS;
2194                 break;
2195         }
2196         vcpu->arch.regs[VCPU_REGS_RAX] = ret;
2197         kvm_x86_ops->decache_regs(vcpu);
2198         return 0;
2199 }
2200 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
2201
2202 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
2203 {
2204         char instruction[3];
2205         int ret = 0;
2206
2207         mutex_lock(&vcpu->kvm->lock);
2208
2209         /*
2210          * Blow out the MMU to ensure that no other VCPU has an active mapping
2211          * to ensure that the updated hypercall appears atomically across all
2212          * VCPUs.
2213          */
2214         kvm_mmu_zap_all(vcpu->kvm);
2215
2216         kvm_x86_ops->cache_regs(vcpu);
2217         kvm_x86_ops->patch_hypercall(vcpu, instruction);
2218         if (emulator_write_emulated(vcpu->arch.rip, instruction, 3, vcpu)
2219             != X86EMUL_CONTINUE)
2220                 ret = -EFAULT;
2221
2222         mutex_unlock(&vcpu->kvm->lock);
2223
2224         return ret;
2225 }
2226
2227 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
2228 {
2229         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
2230 }
2231
2232 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2233 {
2234         struct descriptor_table dt = { limit, base };
2235
2236         kvm_x86_ops->set_gdt(vcpu, &dt);
2237 }
2238
2239 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2240 {
2241         struct descriptor_table dt = { limit, base };
2242
2243         kvm_x86_ops->set_idt(vcpu, &dt);
2244 }
2245
2246 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
2247                    unsigned long *rflags)
2248 {
2249         lmsw(vcpu, msw);
2250         *rflags = kvm_x86_ops->get_rflags(vcpu);
2251 }
2252
2253 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
2254 {
2255         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2256         switch (cr) {
2257         case 0:
2258                 return vcpu->arch.cr0;
2259         case 2:
2260                 return vcpu->arch.cr2;
2261         case 3:
2262                 return vcpu->arch.cr3;
2263         case 4:
2264                 return vcpu->arch.cr4;
2265         case 8:
2266                 return get_cr8(vcpu);
2267         default:
2268                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __FUNCTION__, cr);
2269                 return 0;
2270         }
2271 }
2272
2273 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
2274                      unsigned long *rflags)
2275 {
2276         switch (cr) {
2277         case 0:
2278                 set_cr0(vcpu, mk_cr_64(vcpu->arch.cr0, val));
2279                 *rflags = kvm_x86_ops->get_rflags(vcpu);
2280                 break;
2281         case 2:
2282                 vcpu->arch.cr2 = val;
2283                 break;
2284         case 3:
2285                 set_cr3(vcpu, val);
2286                 break;
2287         case 4:
2288                 set_cr4(vcpu, mk_cr_64(vcpu->arch.cr4, val));
2289                 break;
2290         case 8:
2291                 set_cr8(vcpu, val & 0xfUL);
2292                 break;
2293         default:
2294                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __FUNCTION__, cr);
2295         }
2296 }
2297
2298 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
2299 {
2300         struct kvm_cpuid_entry2 *e = &vcpu->arch.cpuid_entries[i];
2301         int j, nent = vcpu->arch.cpuid_nent;
2302
2303         e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
2304         /* when no next entry is found, the current entry[i] is reselected */
2305         for (j = i + 1; j == i; j = (j + 1) % nent) {
2306                 struct kvm_cpuid_entry2 *ej = &vcpu->arch.cpuid_entries[j];
2307                 if (ej->function == e->function) {
2308                         ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
2309                         return j;
2310                 }
2311         }
2312         return 0; /* silence gcc, even though control never reaches here */
2313 }
2314
2315 /* find an entry with matching function, matching index (if needed), and that
2316  * should be read next (if it's stateful) */
2317 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
2318         u32 function, u32 index)
2319 {
2320         if (e->function != function)
2321                 return 0;
2322         if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
2323                 return 0;
2324         if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
2325                 !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
2326                 return 0;
2327         return 1;
2328 }
2329
2330 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
2331 {
2332         int i;
2333         u32 function, index;
2334         struct kvm_cpuid_entry2 *e, *best;
2335
2336         kvm_x86_ops->cache_regs(vcpu);
2337         function = vcpu->arch.regs[VCPU_REGS_RAX];
2338         index = vcpu->arch.regs[VCPU_REGS_RCX];
2339         vcpu->arch.regs[VCPU_REGS_RAX] = 0;
2340         vcpu->arch.regs[VCPU_REGS_RBX] = 0;
2341         vcpu->arch.regs[VCPU_REGS_RCX] = 0;
2342         vcpu->arch.regs[VCPU_REGS_RDX] = 0;
2343         best = NULL;
2344         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
2345                 e = &vcpu->arch.cpuid_entries[i];
2346                 if (is_matching_cpuid_entry(e, function, index)) {
2347                         if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
2348                                 move_to_next_stateful_cpuid_entry(vcpu, i);
2349                         best = e;
2350                         break;
2351                 }
2352                 /*
2353                  * Both basic or both extended?
2354                  */
2355                 if (((e->function ^ function) & 0x80000000) == 0)
2356                         if (!best || e->function > best->function)
2357                                 best = e;
2358         }
2359         if (best) {
2360                 vcpu->arch.regs[VCPU_REGS_RAX] = best->eax;
2361                 vcpu->arch.regs[VCPU_REGS_RBX] = best->ebx;
2362                 vcpu->arch.regs[VCPU_REGS_RCX] = best->ecx;
2363                 vcpu->arch.regs[VCPU_REGS_RDX] = best->edx;
2364         }
2365         kvm_x86_ops->decache_regs(vcpu);
2366         kvm_x86_ops->skip_emulated_instruction(vcpu);
2367 }
2368 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
2369
2370 /*
2371  * Check if userspace requested an interrupt window, and that the
2372  * interrupt window is open.
2373  *
2374  * No need to exit to userspace if we already have an interrupt queued.
2375  */
2376 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu,
2377                                           struct kvm_run *kvm_run)
2378 {
2379         return (!vcpu->arch.irq_summary &&
2380                 kvm_run->request_interrupt_window &&
2381                 vcpu->arch.interrupt_window_open &&
2382                 (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF));
2383 }
2384
2385 static void post_kvm_run_save(struct kvm_vcpu *vcpu,
2386                               struct kvm_run *kvm_run)
2387 {
2388         kvm_run->if_flag = (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
2389         kvm_run->cr8 = get_cr8(vcpu);
2390         kvm_run->apic_base = kvm_get_apic_base(vcpu);
2391         if (irqchip_in_kernel(vcpu->kvm))
2392                 kvm_run->ready_for_interrupt_injection = 1;
2393         else
2394                 kvm_run->ready_for_interrupt_injection =
2395                                         (vcpu->arch.interrupt_window_open &&
2396                                          vcpu->arch.irq_summary == 0);
2397 }
2398
2399 static int __vcpu_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2400 {
2401         int r;
2402
2403         if (unlikely(vcpu->arch.mp_state == VCPU_MP_STATE_SIPI_RECEIVED)) {
2404                 pr_debug("vcpu %d received sipi with vector # %x\n",
2405                        vcpu->vcpu_id, vcpu->arch.sipi_vector);
2406                 kvm_lapic_reset(vcpu);
2407                 r = kvm_x86_ops->vcpu_reset(vcpu);
2408                 if (r)
2409                         return r;
2410                 vcpu->arch.mp_state = VCPU_MP_STATE_RUNNABLE;
2411         }
2412
2413 preempted:
2414         if (vcpu->guest_debug.enabled)
2415                 kvm_x86_ops->guest_debug_pre(vcpu);
2416
2417 again:
2418         r = kvm_mmu_reload(vcpu);
2419         if (unlikely(r))
2420                 goto out;
2421
2422         kvm_inject_pending_timer_irqs(vcpu);
2423
2424         preempt_disable();
2425
2426         kvm_x86_ops->prepare_guest_switch(vcpu);
2427         kvm_load_guest_fpu(vcpu);
2428
2429         local_irq_disable();
2430
2431         if (signal_pending(current)) {
2432                 local_irq_enable();
2433                 preempt_enable();
2434                 r = -EINTR;
2435                 kvm_run->exit_reason = KVM_EXIT_INTR;
2436                 ++vcpu->stat.signal_exits;
2437                 goto out;
2438         }
2439
2440         if (vcpu->arch.exception.pending)
2441                 __queue_exception(vcpu);
2442         else if (irqchip_in_kernel(vcpu->kvm))
2443                 kvm_x86_ops->inject_pending_irq(vcpu);
2444         else
2445                 kvm_x86_ops->inject_pending_vectors(vcpu, kvm_run);
2446
2447         vcpu->guest_mode = 1;
2448         kvm_guest_enter();
2449
2450         if (vcpu->requests)
2451                 if (test_and_clear_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
2452                         kvm_x86_ops->tlb_flush(vcpu);
2453
2454         kvm_x86_ops->run(vcpu, kvm_run);
2455
2456         vcpu->guest_mode = 0;
2457         local_irq_enable();
2458
2459         ++vcpu->stat.exits;
2460
2461         /*
2462          * We must have an instruction between local_irq_enable() and
2463          * kvm_guest_exit(), so the timer interrupt isn't delayed by
2464          * the interrupt shadow.  The stat.exits increment will do nicely.
2465          * But we need to prevent reordering, hence this barrier():
2466          */
2467         barrier();
2468
2469         kvm_guest_exit();
2470
2471         preempt_enable();
2472
2473         /*
2474          * Profile KVM exit RIPs:
2475          */
2476         if (unlikely(prof_on == KVM_PROFILING)) {
2477                 kvm_x86_ops->cache_regs(vcpu);
2478                 profile_hit(KVM_PROFILING, (void *)vcpu->arch.rip);
2479         }
2480
2481         if (vcpu->arch.exception.pending && kvm_x86_ops->exception_injected(vcpu))
2482                 vcpu->arch.exception.pending = false;
2483
2484         r = kvm_x86_ops->handle_exit(kvm_run, vcpu);
2485
2486         if (r > 0) {
2487                 if (dm_request_for_irq_injection(vcpu, kvm_run)) {
2488                         r = -EINTR;
2489                         kvm_run->exit_reason = KVM_EXIT_INTR;
2490                         ++vcpu->stat.request_irq_exits;
2491                         goto out;
2492                 }
2493                 if (!need_resched())
2494                         goto again;
2495         }
2496
2497 out:
2498         if (r > 0) {
2499                 kvm_resched(vcpu);
2500                 goto preempted;
2501         }
2502
2503         post_kvm_run_save(vcpu, kvm_run);
2504
2505         return r;
2506 }
2507
2508 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2509 {
2510         int r;
2511         sigset_t sigsaved;
2512
2513         vcpu_load(vcpu);
2514
2515         if (unlikely(vcpu->arch.mp_state == VCPU_MP_STATE_UNINITIALIZED)) {
2516                 kvm_vcpu_block(vcpu);
2517                 vcpu_put(vcpu);
2518                 return -EAGAIN;
2519         }
2520
2521         if (vcpu->sigset_active)
2522                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
2523
2524         /* re-sync apic's tpr */
2525         if (!irqchip_in_kernel(vcpu->kvm))
2526                 set_cr8(vcpu, kvm_run->cr8);
2527
2528         if (vcpu->arch.pio.cur_count) {
2529                 r = complete_pio(vcpu);
2530                 if (r)
2531                         goto out;
2532         }
2533 #if CONFIG_HAS_IOMEM
2534         if (vcpu->mmio_needed) {
2535                 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
2536                 vcpu->mmio_read_completed = 1;
2537                 vcpu->mmio_needed = 0;
2538                 r = emulate_instruction(vcpu, kvm_run,
2539                                         vcpu->arch.mmio_fault_cr2, 0, 1);
2540                 if (r == EMULATE_DO_MMIO) {
2541                         /*
2542                          * Read-modify-write.  Back to userspace.
2543                          */
2544                         r = 0;
2545                         goto out;
2546                 }
2547         }
2548 #endif
2549         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL) {
2550                 kvm_x86_ops->cache_regs(vcpu);
2551                 vcpu->arch.regs[VCPU_REGS_RAX] = kvm_run->hypercall.ret;
2552                 kvm_x86_ops->decache_regs(vcpu);
2553         }
2554
2555         r = __vcpu_run(vcpu, kvm_run);
2556
2557 out:
2558         if (vcpu->sigset_active)
2559                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
2560
2561         vcpu_put(vcpu);
2562         return r;
2563 }
2564
2565 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
2566 {
2567         vcpu_load(vcpu);
2568
2569         kvm_x86_ops->cache_regs(vcpu);
2570
2571         regs->rax = vcpu->arch.regs[VCPU_REGS_RAX];
2572         regs->rbx = vcpu->arch.regs[VCPU_REGS_RBX];
2573         regs->rcx = vcpu->arch.regs[VCPU_REGS_RCX];
2574         regs->rdx = vcpu->arch.regs[VCPU_REGS_RDX];
2575         regs->rsi = vcpu->arch.regs[VCPU_REGS_RSI];
2576         regs->rdi = vcpu->arch.regs[VCPU_REGS_RDI];
2577         regs->rsp = vcpu->arch.regs[VCPU_REGS_RSP];
2578         regs->rbp = vcpu->arch.regs[VCPU_REGS_RBP];
2579 #ifdef CONFIG_X86_64
2580         regs->r8 = vcpu->arch.regs[VCPU_REGS_R8];
2581         regs->r9 = vcpu->arch.regs[VCPU_REGS_R9];
2582         regs->r10 = vcpu->arch.regs[VCPU_REGS_R10];
2583         regs->r11 = vcpu->arch.regs[VCPU_REGS_R11];
2584         regs->r12 = vcpu->arch.regs[VCPU_REGS_R12];
2585         regs->r13 = vcpu->arch.regs[VCPU_REGS_R13];
2586         regs->r14 = vcpu->arch.regs[VCPU_REGS_R14];
2587         regs->r15 = vcpu->arch.regs[VCPU_REGS_R15];
2588 #endif
2589
2590         regs->rip = vcpu->arch.rip;
2591         regs->rflags = kvm_x86_ops->get_rflags(vcpu);
2592
2593         /*
2594          * Don't leak debug flags in case they were set for guest debugging
2595          */
2596         if (vcpu->guest_debug.enabled && vcpu->guest_debug.singlestep)
2597                 regs->rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
2598
2599         vcpu_put(vcpu);
2600
2601         return 0;
2602 }
2603
2604 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
2605 {
2606         vcpu_load(vcpu);
2607
2608         vcpu->arch.regs[VCPU_REGS_RAX] = regs->rax;
2609         vcpu->arch.regs[VCPU_REGS_RBX] = regs->rbx;
2610         vcpu->arch.regs[VCPU_REGS_RCX] = regs->rcx;
2611         vcpu->arch.regs[VCPU_REGS_RDX] = regs->rdx;
2612         vcpu->arch.regs[VCPU_REGS_RSI] = regs->rsi;
2613         vcpu->arch.regs[VCPU_REGS_RDI] = regs->rdi;
2614         vcpu->arch.regs[VCPU_REGS_RSP] = regs->rsp;
2615         vcpu->arch.regs[VCPU_REGS_RBP] = regs->rbp;
2616 #ifdef CONFIG_X86_64
2617         vcpu->arch.regs[VCPU_REGS_R8] = regs->r8;
2618         vcpu->arch.regs[VCPU_REGS_R9] = regs->r9;
2619         vcpu->arch.regs[VCPU_REGS_R10] = regs->r10;
2620         vcpu->arch.regs[VCPU_REGS_R11] = regs->r11;
2621         vcpu->arch.regs[VCPU_REGS_R12] = regs->r12;
2622         vcpu->arch.regs[VCPU_REGS_R13] = regs->r13;
2623         vcpu->arch.regs[VCPU_REGS_R14] = regs->r14;
2624         vcpu->arch.regs[VCPU_REGS_R15] = regs->r15;
2625 #endif
2626
2627         vcpu->arch.rip = regs->rip;
2628         kvm_x86_ops->set_rflags(vcpu, regs->rflags);
2629
2630         kvm_x86_ops->decache_regs(vcpu);
2631
2632         vcpu_put(vcpu);
2633
2634         return 0;
2635 }
2636
2637 static void get_segment(struct kvm_vcpu *vcpu,
2638                         struct kvm_segment *var, int seg)
2639 {
2640         return kvm_x86_ops->get_segment(vcpu, var, seg);
2641 }
2642
2643 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
2644 {
2645         struct kvm_segment cs;
2646
2647         get_segment(vcpu, &cs, VCPU_SREG_CS);
2648         *db = cs.db;
2649         *l = cs.l;
2650 }
2651 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
2652
2653 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
2654                                   struct kvm_sregs *sregs)
2655 {
2656         struct descriptor_table dt;
2657         int pending_vec;
2658
2659         vcpu_load(vcpu);
2660
2661         get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
2662         get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
2663         get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
2664         get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
2665         get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
2666         get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
2667
2668         get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
2669         get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
2670
2671         kvm_x86_ops->get_idt(vcpu, &dt);
2672         sregs->idt.limit = dt.limit;
2673         sregs->idt.base = dt.base;
2674         kvm_x86_ops->get_gdt(vcpu, &dt);
2675         sregs->gdt.limit = dt.limit;
2676         sregs->gdt.base = dt.base;
2677
2678         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2679         sregs->cr0 = vcpu->arch.cr0;
2680         sregs->cr2 = vcpu->arch.cr2;
2681         sregs->cr3 = vcpu->arch.cr3;
2682         sregs->cr4 = vcpu->arch.cr4;
2683         sregs->cr8 = get_cr8(vcpu);
2684         sregs->efer = vcpu->arch.shadow_efer;
2685         sregs->apic_base = kvm_get_apic_base(vcpu);
2686
2687         if (irqchip_in_kernel(vcpu->kvm)) {
2688                 memset(sregs->interrupt_bitmap, 0,
2689                        sizeof sregs->interrupt_bitmap);
2690                 pending_vec = kvm_x86_ops->get_irq(vcpu);
2691                 if (pending_vec >= 0)
2692                         set_bit(pending_vec,
2693                                 (unsigned long *)sregs->interrupt_bitmap);
2694         } else
2695                 memcpy(sregs->interrupt_bitmap, vcpu->arch.irq_pending,
2696                        sizeof sregs->interrupt_bitmap);
2697
2698         vcpu_put(vcpu);
2699
2700         return 0;
2701 }
2702
2703 static void set_segment(struct kvm_vcpu *vcpu,
2704                         struct kvm_segment *var, int seg)
2705 {
2706         return kvm_x86_ops->set_segment(vcpu, var, seg);
2707 }
2708
2709 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
2710                                   struct kvm_sregs *sregs)
2711 {
2712         int mmu_reset_needed = 0;
2713         int i, pending_vec, max_bits;
2714         struct descriptor_table dt;
2715
2716         vcpu_load(vcpu);
2717
2718         dt.limit = sregs->idt.limit;
2719         dt.base = sregs->idt.base;
2720         kvm_x86_ops->set_idt(vcpu, &dt);
2721         dt.limit = sregs->gdt.limit;
2722         dt.base = sregs->gdt.base;
2723         kvm_x86_ops->set_gdt(vcpu, &dt);
2724
2725         vcpu->arch.cr2 = sregs->cr2;
2726         mmu_reset_needed |= vcpu->arch.cr3 != sregs->cr3;
2727         vcpu->arch.cr3 = sregs->cr3;
2728
2729         set_cr8(vcpu, sregs->cr8);
2730
2731         mmu_reset_needed |= vcpu->arch.shadow_efer != sregs->efer;
2732 #ifdef CONFIG_X86_64
2733         kvm_x86_ops->set_efer(vcpu, sregs->efer);
2734 #endif
2735         kvm_set_apic_base(vcpu, sregs->apic_base);
2736
2737         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2738
2739         mmu_reset_needed |= vcpu->arch.cr0 != sregs->cr0;
2740         vcpu->arch.cr0 = sregs->cr0;
2741         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
2742
2743         mmu_reset_needed |= vcpu->arch.cr4 != sregs->cr4;
2744         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
2745         if (!is_long_mode(vcpu) && is_pae(vcpu))
2746                 load_pdptrs(vcpu, vcpu->arch.cr3);
2747
2748         if (mmu_reset_needed)
2749                 kvm_mmu_reset_context(vcpu);
2750
2751         if (!irqchip_in_kernel(vcpu->kvm)) {
2752                 memcpy(vcpu->arch.irq_pending, sregs->interrupt_bitmap,
2753                        sizeof vcpu->arch.irq_pending);
2754                 vcpu->arch.irq_summary = 0;
2755                 for (i = 0; i < ARRAY_SIZE(vcpu->arch.irq_pending); ++i)
2756                         if (vcpu->arch.irq_pending[i])
2757                                 __set_bit(i, &vcpu->arch.irq_summary);
2758         } else {
2759                 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
2760                 pending_vec = find_first_bit(
2761                         (const unsigned long *)sregs->interrupt_bitmap,
2762                         max_bits);
2763                 /* Only pending external irq is handled here */
2764                 if (pending_vec < max_bits) {
2765                         kvm_x86_ops->set_irq(vcpu, pending_vec);
2766                         pr_debug("Set back pending irq %d\n",
2767                                  pending_vec);
2768                 }
2769         }
2770
2771         set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
2772         set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
2773         set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
2774         set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
2775         set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
2776         set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
2777
2778         set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
2779         set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
2780
2781         vcpu_put(vcpu);
2782
2783         return 0;
2784 }
2785
2786 int kvm_arch_vcpu_ioctl_debug_guest(struct kvm_vcpu *vcpu,
2787                                     struct kvm_debug_guest *dbg)
2788 {
2789         int r;
2790
2791         vcpu_load(vcpu);
2792
2793         r = kvm_x86_ops->set_guest_debug(vcpu, dbg);
2794
2795         vcpu_put(vcpu);
2796
2797         return r;
2798 }
2799
2800 /*
2801  * fxsave fpu state.  Taken from x86_64/processor.h.  To be killed when
2802  * we have asm/x86/processor.h
2803  */
2804 struct fxsave {
2805         u16     cwd;
2806         u16     swd;
2807         u16     twd;
2808         u16     fop;
2809         u64     rip;
2810         u64     rdp;
2811         u32     mxcsr;
2812         u32     mxcsr_mask;
2813         u32     st_space[32];   /* 8*16 bytes for each FP-reg = 128 bytes */
2814 #ifdef CONFIG_X86_64
2815         u32     xmm_space[64];  /* 16*16 bytes for each XMM-reg = 256 bytes */
2816 #else
2817         u32     xmm_space[32];  /* 8*16 bytes for each XMM-reg = 128 bytes */
2818 #endif
2819 };
2820
2821 /*
2822  * Translate a guest virtual address to a guest physical address.
2823  */
2824 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
2825                                     struct kvm_translation *tr)
2826 {
2827         unsigned long vaddr = tr->linear_address;
2828         gpa_t gpa;
2829
2830         vcpu_load(vcpu);
2831         mutex_lock(&vcpu->kvm->lock);
2832         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, vaddr);
2833         tr->physical_address = gpa;
2834         tr->valid = gpa != UNMAPPED_GVA;
2835         tr->writeable = 1;
2836         tr->usermode = 0;
2837         mutex_unlock(&vcpu->kvm->lock);
2838         vcpu_put(vcpu);
2839
2840         return 0;
2841 }
2842
2843 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2844 {
2845         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
2846
2847         vcpu_load(vcpu);
2848
2849         memcpy(fpu->fpr, fxsave->st_space, 128);
2850         fpu->fcw = fxsave->cwd;
2851         fpu->fsw = fxsave->swd;
2852         fpu->ftwx = fxsave->twd;
2853         fpu->last_opcode = fxsave->fop;
2854         fpu->last_ip = fxsave->rip;
2855         fpu->last_dp = fxsave->rdp;
2856         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
2857
2858         vcpu_put(vcpu);
2859
2860         return 0;
2861 }
2862
2863 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2864 {
2865         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
2866
2867         vcpu_load(vcpu);
2868
2869         memcpy(fxsave->st_space, fpu->fpr, 128);
2870         fxsave->cwd = fpu->fcw;
2871         fxsave->swd = fpu->fsw;
2872         fxsave->twd = fpu->ftwx;
2873         fxsave->fop = fpu->last_opcode;
2874         fxsave->rip = fpu->last_ip;
2875         fxsave->rdp = fpu->last_dp;
2876         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
2877
2878         vcpu_put(vcpu);
2879
2880         return 0;
2881 }
2882
2883 void fx_init(struct kvm_vcpu *vcpu)
2884 {
2885         unsigned after_mxcsr_mask;
2886
2887         /* Initialize guest FPU by resetting ours and saving into guest's */
2888         preempt_disable();
2889         fx_save(&vcpu->arch.host_fx_image);
2890         fpu_init();
2891         fx_save(&vcpu->arch.guest_fx_image);
2892         fx_restore(&vcpu->arch.host_fx_image);
2893         preempt_enable();
2894
2895         vcpu->arch.cr0 |= X86_CR0_ET;
2896         after_mxcsr_mask = offsetof(struct i387_fxsave_struct, st_space);
2897         vcpu->arch.guest_fx_image.mxcsr = 0x1f80;
2898         memset((void *)&vcpu->arch.guest_fx_image + after_mxcsr_mask,
2899                0, sizeof(struct i387_fxsave_struct) - after_mxcsr_mask);
2900 }
2901 EXPORT_SYMBOL_GPL(fx_init);
2902
2903 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
2904 {
2905         if (!vcpu->fpu_active || vcpu->guest_fpu_loaded)
2906                 return;
2907
2908         vcpu->guest_fpu_loaded = 1;
2909         fx_save(&vcpu->arch.host_fx_image);
2910         fx_restore(&vcpu->arch.guest_fx_image);
2911 }
2912 EXPORT_SYMBOL_GPL(kvm_load_guest_fpu);
2913
2914 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
2915 {
2916         if (!vcpu->guest_fpu_loaded)
2917                 return;
2918
2919         vcpu->guest_fpu_loaded = 0;
2920         fx_save(&vcpu->arch.guest_fx_image);
2921         fx_restore(&vcpu->arch.host_fx_image);
2922         ++vcpu->stat.fpu_reload;
2923 }
2924 EXPORT_SYMBOL_GPL(kvm_put_guest_fpu);
2925
2926 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
2927 {
2928         kvm_x86_ops->vcpu_free(vcpu);
2929 }
2930
2931 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
2932                                                 unsigned int id)
2933 {
2934         return kvm_x86_ops->vcpu_create(kvm, id);
2935 }
2936
2937 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
2938 {
2939         int r;
2940
2941         /* We do fxsave: this must be aligned. */
2942         BUG_ON((unsigned long)&vcpu->arch.host_fx_image & 0xF);
2943
2944         vcpu_load(vcpu);
2945         r = kvm_arch_vcpu_reset(vcpu);
2946         if (r == 0)
2947                 r = kvm_mmu_setup(vcpu);
2948         vcpu_put(vcpu);
2949         if (r < 0)
2950                 goto free_vcpu;
2951
2952         return 0;
2953 free_vcpu:
2954         kvm_x86_ops->vcpu_free(vcpu);
2955         return r;
2956 }
2957
2958 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
2959 {
2960         vcpu_load(vcpu);
2961         kvm_mmu_unload(vcpu);
2962         vcpu_put(vcpu);
2963
2964         kvm_x86_ops->vcpu_free(vcpu);
2965 }
2966
2967 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
2968 {
2969         return kvm_x86_ops->vcpu_reset(vcpu);
2970 }
2971
2972 void kvm_arch_hardware_enable(void *garbage)
2973 {
2974         kvm_x86_ops->hardware_enable(garbage);
2975 }
2976
2977 void kvm_arch_hardware_disable(void *garbage)
2978 {
2979         kvm_x86_ops->hardware_disable(garbage);
2980 }
2981
2982 int kvm_arch_hardware_setup(void)
2983 {
2984         return kvm_x86_ops->hardware_setup();
2985 }
2986
2987 void kvm_arch_hardware_unsetup(void)
2988 {
2989         kvm_x86_ops->hardware_unsetup();
2990 }
2991
2992 void kvm_arch_check_processor_compat(void *rtn)
2993 {
2994         kvm_x86_ops->check_processor_compatibility(rtn);
2995 }
2996
2997 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
2998 {
2999         struct page *page;
3000         struct kvm *kvm;
3001         int r;
3002
3003         BUG_ON(vcpu->kvm == NULL);
3004         kvm = vcpu->kvm;
3005
3006         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
3007         if (!irqchip_in_kernel(kvm) || vcpu->vcpu_id == 0)
3008                 vcpu->arch.mp_state = VCPU_MP_STATE_RUNNABLE;
3009         else
3010                 vcpu->arch.mp_state = VCPU_MP_STATE_UNINITIALIZED;
3011
3012         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
3013         if (!page) {
3014                 r = -ENOMEM;
3015                 goto fail;
3016         }
3017         vcpu->arch.pio_data = page_address(page);
3018
3019         r = kvm_mmu_create(vcpu);
3020         if (r < 0)
3021                 goto fail_free_pio_data;
3022
3023         if (irqchip_in_kernel(kvm)) {
3024                 r = kvm_create_lapic(vcpu);
3025                 if (r < 0)
3026                         goto fail_mmu_destroy;
3027         }
3028
3029         return 0;
3030
3031 fail_mmu_destroy:
3032         kvm_mmu_destroy(vcpu);
3033 fail_free_pio_data:
3034         free_page((unsigned long)vcpu->arch.pio_data);
3035 fail:
3036         return r;
3037 }
3038
3039 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
3040 {
3041         kvm_free_lapic(vcpu);
3042         kvm_mmu_destroy(vcpu);
3043         free_page((unsigned long)vcpu->arch.pio_data);
3044 }
3045
3046 struct  kvm *kvm_arch_create_vm(void)
3047 {
3048         struct kvm *kvm = kzalloc(sizeof(struct kvm), GFP_KERNEL);
3049
3050         if (!kvm)
3051                 return ERR_PTR(-ENOMEM);
3052
3053         INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
3054
3055         return kvm;
3056 }
3057
3058 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
3059 {
3060         vcpu_load(vcpu);
3061         kvm_mmu_unload(vcpu);
3062         vcpu_put(vcpu);
3063 }
3064
3065 static void kvm_free_vcpus(struct kvm *kvm)
3066 {
3067         unsigned int i;
3068
3069         /*
3070          * Unpin any mmu pages first.
3071          */
3072         for (i = 0; i < KVM_MAX_VCPUS; ++i)
3073                 if (kvm->vcpus[i])
3074                         kvm_unload_vcpu_mmu(kvm->vcpus[i]);
3075         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
3076                 if (kvm->vcpus[i]) {
3077                         kvm_arch_vcpu_free(kvm->vcpus[i]);
3078                         kvm->vcpus[i] = NULL;
3079                 }
3080         }
3081
3082 }
3083
3084 void kvm_arch_destroy_vm(struct kvm *kvm)
3085 {
3086         kfree(kvm->arch.vpic);
3087         kfree(kvm->arch.vioapic);
3088         kvm_free_vcpus(kvm);
3089         kvm_free_physmem(kvm);
3090         kfree(kvm);
3091 }
3092
3093 int kvm_arch_set_memory_region(struct kvm *kvm,
3094                                 struct kvm_userspace_memory_region *mem,
3095                                 struct kvm_memory_slot old,
3096                                 int user_alloc)
3097 {
3098         int npages = mem->memory_size >> PAGE_SHIFT;
3099         struct kvm_memory_slot *memslot = &kvm->memslots[mem->slot];
3100
3101         /*To keep backward compatibility with older userspace,
3102          *x86 needs to hanlde !user_alloc case.
3103          */
3104         if (!user_alloc) {
3105                 if (npages && !old.rmap) {
3106                         down_write(&current->mm->mmap_sem);
3107                         memslot->userspace_addr = do_mmap(NULL, 0,
3108                                                      npages * PAGE_SIZE,
3109                                                      PROT_READ | PROT_WRITE,
3110                                                      MAP_SHARED | MAP_ANONYMOUS,
3111                                                      0);
3112                         up_write(&current->mm->mmap_sem);
3113
3114                         if (IS_ERR((void *)memslot->userspace_addr))
3115                                 return PTR_ERR((void *)memslot->userspace_addr);
3116                 } else {
3117                         if (!old.user_alloc && old.rmap) {
3118                                 int ret;
3119
3120                                 down_write(&current->mm->mmap_sem);
3121                                 ret = do_munmap(current->mm, old.userspace_addr,
3122                                                 old.npages * PAGE_SIZE);
3123                                 up_write(&current->mm->mmap_sem);
3124                                 if (ret < 0)
3125                                         printk(KERN_WARNING
3126                                        "kvm_vm_ioctl_set_memory_region: "
3127                                        "failed to munmap memory\n");
3128                         }
3129                 }
3130         }
3131
3132         if (!kvm->arch.n_requested_mmu_pages) {
3133                 unsigned int nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
3134                 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
3135         }
3136
3137         kvm_mmu_slot_remove_write_access(kvm, mem->slot);
3138         kvm_flush_remote_tlbs(kvm);
3139
3140         return 0;
3141 }
3142
3143 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
3144 {
3145         return vcpu->arch.mp_state == VCPU_MP_STATE_RUNNABLE
3146                || vcpu->arch.mp_state == VCPU_MP_STATE_SIPI_RECEIVED;
3147 }
3148
3149 static void vcpu_kick_intr(void *info)
3150 {
3151 #ifdef DEBUG
3152         struct kvm_vcpu *vcpu = (struct kvm_vcpu *)info;
3153         printk(KERN_DEBUG "vcpu_kick_intr %p \n", vcpu);
3154 #endif
3155 }
3156
3157 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
3158 {
3159         int ipi_pcpu = vcpu->cpu;
3160
3161         if (waitqueue_active(&vcpu->wq)) {
3162                 wake_up_interruptible(&vcpu->wq);
3163                 ++vcpu->stat.halt_wakeup;
3164         }
3165         if (vcpu->guest_mode)
3166                 smp_call_function_single(ipi_pcpu, vcpu_kick_intr, vcpu, 0, 0);
3167 }