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