]> err.no Git - linux-2.6/blob - drivers/kvm/x86.c
KVM: Portability: Add vcpu and hardware management arch hooks
[linux-2.6] / drivers / 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 "kvm.h"
18 #include "x86.h"
19 #include "x86_emulate.h"
20 #include "segment_descriptor.h"
21 #include "irq.h"
22
23 #include <linux/kvm.h>
24 #include <linux/fs.h>
25 #include <linux/vmalloc.h>
26 #include <linux/module.h>
27
28 #include <asm/uaccess.h>
29 #include <asm/msr.h>
30
31 #define MAX_IO_MSRS 256
32 #define CR0_RESERVED_BITS                                               \
33         (~(unsigned long)(X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS \
34                           | X86_CR0_ET | X86_CR0_NE | X86_CR0_WP | X86_CR0_AM \
35                           | X86_CR0_NW | X86_CR0_CD | X86_CR0_PG))
36 #define CR4_RESERVED_BITS                                               \
37         (~(unsigned long)(X86_CR4_VME | X86_CR4_PVI | X86_CR4_TSD | X86_CR4_DE\
38                           | X86_CR4_PSE | X86_CR4_PAE | X86_CR4_MCE     \
39                           | X86_CR4_PGE | X86_CR4_PCE | X86_CR4_OSFXSR  \
40                           | X86_CR4_OSXMMEXCPT | X86_CR4_VMXE))
41
42 #define CR8_RESERVED_BITS (~(unsigned long)X86_CR8_TPR)
43 #define EFER_RESERVED_BITS 0xfffffffffffff2fe
44
45 #define STAT_OFFSET(x) offsetof(struct kvm_vcpu, stat.x)
46
47 struct kvm_x86_ops *kvm_x86_ops;
48
49 struct kvm_stats_debugfs_item debugfs_entries[] = {
50         { "pf_fixed", STAT_OFFSET(pf_fixed) },
51         { "pf_guest", STAT_OFFSET(pf_guest) },
52         { "tlb_flush", STAT_OFFSET(tlb_flush) },
53         { "invlpg", STAT_OFFSET(invlpg) },
54         { "exits", STAT_OFFSET(exits) },
55         { "io_exits", STAT_OFFSET(io_exits) },
56         { "mmio_exits", STAT_OFFSET(mmio_exits) },
57         { "signal_exits", STAT_OFFSET(signal_exits) },
58         { "irq_window", STAT_OFFSET(irq_window_exits) },
59         { "halt_exits", STAT_OFFSET(halt_exits) },
60         { "halt_wakeup", STAT_OFFSET(halt_wakeup) },
61         { "request_irq", STAT_OFFSET(request_irq_exits) },
62         { "irq_exits", STAT_OFFSET(irq_exits) },
63         { "light_exits", STAT_OFFSET(light_exits) },
64         { "efer_reload", STAT_OFFSET(efer_reload) },
65         { NULL }
66 };
67
68
69 unsigned long segment_base(u16 selector)
70 {
71         struct descriptor_table gdt;
72         struct segment_descriptor *d;
73         unsigned long table_base;
74         unsigned long v;
75
76         if (selector == 0)
77                 return 0;
78
79         asm("sgdt %0" : "=m"(gdt));
80         table_base = gdt.base;
81
82         if (selector & 4) {           /* from ldt */
83                 u16 ldt_selector;
84
85                 asm("sldt %0" : "=g"(ldt_selector));
86                 table_base = segment_base(ldt_selector);
87         }
88         d = (struct segment_descriptor *)(table_base + (selector & ~7));
89         v = d->base_low | ((unsigned long)d->base_mid << 16) |
90                 ((unsigned long)d->base_high << 24);
91 #ifdef CONFIG_X86_64
92         if (d->system == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
93                 v |= ((unsigned long) \
94                       ((struct segment_descriptor_64 *)d)->base_higher) << 32;
95 #endif
96         return v;
97 }
98 EXPORT_SYMBOL_GPL(segment_base);
99
100 u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
101 {
102         if (irqchip_in_kernel(vcpu->kvm))
103                 return vcpu->apic_base;
104         else
105                 return vcpu->apic_base;
106 }
107 EXPORT_SYMBOL_GPL(kvm_get_apic_base);
108
109 void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
110 {
111         /* TODO: reserve bits check */
112         if (irqchip_in_kernel(vcpu->kvm))
113                 kvm_lapic_set_base(vcpu, data);
114         else
115                 vcpu->apic_base = data;
116 }
117 EXPORT_SYMBOL_GPL(kvm_set_apic_base);
118
119 static void inject_gp(struct kvm_vcpu *vcpu)
120 {
121         kvm_x86_ops->inject_gp(vcpu, 0);
122 }
123
124 /*
125  * Load the pae pdptrs.  Return true is they are all valid.
126  */
127 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
128 {
129         gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
130         unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
131         int i;
132         int ret;
133         u64 pdpte[ARRAY_SIZE(vcpu->pdptrs)];
134
135         mutex_lock(&vcpu->kvm->lock);
136         ret = kvm_read_guest_page(vcpu->kvm, pdpt_gfn, pdpte,
137                                   offset * sizeof(u64), sizeof(pdpte));
138         if (ret < 0) {
139                 ret = 0;
140                 goto out;
141         }
142         for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
143                 if ((pdpte[i] & 1) && (pdpte[i] & 0xfffffff0000001e6ull)) {
144                         ret = 0;
145                         goto out;
146                 }
147         }
148         ret = 1;
149
150         memcpy(vcpu->pdptrs, pdpte, sizeof(vcpu->pdptrs));
151 out:
152         mutex_unlock(&vcpu->kvm->lock);
153
154         return ret;
155 }
156
157 void set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
158 {
159         if (cr0 & CR0_RESERVED_BITS) {
160                 printk(KERN_DEBUG "set_cr0: 0x%lx #GP, reserved bits 0x%lx\n",
161                        cr0, vcpu->cr0);
162                 inject_gp(vcpu);
163                 return;
164         }
165
166         if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD)) {
167                 printk(KERN_DEBUG "set_cr0: #GP, CD == 0 && NW == 1\n");
168                 inject_gp(vcpu);
169                 return;
170         }
171
172         if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE)) {
173                 printk(KERN_DEBUG "set_cr0: #GP, set PG flag "
174                        "and a clear PE flag\n");
175                 inject_gp(vcpu);
176                 return;
177         }
178
179         if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
180 #ifdef CONFIG_X86_64
181                 if ((vcpu->shadow_efer & EFER_LME)) {
182                         int cs_db, cs_l;
183
184                         if (!is_pae(vcpu)) {
185                                 printk(KERN_DEBUG "set_cr0: #GP, start paging "
186                                        "in long mode while PAE is disabled\n");
187                                 inject_gp(vcpu);
188                                 return;
189                         }
190                         kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
191                         if (cs_l) {
192                                 printk(KERN_DEBUG "set_cr0: #GP, start paging "
193                                        "in long mode while CS.L == 1\n");
194                                 inject_gp(vcpu);
195                                 return;
196
197                         }
198                 } else
199 #endif
200                 if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->cr3)) {
201                         printk(KERN_DEBUG "set_cr0: #GP, pdptrs "
202                                "reserved bits\n");
203                         inject_gp(vcpu);
204                         return;
205                 }
206
207         }
208
209         kvm_x86_ops->set_cr0(vcpu, cr0);
210         vcpu->cr0 = cr0;
211
212         mutex_lock(&vcpu->kvm->lock);
213         kvm_mmu_reset_context(vcpu);
214         mutex_unlock(&vcpu->kvm->lock);
215         return;
216 }
217 EXPORT_SYMBOL_GPL(set_cr0);
218
219 void lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
220 {
221         set_cr0(vcpu, (vcpu->cr0 & ~0x0ful) | (msw & 0x0f));
222 }
223 EXPORT_SYMBOL_GPL(lmsw);
224
225 void set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
226 {
227         if (cr4 & CR4_RESERVED_BITS) {
228                 printk(KERN_DEBUG "set_cr4: #GP, reserved bits\n");
229                 inject_gp(vcpu);
230                 return;
231         }
232
233         if (is_long_mode(vcpu)) {
234                 if (!(cr4 & X86_CR4_PAE)) {
235                         printk(KERN_DEBUG "set_cr4: #GP, clearing PAE while "
236                                "in long mode\n");
237                         inject_gp(vcpu);
238                         return;
239                 }
240         } else if (is_paging(vcpu) && !is_pae(vcpu) && (cr4 & X86_CR4_PAE)
241                    && !load_pdptrs(vcpu, vcpu->cr3)) {
242                 printk(KERN_DEBUG "set_cr4: #GP, pdptrs reserved bits\n");
243                 inject_gp(vcpu);
244                 return;
245         }
246
247         if (cr4 & X86_CR4_VMXE) {
248                 printk(KERN_DEBUG "set_cr4: #GP, setting VMXE\n");
249                 inject_gp(vcpu);
250                 return;
251         }
252         kvm_x86_ops->set_cr4(vcpu, cr4);
253         vcpu->cr4 = cr4;
254         mutex_lock(&vcpu->kvm->lock);
255         kvm_mmu_reset_context(vcpu);
256         mutex_unlock(&vcpu->kvm->lock);
257 }
258 EXPORT_SYMBOL_GPL(set_cr4);
259
260 void set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
261 {
262         if (is_long_mode(vcpu)) {
263                 if (cr3 & CR3_L_MODE_RESERVED_BITS) {
264                         printk(KERN_DEBUG "set_cr3: #GP, reserved bits\n");
265                         inject_gp(vcpu);
266                         return;
267                 }
268         } else {
269                 if (is_pae(vcpu)) {
270                         if (cr3 & CR3_PAE_RESERVED_BITS) {
271                                 printk(KERN_DEBUG
272                                        "set_cr3: #GP, reserved bits\n");
273                                 inject_gp(vcpu);
274                                 return;
275                         }
276                         if (is_paging(vcpu) && !load_pdptrs(vcpu, cr3)) {
277                                 printk(KERN_DEBUG "set_cr3: #GP, pdptrs "
278                                        "reserved bits\n");
279                                 inject_gp(vcpu);
280                                 return;
281                         }
282                 }
283                 /*
284                  * We don't check reserved bits in nonpae mode, because
285                  * this isn't enforced, and VMware depends on this.
286                  */
287         }
288
289         mutex_lock(&vcpu->kvm->lock);
290         /*
291          * Does the new cr3 value map to physical memory? (Note, we
292          * catch an invalid cr3 even in real-mode, because it would
293          * cause trouble later on when we turn on paging anyway.)
294          *
295          * A real CPU would silently accept an invalid cr3 and would
296          * attempt to use it - with largely undefined (and often hard
297          * to debug) behavior on the guest side.
298          */
299         if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
300                 inject_gp(vcpu);
301         else {
302                 vcpu->cr3 = cr3;
303                 vcpu->mmu.new_cr3(vcpu);
304         }
305         mutex_unlock(&vcpu->kvm->lock);
306 }
307 EXPORT_SYMBOL_GPL(set_cr3);
308
309 void set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
310 {
311         if (cr8 & CR8_RESERVED_BITS) {
312                 printk(KERN_DEBUG "set_cr8: #GP, reserved bits 0x%lx\n", cr8);
313                 inject_gp(vcpu);
314                 return;
315         }
316         if (irqchip_in_kernel(vcpu->kvm))
317                 kvm_lapic_set_tpr(vcpu, cr8);
318         else
319                 vcpu->cr8 = cr8;
320 }
321 EXPORT_SYMBOL_GPL(set_cr8);
322
323 unsigned long get_cr8(struct kvm_vcpu *vcpu)
324 {
325         if (irqchip_in_kernel(vcpu->kvm))
326                 return kvm_lapic_get_cr8(vcpu);
327         else
328                 return vcpu->cr8;
329 }
330 EXPORT_SYMBOL_GPL(get_cr8);
331
332 /*
333  * List of msr numbers which we expose to userspace through KVM_GET_MSRS
334  * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
335  *
336  * This list is modified at module load time to reflect the
337  * capabilities of the host cpu.
338  */
339 static u32 msrs_to_save[] = {
340         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
341         MSR_K6_STAR,
342 #ifdef CONFIG_X86_64
343         MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
344 #endif
345         MSR_IA32_TIME_STAMP_COUNTER,
346 };
347
348 static unsigned num_msrs_to_save;
349
350 static u32 emulated_msrs[] = {
351         MSR_IA32_MISC_ENABLE,
352 };
353
354 #ifdef CONFIG_X86_64
355
356 static void set_efer(struct kvm_vcpu *vcpu, u64 efer)
357 {
358         if (efer & EFER_RESERVED_BITS) {
359                 printk(KERN_DEBUG "set_efer: 0x%llx #GP, reserved bits\n",
360                        efer);
361                 inject_gp(vcpu);
362                 return;
363         }
364
365         if (is_paging(vcpu)
366             && (vcpu->shadow_efer & EFER_LME) != (efer & EFER_LME)) {
367                 printk(KERN_DEBUG "set_efer: #GP, change LME while paging\n");
368                 inject_gp(vcpu);
369                 return;
370         }
371
372         kvm_x86_ops->set_efer(vcpu, efer);
373
374         efer &= ~EFER_LMA;
375         efer |= vcpu->shadow_efer & EFER_LMA;
376
377         vcpu->shadow_efer = efer;
378 }
379
380 #endif
381
382 /*
383  * Writes msr value into into the appropriate "register".
384  * Returns 0 on success, non-0 otherwise.
385  * Assumes vcpu_load() was already called.
386  */
387 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
388 {
389         return kvm_x86_ops->set_msr(vcpu, msr_index, data);
390 }
391
392 /*
393  * Adapt set_msr() to msr_io()'s calling convention
394  */
395 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
396 {
397         return kvm_set_msr(vcpu, index, *data);
398 }
399
400
401 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
402 {
403         switch (msr) {
404 #ifdef CONFIG_X86_64
405         case MSR_EFER:
406                 set_efer(vcpu, data);
407                 break;
408 #endif
409         case MSR_IA32_MC0_STATUS:
410                 pr_unimpl(vcpu, "%s: MSR_IA32_MC0_STATUS 0x%llx, nop\n",
411                        __FUNCTION__, data);
412                 break;
413         case MSR_IA32_MCG_STATUS:
414                 pr_unimpl(vcpu, "%s: MSR_IA32_MCG_STATUS 0x%llx, nop\n",
415                         __FUNCTION__, data);
416                 break;
417         case MSR_IA32_UCODE_REV:
418         case MSR_IA32_UCODE_WRITE:
419         case 0x200 ... 0x2ff: /* MTRRs */
420                 break;
421         case MSR_IA32_APICBASE:
422                 kvm_set_apic_base(vcpu, data);
423                 break;
424         case MSR_IA32_MISC_ENABLE:
425                 vcpu->ia32_misc_enable_msr = data;
426                 break;
427         default:
428                 pr_unimpl(vcpu, "unhandled wrmsr: 0x%x\n", msr);
429                 return 1;
430         }
431         return 0;
432 }
433 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
434
435
436 /*
437  * Reads an msr value (of 'msr_index') into 'pdata'.
438  * Returns 0 on success, non-0 otherwise.
439  * Assumes vcpu_load() was already called.
440  */
441 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
442 {
443         return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
444 }
445
446 int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
447 {
448         u64 data;
449
450         switch (msr) {
451         case 0xc0010010: /* SYSCFG */
452         case 0xc0010015: /* HWCR */
453         case MSR_IA32_PLATFORM_ID:
454         case MSR_IA32_P5_MC_ADDR:
455         case MSR_IA32_P5_MC_TYPE:
456         case MSR_IA32_MC0_CTL:
457         case MSR_IA32_MCG_STATUS:
458         case MSR_IA32_MCG_CAP:
459         case MSR_IA32_MC0_MISC:
460         case MSR_IA32_MC0_MISC+4:
461         case MSR_IA32_MC0_MISC+8:
462         case MSR_IA32_MC0_MISC+12:
463         case MSR_IA32_MC0_MISC+16:
464         case MSR_IA32_UCODE_REV:
465         case MSR_IA32_PERF_STATUS:
466         case MSR_IA32_EBL_CR_POWERON:
467                 /* MTRR registers */
468         case 0xfe:
469         case 0x200 ... 0x2ff:
470                 data = 0;
471                 break;
472         case 0xcd: /* fsb frequency */
473                 data = 3;
474                 break;
475         case MSR_IA32_APICBASE:
476                 data = kvm_get_apic_base(vcpu);
477                 break;
478         case MSR_IA32_MISC_ENABLE:
479                 data = vcpu->ia32_misc_enable_msr;
480                 break;
481 #ifdef CONFIG_X86_64
482         case MSR_EFER:
483                 data = vcpu->shadow_efer;
484                 break;
485 #endif
486         default:
487                 pr_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
488                 return 1;
489         }
490         *pdata = data;
491         return 0;
492 }
493 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
494
495 /*
496  * Read or write a bunch of msrs. All parameters are kernel addresses.
497  *
498  * @return number of msrs set successfully.
499  */
500 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
501                     struct kvm_msr_entry *entries,
502                     int (*do_msr)(struct kvm_vcpu *vcpu,
503                                   unsigned index, u64 *data))
504 {
505         int i;
506
507         vcpu_load(vcpu);
508
509         for (i = 0; i < msrs->nmsrs; ++i)
510                 if (do_msr(vcpu, entries[i].index, &entries[i].data))
511                         break;
512
513         vcpu_put(vcpu);
514
515         return i;
516 }
517
518 /*
519  * Read or write a bunch of msrs. Parameters are user addresses.
520  *
521  * @return number of msrs set successfully.
522  */
523 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
524                   int (*do_msr)(struct kvm_vcpu *vcpu,
525                                 unsigned index, u64 *data),
526                   int writeback)
527 {
528         struct kvm_msrs msrs;
529         struct kvm_msr_entry *entries;
530         int r, n;
531         unsigned size;
532
533         r = -EFAULT;
534         if (copy_from_user(&msrs, user_msrs, sizeof msrs))
535                 goto out;
536
537         r = -E2BIG;
538         if (msrs.nmsrs >= MAX_IO_MSRS)
539                 goto out;
540
541         r = -ENOMEM;
542         size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
543         entries = vmalloc(size);
544         if (!entries)
545                 goto out;
546
547         r = -EFAULT;
548         if (copy_from_user(entries, user_msrs->entries, size))
549                 goto out_free;
550
551         r = n = __msr_io(vcpu, &msrs, entries, do_msr);
552         if (r < 0)
553                 goto out_free;
554
555         r = -EFAULT;
556         if (writeback && copy_to_user(user_msrs->entries, entries, size))
557                 goto out_free;
558
559         r = n;
560
561 out_free:
562         vfree(entries);
563 out:
564         return r;
565 }
566
567 /*
568  * Make sure that a cpu that is being hot-unplugged does not have any vcpus
569  * cached on it.
570  */
571 void decache_vcpus_on_cpu(int cpu)
572 {
573         struct kvm *vm;
574         struct kvm_vcpu *vcpu;
575         int i;
576
577         spin_lock(&kvm_lock);
578         list_for_each_entry(vm, &vm_list, vm_list)
579                 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
580                         vcpu = vm->vcpus[i];
581                         if (!vcpu)
582                                 continue;
583                         /*
584                          * If the vcpu is locked, then it is running on some
585                          * other cpu and therefore it is not cached on the
586                          * cpu in question.
587                          *
588                          * If it's not locked, check the last cpu it executed
589                          * on.
590                          */
591                         if (mutex_trylock(&vcpu->mutex)) {
592                                 if (vcpu->cpu == cpu) {
593                                         kvm_x86_ops->vcpu_decache(vcpu);
594                                         vcpu->cpu = -1;
595                                 }
596                                 mutex_unlock(&vcpu->mutex);
597                         }
598                 }
599         spin_unlock(&kvm_lock);
600 }
601
602 long kvm_arch_dev_ioctl(struct file *filp,
603                         unsigned int ioctl, unsigned long arg)
604 {
605         void __user *argp = (void __user *)arg;
606         long r;
607
608         switch (ioctl) {
609         case KVM_GET_MSR_INDEX_LIST: {
610                 struct kvm_msr_list __user *user_msr_list = argp;
611                 struct kvm_msr_list msr_list;
612                 unsigned n;
613
614                 r = -EFAULT;
615                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
616                         goto out;
617                 n = msr_list.nmsrs;
618                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
619                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
620                         goto out;
621                 r = -E2BIG;
622                 if (n < num_msrs_to_save)
623                         goto out;
624                 r = -EFAULT;
625                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
626                                  num_msrs_to_save * sizeof(u32)))
627                         goto out;
628                 if (copy_to_user(user_msr_list->indices
629                                  + num_msrs_to_save * sizeof(u32),
630                                  &emulated_msrs,
631                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
632                         goto out;
633                 r = 0;
634                 break;
635         }
636         default:
637                 r = -EINVAL;
638         }
639 out:
640         return r;
641 }
642
643 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
644 {
645         kvm_x86_ops->vcpu_load(vcpu, cpu);
646 }
647
648 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
649 {
650         kvm_x86_ops->vcpu_put(vcpu);
651 }
652
653 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
654 {
655         u64 efer;
656         int i;
657         struct kvm_cpuid_entry *e, *entry;
658
659         rdmsrl(MSR_EFER, efer);
660         entry = NULL;
661         for (i = 0; i < vcpu->cpuid_nent; ++i) {
662                 e = &vcpu->cpuid_entries[i];
663                 if (e->function == 0x80000001) {
664                         entry = e;
665                         break;
666                 }
667         }
668         if (entry && (entry->edx & (1 << 20)) && !(efer & EFER_NX)) {
669                 entry->edx &= ~(1 << 20);
670                 printk(KERN_INFO "kvm: guest NX capability removed\n");
671         }
672 }
673
674 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
675                                     struct kvm_cpuid *cpuid,
676                                     struct kvm_cpuid_entry __user *entries)
677 {
678         int r;
679
680         r = -E2BIG;
681         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
682                 goto out;
683         r = -EFAULT;
684         if (copy_from_user(&vcpu->cpuid_entries, entries,
685                            cpuid->nent * sizeof(struct kvm_cpuid_entry)))
686                 goto out;
687         vcpu->cpuid_nent = cpuid->nent;
688         cpuid_fix_nx_cap(vcpu);
689         return 0;
690
691 out:
692         return r;
693 }
694
695 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
696                                     struct kvm_lapic_state *s)
697 {
698         vcpu_load(vcpu);
699         memcpy(s->regs, vcpu->apic->regs, sizeof *s);
700         vcpu_put(vcpu);
701
702         return 0;
703 }
704
705 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
706                                     struct kvm_lapic_state *s)
707 {
708         vcpu_load(vcpu);
709         memcpy(vcpu->apic->regs, s->regs, sizeof *s);
710         kvm_apic_post_state_restore(vcpu);
711         vcpu_put(vcpu);
712
713         return 0;
714 }
715
716 long kvm_arch_vcpu_ioctl(struct file *filp,
717                          unsigned int ioctl, unsigned long arg)
718 {
719         struct kvm_vcpu *vcpu = filp->private_data;
720         void __user *argp = (void __user *)arg;
721         int r;
722
723         switch (ioctl) {
724         case KVM_GET_LAPIC: {
725                 struct kvm_lapic_state lapic;
726
727                 memset(&lapic, 0, sizeof lapic);
728                 r = kvm_vcpu_ioctl_get_lapic(vcpu, &lapic);
729                 if (r)
730                         goto out;
731                 r = -EFAULT;
732                 if (copy_to_user(argp, &lapic, sizeof lapic))
733                         goto out;
734                 r = 0;
735                 break;
736         }
737         case KVM_SET_LAPIC: {
738                 struct kvm_lapic_state lapic;
739
740                 r = -EFAULT;
741                 if (copy_from_user(&lapic, argp, sizeof lapic))
742                         goto out;
743                 r = kvm_vcpu_ioctl_set_lapic(vcpu, &lapic);;
744                 if (r)
745                         goto out;
746                 r = 0;
747                 break;
748         }
749         case KVM_SET_CPUID: {
750                 struct kvm_cpuid __user *cpuid_arg = argp;
751                 struct kvm_cpuid cpuid;
752
753                 r = -EFAULT;
754                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
755                         goto out;
756                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
757                 if (r)
758                         goto out;
759                 break;
760         }
761         case KVM_GET_MSRS:
762                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
763                 break;
764         case KVM_SET_MSRS:
765                 r = msr_io(vcpu, argp, do_set_msr, 0);
766                 break;
767         default:
768                 r = -EINVAL;
769         }
770 out:
771         return r;
772 }
773
774 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
775 {
776         int ret;
777
778         if (addr > (unsigned int)(-3 * PAGE_SIZE))
779                 return -1;
780         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
781         return ret;
782 }
783
784 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
785                                           u32 kvm_nr_mmu_pages)
786 {
787         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
788                 return -EINVAL;
789
790         mutex_lock(&kvm->lock);
791
792         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
793         kvm->n_requested_mmu_pages = kvm_nr_mmu_pages;
794
795         mutex_unlock(&kvm->lock);
796         return 0;
797 }
798
799 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
800 {
801         return kvm->n_alloc_mmu_pages;
802 }
803
804 /*
805  * Set a new alias region.  Aliases map a portion of physical memory into
806  * another portion.  This is useful for memory windows, for example the PC
807  * VGA region.
808  */
809 static int kvm_vm_ioctl_set_memory_alias(struct kvm *kvm,
810                                          struct kvm_memory_alias *alias)
811 {
812         int r, n;
813         struct kvm_mem_alias *p;
814
815         r = -EINVAL;
816         /* General sanity checks */
817         if (alias->memory_size & (PAGE_SIZE - 1))
818                 goto out;
819         if (alias->guest_phys_addr & (PAGE_SIZE - 1))
820                 goto out;
821         if (alias->slot >= KVM_ALIAS_SLOTS)
822                 goto out;
823         if (alias->guest_phys_addr + alias->memory_size
824             < alias->guest_phys_addr)
825                 goto out;
826         if (alias->target_phys_addr + alias->memory_size
827             < alias->target_phys_addr)
828                 goto out;
829
830         mutex_lock(&kvm->lock);
831
832         p = &kvm->aliases[alias->slot];
833         p->base_gfn = alias->guest_phys_addr >> PAGE_SHIFT;
834         p->npages = alias->memory_size >> PAGE_SHIFT;
835         p->target_gfn = alias->target_phys_addr >> PAGE_SHIFT;
836
837         for (n = KVM_ALIAS_SLOTS; n > 0; --n)
838                 if (kvm->aliases[n - 1].npages)
839                         break;
840         kvm->naliases = n;
841
842         kvm_mmu_zap_all(kvm);
843
844         mutex_unlock(&kvm->lock);
845
846         return 0;
847
848 out:
849         return r;
850 }
851
852 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
853 {
854         int r;
855
856         r = 0;
857         switch (chip->chip_id) {
858         case KVM_IRQCHIP_PIC_MASTER:
859                 memcpy(&chip->chip.pic,
860                         &pic_irqchip(kvm)->pics[0],
861                         sizeof(struct kvm_pic_state));
862                 break;
863         case KVM_IRQCHIP_PIC_SLAVE:
864                 memcpy(&chip->chip.pic,
865                         &pic_irqchip(kvm)->pics[1],
866                         sizeof(struct kvm_pic_state));
867                 break;
868         case KVM_IRQCHIP_IOAPIC:
869                 memcpy(&chip->chip.ioapic,
870                         ioapic_irqchip(kvm),
871                         sizeof(struct kvm_ioapic_state));
872                 break;
873         default:
874                 r = -EINVAL;
875                 break;
876         }
877         return r;
878 }
879
880 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
881 {
882         int r;
883
884         r = 0;
885         switch (chip->chip_id) {
886         case KVM_IRQCHIP_PIC_MASTER:
887                 memcpy(&pic_irqchip(kvm)->pics[0],
888                         &chip->chip.pic,
889                         sizeof(struct kvm_pic_state));
890                 break;
891         case KVM_IRQCHIP_PIC_SLAVE:
892                 memcpy(&pic_irqchip(kvm)->pics[1],
893                         &chip->chip.pic,
894                         sizeof(struct kvm_pic_state));
895                 break;
896         case KVM_IRQCHIP_IOAPIC:
897                 memcpy(ioapic_irqchip(kvm),
898                         &chip->chip.ioapic,
899                         sizeof(struct kvm_ioapic_state));
900                 break;
901         default:
902                 r = -EINVAL;
903                 break;
904         }
905         kvm_pic_update_irq(pic_irqchip(kvm));
906         return r;
907 }
908
909 long kvm_arch_vm_ioctl(struct file *filp,
910                        unsigned int ioctl, unsigned long arg)
911 {
912         struct kvm *kvm = filp->private_data;
913         void __user *argp = (void __user *)arg;
914         int r = -EINVAL;
915
916         switch (ioctl) {
917         case KVM_SET_TSS_ADDR:
918                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
919                 if (r < 0)
920                         goto out;
921                 break;
922         case KVM_SET_MEMORY_REGION: {
923                 struct kvm_memory_region kvm_mem;
924                 struct kvm_userspace_memory_region kvm_userspace_mem;
925
926                 r = -EFAULT;
927                 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
928                         goto out;
929                 kvm_userspace_mem.slot = kvm_mem.slot;
930                 kvm_userspace_mem.flags = kvm_mem.flags;
931                 kvm_userspace_mem.guest_phys_addr = kvm_mem.guest_phys_addr;
932                 kvm_userspace_mem.memory_size = kvm_mem.memory_size;
933                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 0);
934                 if (r)
935                         goto out;
936                 break;
937         }
938         case KVM_SET_NR_MMU_PAGES:
939                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
940                 if (r)
941                         goto out;
942                 break;
943         case KVM_GET_NR_MMU_PAGES:
944                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
945                 break;
946         case KVM_SET_MEMORY_ALIAS: {
947                 struct kvm_memory_alias alias;
948
949                 r = -EFAULT;
950                 if (copy_from_user(&alias, argp, sizeof alias))
951                         goto out;
952                 r = kvm_vm_ioctl_set_memory_alias(kvm, &alias);
953                 if (r)
954                         goto out;
955                 break;
956         }
957         case KVM_CREATE_IRQCHIP:
958                 r = -ENOMEM;
959                 kvm->vpic = kvm_create_pic(kvm);
960                 if (kvm->vpic) {
961                         r = kvm_ioapic_init(kvm);
962                         if (r) {
963                                 kfree(kvm->vpic);
964                                 kvm->vpic = NULL;
965                                 goto out;
966                         }
967                 } else
968                         goto out;
969                 break;
970         case KVM_IRQ_LINE: {
971                 struct kvm_irq_level irq_event;
972
973                 r = -EFAULT;
974                 if (copy_from_user(&irq_event, argp, sizeof irq_event))
975                         goto out;
976                 if (irqchip_in_kernel(kvm)) {
977                         mutex_lock(&kvm->lock);
978                         if (irq_event.irq < 16)
979                                 kvm_pic_set_irq(pic_irqchip(kvm),
980                                         irq_event.irq,
981                                         irq_event.level);
982                         kvm_ioapic_set_irq(kvm->vioapic,
983                                         irq_event.irq,
984                                         irq_event.level);
985                         mutex_unlock(&kvm->lock);
986                         r = 0;
987                 }
988                 break;
989         }
990         case KVM_GET_IRQCHIP: {
991                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
992                 struct kvm_irqchip chip;
993
994                 r = -EFAULT;
995                 if (copy_from_user(&chip, argp, sizeof chip))
996                         goto out;
997                 r = -ENXIO;
998                 if (!irqchip_in_kernel(kvm))
999                         goto out;
1000                 r = kvm_vm_ioctl_get_irqchip(kvm, &chip);
1001                 if (r)
1002                         goto out;
1003                 r = -EFAULT;
1004                 if (copy_to_user(argp, &chip, sizeof chip))
1005                         goto out;
1006                 r = 0;
1007                 break;
1008         }
1009         case KVM_SET_IRQCHIP: {
1010                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1011                 struct kvm_irqchip chip;
1012
1013                 r = -EFAULT;
1014                 if (copy_from_user(&chip, argp, sizeof chip))
1015                         goto out;
1016                 r = -ENXIO;
1017                 if (!irqchip_in_kernel(kvm))
1018                         goto out;
1019                 r = kvm_vm_ioctl_set_irqchip(kvm, &chip);
1020                 if (r)
1021                         goto out;
1022                 r = 0;
1023                 break;
1024         }
1025         default:
1026                 ;
1027         }
1028 out:
1029         return r;
1030 }
1031
1032 static __init void kvm_init_msr_list(void)
1033 {
1034         u32 dummy[2];
1035         unsigned i, j;
1036
1037         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
1038                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
1039                         continue;
1040                 if (j < i)
1041                         msrs_to_save[j] = msrs_to_save[i];
1042                 j++;
1043         }
1044         num_msrs_to_save = j;
1045 }
1046
1047 /*
1048  * Only apic need an MMIO device hook, so shortcut now..
1049  */
1050 static struct kvm_io_device *vcpu_find_pervcpu_dev(struct kvm_vcpu *vcpu,
1051                                                 gpa_t addr)
1052 {
1053         struct kvm_io_device *dev;
1054
1055         if (vcpu->apic) {
1056                 dev = &vcpu->apic->dev;
1057                 if (dev->in_range(dev, addr))
1058                         return dev;
1059         }
1060         return NULL;
1061 }
1062
1063
1064 static struct kvm_io_device *vcpu_find_mmio_dev(struct kvm_vcpu *vcpu,
1065                                                 gpa_t addr)
1066 {
1067         struct kvm_io_device *dev;
1068
1069         dev = vcpu_find_pervcpu_dev(vcpu, addr);
1070         if (dev == NULL)
1071                 dev = kvm_io_bus_find_dev(&vcpu->kvm->mmio_bus, addr);
1072         return dev;
1073 }
1074
1075 int emulator_read_std(unsigned long addr,
1076                              void *val,
1077                              unsigned int bytes,
1078                              struct kvm_vcpu *vcpu)
1079 {
1080         void *data = val;
1081
1082         while (bytes) {
1083                 gpa_t gpa = vcpu->mmu.gva_to_gpa(vcpu, addr);
1084                 unsigned offset = addr & (PAGE_SIZE-1);
1085                 unsigned tocopy = min(bytes, (unsigned)PAGE_SIZE - offset);
1086                 int ret;
1087
1088                 if (gpa == UNMAPPED_GVA)
1089                         return X86EMUL_PROPAGATE_FAULT;
1090                 ret = kvm_read_guest(vcpu->kvm, gpa, data, tocopy);
1091                 if (ret < 0)
1092                         return X86EMUL_UNHANDLEABLE;
1093
1094                 bytes -= tocopy;
1095                 data += tocopy;
1096                 addr += tocopy;
1097         }
1098
1099         return X86EMUL_CONTINUE;
1100 }
1101 EXPORT_SYMBOL_GPL(emulator_read_std);
1102
1103 static int emulator_write_std(unsigned long addr,
1104                               const void *val,
1105                               unsigned int bytes,
1106                               struct kvm_vcpu *vcpu)
1107 {
1108         pr_unimpl(vcpu, "emulator_write_std: addr %lx n %d\n", addr, bytes);
1109         return X86EMUL_UNHANDLEABLE;
1110 }
1111
1112 static int emulator_read_emulated(unsigned long addr,
1113                                   void *val,
1114                                   unsigned int bytes,
1115                                   struct kvm_vcpu *vcpu)
1116 {
1117         struct kvm_io_device *mmio_dev;
1118         gpa_t                 gpa;
1119
1120         if (vcpu->mmio_read_completed) {
1121                 memcpy(val, vcpu->mmio_data, bytes);
1122                 vcpu->mmio_read_completed = 0;
1123                 return X86EMUL_CONTINUE;
1124         }
1125
1126         gpa = vcpu->mmu.gva_to_gpa(vcpu, addr);
1127
1128         /* For APIC access vmexit */
1129         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1130                 goto mmio;
1131
1132         if (emulator_read_std(addr, val, bytes, vcpu)
1133                         == X86EMUL_CONTINUE)
1134                 return X86EMUL_CONTINUE;
1135         if (gpa == UNMAPPED_GVA)
1136                 return X86EMUL_PROPAGATE_FAULT;
1137
1138 mmio:
1139         /*
1140          * Is this MMIO handled locally?
1141          */
1142         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa);
1143         if (mmio_dev) {
1144                 kvm_iodevice_read(mmio_dev, gpa, bytes, val);
1145                 return X86EMUL_CONTINUE;
1146         }
1147
1148         vcpu->mmio_needed = 1;
1149         vcpu->mmio_phys_addr = gpa;
1150         vcpu->mmio_size = bytes;
1151         vcpu->mmio_is_write = 0;
1152
1153         return X86EMUL_UNHANDLEABLE;
1154 }
1155
1156 static int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
1157                                const void *val, int bytes)
1158 {
1159         int ret;
1160
1161         ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
1162         if (ret < 0)
1163                 return 0;
1164         kvm_mmu_pte_write(vcpu, gpa, val, bytes);
1165         return 1;
1166 }
1167
1168 static int emulator_write_emulated_onepage(unsigned long addr,
1169                                            const void *val,
1170                                            unsigned int bytes,
1171                                            struct kvm_vcpu *vcpu)
1172 {
1173         struct kvm_io_device *mmio_dev;
1174         gpa_t                 gpa = vcpu->mmu.gva_to_gpa(vcpu, addr);
1175
1176         if (gpa == UNMAPPED_GVA) {
1177                 kvm_x86_ops->inject_page_fault(vcpu, addr, 2);
1178                 return X86EMUL_PROPAGATE_FAULT;
1179         }
1180
1181         /* For APIC access vmexit */
1182         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1183                 goto mmio;
1184
1185         if (emulator_write_phys(vcpu, gpa, val, bytes))
1186                 return X86EMUL_CONTINUE;
1187
1188 mmio:
1189         /*
1190          * Is this MMIO handled locally?
1191          */
1192         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa);
1193         if (mmio_dev) {
1194                 kvm_iodevice_write(mmio_dev, gpa, bytes, val);
1195                 return X86EMUL_CONTINUE;
1196         }
1197
1198         vcpu->mmio_needed = 1;
1199         vcpu->mmio_phys_addr = gpa;
1200         vcpu->mmio_size = bytes;
1201         vcpu->mmio_is_write = 1;
1202         memcpy(vcpu->mmio_data, val, bytes);
1203
1204         return X86EMUL_CONTINUE;
1205 }
1206
1207 int emulator_write_emulated(unsigned long addr,
1208                                    const void *val,
1209                                    unsigned int bytes,
1210                                    struct kvm_vcpu *vcpu)
1211 {
1212         /* Crossing a page boundary? */
1213         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
1214                 int rc, now;
1215
1216                 now = -addr & ~PAGE_MASK;
1217                 rc = emulator_write_emulated_onepage(addr, val, now, vcpu);
1218                 if (rc != X86EMUL_CONTINUE)
1219                         return rc;
1220                 addr += now;
1221                 val += now;
1222                 bytes -= now;
1223         }
1224         return emulator_write_emulated_onepage(addr, val, bytes, vcpu);
1225 }
1226 EXPORT_SYMBOL_GPL(emulator_write_emulated);
1227
1228 static int emulator_cmpxchg_emulated(unsigned long addr,
1229                                      const void *old,
1230                                      const void *new,
1231                                      unsigned int bytes,
1232                                      struct kvm_vcpu *vcpu)
1233 {
1234         static int reported;
1235
1236         if (!reported) {
1237                 reported = 1;
1238                 printk(KERN_WARNING "kvm: emulating exchange as write\n");
1239         }
1240         return emulator_write_emulated(addr, new, bytes, vcpu);
1241 }
1242
1243 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
1244 {
1245         return kvm_x86_ops->get_segment_base(vcpu, seg);
1246 }
1247
1248 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
1249 {
1250         return X86EMUL_CONTINUE;
1251 }
1252
1253 int emulate_clts(struct kvm_vcpu *vcpu)
1254 {
1255         kvm_x86_ops->set_cr0(vcpu, vcpu->cr0 & ~X86_CR0_TS);
1256         return X86EMUL_CONTINUE;
1257 }
1258
1259 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
1260 {
1261         struct kvm_vcpu *vcpu = ctxt->vcpu;
1262
1263         switch (dr) {
1264         case 0 ... 3:
1265                 *dest = kvm_x86_ops->get_dr(vcpu, dr);
1266                 return X86EMUL_CONTINUE;
1267         default:
1268                 pr_unimpl(vcpu, "%s: unexpected dr %u\n", __FUNCTION__, dr);
1269                 return X86EMUL_UNHANDLEABLE;
1270         }
1271 }
1272
1273 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
1274 {
1275         unsigned long mask = (ctxt->mode == X86EMUL_MODE_PROT64) ? ~0ULL : ~0U;
1276         int exception;
1277
1278         kvm_x86_ops->set_dr(ctxt->vcpu, dr, value & mask, &exception);
1279         if (exception) {
1280                 /* FIXME: better handling */
1281                 return X86EMUL_UNHANDLEABLE;
1282         }
1283         return X86EMUL_CONTINUE;
1284 }
1285
1286 void kvm_report_emulation_failure(struct kvm_vcpu *vcpu, const char *context)
1287 {
1288         static int reported;
1289         u8 opcodes[4];
1290         unsigned long rip = vcpu->rip;
1291         unsigned long rip_linear;
1292
1293         rip_linear = rip + get_segment_base(vcpu, VCPU_SREG_CS);
1294
1295         if (reported)
1296                 return;
1297
1298         emulator_read_std(rip_linear, (void *)opcodes, 4, vcpu);
1299
1300         printk(KERN_ERR "emulation failed (%s) rip %lx %02x %02x %02x %02x\n",
1301                context, rip, opcodes[0], opcodes[1], opcodes[2], opcodes[3]);
1302         reported = 1;
1303 }
1304 EXPORT_SYMBOL_GPL(kvm_report_emulation_failure);
1305
1306 struct x86_emulate_ops emulate_ops = {
1307         .read_std            = emulator_read_std,
1308         .write_std           = emulator_write_std,
1309         .read_emulated       = emulator_read_emulated,
1310         .write_emulated      = emulator_write_emulated,
1311         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
1312 };
1313
1314 int emulate_instruction(struct kvm_vcpu *vcpu,
1315                         struct kvm_run *run,
1316                         unsigned long cr2,
1317                         u16 error_code,
1318                         int no_decode)
1319 {
1320         int r;
1321
1322         vcpu->mmio_fault_cr2 = cr2;
1323         kvm_x86_ops->cache_regs(vcpu);
1324
1325         vcpu->mmio_is_write = 0;
1326         vcpu->pio.string = 0;
1327
1328         if (!no_decode) {
1329                 int cs_db, cs_l;
1330                 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
1331
1332                 vcpu->emulate_ctxt.vcpu = vcpu;
1333                 vcpu->emulate_ctxt.eflags = kvm_x86_ops->get_rflags(vcpu);
1334                 vcpu->emulate_ctxt.cr2 = cr2;
1335                 vcpu->emulate_ctxt.mode =
1336                         (vcpu->emulate_ctxt.eflags & X86_EFLAGS_VM)
1337                         ? X86EMUL_MODE_REAL : cs_l
1338                         ? X86EMUL_MODE_PROT64 : cs_db
1339                         ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
1340
1341                 if (vcpu->emulate_ctxt.mode == X86EMUL_MODE_PROT64) {
1342                         vcpu->emulate_ctxt.cs_base = 0;
1343                         vcpu->emulate_ctxt.ds_base = 0;
1344                         vcpu->emulate_ctxt.es_base = 0;
1345                         vcpu->emulate_ctxt.ss_base = 0;
1346                 } else {
1347                         vcpu->emulate_ctxt.cs_base =
1348                                         get_segment_base(vcpu, VCPU_SREG_CS);
1349                         vcpu->emulate_ctxt.ds_base =
1350                                         get_segment_base(vcpu, VCPU_SREG_DS);
1351                         vcpu->emulate_ctxt.es_base =
1352                                         get_segment_base(vcpu, VCPU_SREG_ES);
1353                         vcpu->emulate_ctxt.ss_base =
1354                                         get_segment_base(vcpu, VCPU_SREG_SS);
1355                 }
1356
1357                 vcpu->emulate_ctxt.gs_base =
1358                                         get_segment_base(vcpu, VCPU_SREG_GS);
1359                 vcpu->emulate_ctxt.fs_base =
1360                                         get_segment_base(vcpu, VCPU_SREG_FS);
1361
1362                 r = x86_decode_insn(&vcpu->emulate_ctxt, &emulate_ops);
1363                 if (r)  {
1364                         if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
1365                                 return EMULATE_DONE;
1366                         return EMULATE_FAIL;
1367                 }
1368         }
1369
1370         r = x86_emulate_insn(&vcpu->emulate_ctxt, &emulate_ops);
1371
1372         if (vcpu->pio.string)
1373                 return EMULATE_DO_MMIO;
1374
1375         if ((r || vcpu->mmio_is_write) && run) {
1376                 run->exit_reason = KVM_EXIT_MMIO;
1377                 run->mmio.phys_addr = vcpu->mmio_phys_addr;
1378                 memcpy(run->mmio.data, vcpu->mmio_data, 8);
1379                 run->mmio.len = vcpu->mmio_size;
1380                 run->mmio.is_write = vcpu->mmio_is_write;
1381         }
1382
1383         if (r) {
1384                 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
1385                         return EMULATE_DONE;
1386                 if (!vcpu->mmio_needed) {
1387                         kvm_report_emulation_failure(vcpu, "mmio");
1388                         return EMULATE_FAIL;
1389                 }
1390                 return EMULATE_DO_MMIO;
1391         }
1392
1393         kvm_x86_ops->decache_regs(vcpu);
1394         kvm_x86_ops->set_rflags(vcpu, vcpu->emulate_ctxt.eflags);
1395
1396         if (vcpu->mmio_is_write) {
1397                 vcpu->mmio_needed = 0;
1398                 return EMULATE_DO_MMIO;
1399         }
1400
1401         return EMULATE_DONE;
1402 }
1403 EXPORT_SYMBOL_GPL(emulate_instruction);
1404
1405 static void free_pio_guest_pages(struct kvm_vcpu *vcpu)
1406 {
1407         int i;
1408
1409         for (i = 0; i < ARRAY_SIZE(vcpu->pio.guest_pages); ++i)
1410                 if (vcpu->pio.guest_pages[i]) {
1411                         kvm_release_page(vcpu->pio.guest_pages[i]);
1412                         vcpu->pio.guest_pages[i] = NULL;
1413                 }
1414 }
1415
1416 static int pio_copy_data(struct kvm_vcpu *vcpu)
1417 {
1418         void *p = vcpu->pio_data;
1419         void *q;
1420         unsigned bytes;
1421         int nr_pages = vcpu->pio.guest_pages[1] ? 2 : 1;
1422
1423         q = vmap(vcpu->pio.guest_pages, nr_pages, VM_READ|VM_WRITE,
1424                  PAGE_KERNEL);
1425         if (!q) {
1426                 free_pio_guest_pages(vcpu);
1427                 return -ENOMEM;
1428         }
1429         q += vcpu->pio.guest_page_offset;
1430         bytes = vcpu->pio.size * vcpu->pio.cur_count;
1431         if (vcpu->pio.in)
1432                 memcpy(q, p, bytes);
1433         else
1434                 memcpy(p, q, bytes);
1435         q -= vcpu->pio.guest_page_offset;
1436         vunmap(q);
1437         free_pio_guest_pages(vcpu);
1438         return 0;
1439 }
1440
1441 int complete_pio(struct kvm_vcpu *vcpu)
1442 {
1443         struct kvm_pio_request *io = &vcpu->pio;
1444         long delta;
1445         int r;
1446
1447         kvm_x86_ops->cache_regs(vcpu);
1448
1449         if (!io->string) {
1450                 if (io->in)
1451                         memcpy(&vcpu->regs[VCPU_REGS_RAX], vcpu->pio_data,
1452                                io->size);
1453         } else {
1454                 if (io->in) {
1455                         r = pio_copy_data(vcpu);
1456                         if (r) {
1457                                 kvm_x86_ops->cache_regs(vcpu);
1458                                 return r;
1459                         }
1460                 }
1461
1462                 delta = 1;
1463                 if (io->rep) {
1464                         delta *= io->cur_count;
1465                         /*
1466                          * The size of the register should really depend on
1467                          * current address size.
1468                          */
1469                         vcpu->regs[VCPU_REGS_RCX] -= delta;
1470                 }
1471                 if (io->down)
1472                         delta = -delta;
1473                 delta *= io->size;
1474                 if (io->in)
1475                         vcpu->regs[VCPU_REGS_RDI] += delta;
1476                 else
1477                         vcpu->regs[VCPU_REGS_RSI] += delta;
1478         }
1479
1480         kvm_x86_ops->decache_regs(vcpu);
1481
1482         io->count -= io->cur_count;
1483         io->cur_count = 0;
1484
1485         return 0;
1486 }
1487
1488 static void kernel_pio(struct kvm_io_device *pio_dev,
1489                        struct kvm_vcpu *vcpu,
1490                        void *pd)
1491 {
1492         /* TODO: String I/O for in kernel device */
1493
1494         mutex_lock(&vcpu->kvm->lock);
1495         if (vcpu->pio.in)
1496                 kvm_iodevice_read(pio_dev, vcpu->pio.port,
1497                                   vcpu->pio.size,
1498                                   pd);
1499         else
1500                 kvm_iodevice_write(pio_dev, vcpu->pio.port,
1501                                    vcpu->pio.size,
1502                                    pd);
1503         mutex_unlock(&vcpu->kvm->lock);
1504 }
1505
1506 static void pio_string_write(struct kvm_io_device *pio_dev,
1507                              struct kvm_vcpu *vcpu)
1508 {
1509         struct kvm_pio_request *io = &vcpu->pio;
1510         void *pd = vcpu->pio_data;
1511         int i;
1512
1513         mutex_lock(&vcpu->kvm->lock);
1514         for (i = 0; i < io->cur_count; i++) {
1515                 kvm_iodevice_write(pio_dev, io->port,
1516                                    io->size,
1517                                    pd);
1518                 pd += io->size;
1519         }
1520         mutex_unlock(&vcpu->kvm->lock);
1521 }
1522
1523 static struct kvm_io_device *vcpu_find_pio_dev(struct kvm_vcpu *vcpu,
1524                                                gpa_t addr)
1525 {
1526         return kvm_io_bus_find_dev(&vcpu->kvm->pio_bus, addr);
1527 }
1528
1529 int kvm_emulate_pio(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
1530                   int size, unsigned port)
1531 {
1532         struct kvm_io_device *pio_dev;
1533
1534         vcpu->run->exit_reason = KVM_EXIT_IO;
1535         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
1536         vcpu->run->io.size = vcpu->pio.size = size;
1537         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
1538         vcpu->run->io.count = vcpu->pio.count = vcpu->pio.cur_count = 1;
1539         vcpu->run->io.port = vcpu->pio.port = port;
1540         vcpu->pio.in = in;
1541         vcpu->pio.string = 0;
1542         vcpu->pio.down = 0;
1543         vcpu->pio.guest_page_offset = 0;
1544         vcpu->pio.rep = 0;
1545
1546         kvm_x86_ops->cache_regs(vcpu);
1547         memcpy(vcpu->pio_data, &vcpu->regs[VCPU_REGS_RAX], 4);
1548         kvm_x86_ops->decache_regs(vcpu);
1549
1550         kvm_x86_ops->skip_emulated_instruction(vcpu);
1551
1552         pio_dev = vcpu_find_pio_dev(vcpu, port);
1553         if (pio_dev) {
1554                 kernel_pio(pio_dev, vcpu, vcpu->pio_data);
1555                 complete_pio(vcpu);
1556                 return 1;
1557         }
1558         return 0;
1559 }
1560 EXPORT_SYMBOL_GPL(kvm_emulate_pio);
1561
1562 int kvm_emulate_pio_string(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
1563                   int size, unsigned long count, int down,
1564                   gva_t address, int rep, unsigned port)
1565 {
1566         unsigned now, in_page;
1567         int i, ret = 0;
1568         int nr_pages = 1;
1569         struct page *page;
1570         struct kvm_io_device *pio_dev;
1571
1572         vcpu->run->exit_reason = KVM_EXIT_IO;
1573         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
1574         vcpu->run->io.size = vcpu->pio.size = size;
1575         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
1576         vcpu->run->io.count = vcpu->pio.count = vcpu->pio.cur_count = count;
1577         vcpu->run->io.port = vcpu->pio.port = port;
1578         vcpu->pio.in = in;
1579         vcpu->pio.string = 1;
1580         vcpu->pio.down = down;
1581         vcpu->pio.guest_page_offset = offset_in_page(address);
1582         vcpu->pio.rep = rep;
1583
1584         if (!count) {
1585                 kvm_x86_ops->skip_emulated_instruction(vcpu);
1586                 return 1;
1587         }
1588
1589         if (!down)
1590                 in_page = PAGE_SIZE - offset_in_page(address);
1591         else
1592                 in_page = offset_in_page(address) + size;
1593         now = min(count, (unsigned long)in_page / size);
1594         if (!now) {
1595                 /*
1596                  * String I/O straddles page boundary.  Pin two guest pages
1597                  * so that we satisfy atomicity constraints.  Do just one
1598                  * transaction to avoid complexity.
1599                  */
1600                 nr_pages = 2;
1601                 now = 1;
1602         }
1603         if (down) {
1604                 /*
1605                  * String I/O in reverse.  Yuck.  Kill the guest, fix later.
1606                  */
1607                 pr_unimpl(vcpu, "guest string pio down\n");
1608                 inject_gp(vcpu);
1609                 return 1;
1610         }
1611         vcpu->run->io.count = now;
1612         vcpu->pio.cur_count = now;
1613
1614         if (vcpu->pio.cur_count == vcpu->pio.count)
1615                 kvm_x86_ops->skip_emulated_instruction(vcpu);
1616
1617         for (i = 0; i < nr_pages; ++i) {
1618                 mutex_lock(&vcpu->kvm->lock);
1619                 page = gva_to_page(vcpu, address + i * PAGE_SIZE);
1620                 vcpu->pio.guest_pages[i] = page;
1621                 mutex_unlock(&vcpu->kvm->lock);
1622                 if (!page) {
1623                         inject_gp(vcpu);
1624                         free_pio_guest_pages(vcpu);
1625                         return 1;
1626                 }
1627         }
1628
1629         pio_dev = vcpu_find_pio_dev(vcpu, port);
1630         if (!vcpu->pio.in) {
1631                 /* string PIO write */
1632                 ret = pio_copy_data(vcpu);
1633                 if (ret >= 0 && pio_dev) {
1634                         pio_string_write(pio_dev, vcpu);
1635                         complete_pio(vcpu);
1636                         if (vcpu->pio.count == 0)
1637                                 ret = 1;
1638                 }
1639         } else if (pio_dev)
1640                 pr_unimpl(vcpu, "no string pio read support yet, "
1641                        "port %x size %d count %ld\n",
1642                         port, size, count);
1643
1644         return ret;
1645 }
1646 EXPORT_SYMBOL_GPL(kvm_emulate_pio_string);
1647
1648 __init void kvm_arch_init(void)
1649 {
1650         kvm_init_msr_list();
1651 }
1652
1653 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
1654 {
1655         ++vcpu->stat.halt_exits;
1656         if (irqchip_in_kernel(vcpu->kvm)) {
1657                 vcpu->mp_state = VCPU_MP_STATE_HALTED;
1658                 kvm_vcpu_block(vcpu);
1659                 if (vcpu->mp_state != VCPU_MP_STATE_RUNNABLE)
1660                         return -EINTR;
1661                 return 1;
1662         } else {
1663                 vcpu->run->exit_reason = KVM_EXIT_HLT;
1664                 return 0;
1665         }
1666 }
1667 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
1668
1669 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
1670 {
1671         unsigned long nr, a0, a1, a2, a3, ret;
1672
1673         kvm_x86_ops->cache_regs(vcpu);
1674
1675         nr = vcpu->regs[VCPU_REGS_RAX];
1676         a0 = vcpu->regs[VCPU_REGS_RBX];
1677         a1 = vcpu->regs[VCPU_REGS_RCX];
1678         a2 = vcpu->regs[VCPU_REGS_RDX];
1679         a3 = vcpu->regs[VCPU_REGS_RSI];
1680
1681         if (!is_long_mode(vcpu)) {
1682                 nr &= 0xFFFFFFFF;
1683                 a0 &= 0xFFFFFFFF;
1684                 a1 &= 0xFFFFFFFF;
1685                 a2 &= 0xFFFFFFFF;
1686                 a3 &= 0xFFFFFFFF;
1687         }
1688
1689         switch (nr) {
1690         default:
1691                 ret = -KVM_ENOSYS;
1692                 break;
1693         }
1694         vcpu->regs[VCPU_REGS_RAX] = ret;
1695         kvm_x86_ops->decache_regs(vcpu);
1696         return 0;
1697 }
1698 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
1699
1700 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
1701 {
1702         char instruction[3];
1703         int ret = 0;
1704
1705         mutex_lock(&vcpu->kvm->lock);
1706
1707         /*
1708          * Blow out the MMU to ensure that no other VCPU has an active mapping
1709          * to ensure that the updated hypercall appears atomically across all
1710          * VCPUs.
1711          */
1712         kvm_mmu_zap_all(vcpu->kvm);
1713
1714         kvm_x86_ops->cache_regs(vcpu);
1715         kvm_x86_ops->patch_hypercall(vcpu, instruction);
1716         if (emulator_write_emulated(vcpu->rip, instruction, 3, vcpu)
1717             != X86EMUL_CONTINUE)
1718                 ret = -EFAULT;
1719
1720         mutex_unlock(&vcpu->kvm->lock);
1721
1722         return ret;
1723 }
1724
1725 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
1726 {
1727         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
1728 }
1729
1730 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
1731 {
1732         struct descriptor_table dt = { limit, base };
1733
1734         kvm_x86_ops->set_gdt(vcpu, &dt);
1735 }
1736
1737 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
1738 {
1739         struct descriptor_table dt = { limit, base };
1740
1741         kvm_x86_ops->set_idt(vcpu, &dt);
1742 }
1743
1744 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
1745                    unsigned long *rflags)
1746 {
1747         lmsw(vcpu, msw);
1748         *rflags = kvm_x86_ops->get_rflags(vcpu);
1749 }
1750
1751 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
1752 {
1753         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
1754         switch (cr) {
1755         case 0:
1756                 return vcpu->cr0;
1757         case 2:
1758                 return vcpu->cr2;
1759         case 3:
1760                 return vcpu->cr3;
1761         case 4:
1762                 return vcpu->cr4;
1763         default:
1764                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __FUNCTION__, cr);
1765                 return 0;
1766         }
1767 }
1768
1769 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
1770                      unsigned long *rflags)
1771 {
1772         switch (cr) {
1773         case 0:
1774                 set_cr0(vcpu, mk_cr_64(vcpu->cr0, val));
1775                 *rflags = kvm_x86_ops->get_rflags(vcpu);
1776                 break;
1777         case 2:
1778                 vcpu->cr2 = val;
1779                 break;
1780         case 3:
1781                 set_cr3(vcpu, val);
1782                 break;
1783         case 4:
1784                 set_cr4(vcpu, mk_cr_64(vcpu->cr4, val));
1785                 break;
1786         default:
1787                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __FUNCTION__, cr);
1788         }
1789 }
1790
1791 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
1792 {
1793         int i;
1794         u32 function;
1795         struct kvm_cpuid_entry *e, *best;
1796
1797         kvm_x86_ops->cache_regs(vcpu);
1798         function = vcpu->regs[VCPU_REGS_RAX];
1799         vcpu->regs[VCPU_REGS_RAX] = 0;
1800         vcpu->regs[VCPU_REGS_RBX] = 0;
1801         vcpu->regs[VCPU_REGS_RCX] = 0;
1802         vcpu->regs[VCPU_REGS_RDX] = 0;
1803         best = NULL;
1804         for (i = 0; i < vcpu->cpuid_nent; ++i) {
1805                 e = &vcpu->cpuid_entries[i];
1806                 if (e->function == function) {
1807                         best = e;
1808                         break;
1809                 }
1810                 /*
1811                  * Both basic or both extended?
1812                  */
1813                 if (((e->function ^ function) & 0x80000000) == 0)
1814                         if (!best || e->function > best->function)
1815                                 best = e;
1816         }
1817         if (best) {
1818                 vcpu->regs[VCPU_REGS_RAX] = best->eax;
1819                 vcpu->regs[VCPU_REGS_RBX] = best->ebx;
1820                 vcpu->regs[VCPU_REGS_RCX] = best->ecx;
1821                 vcpu->regs[VCPU_REGS_RDX] = best->edx;
1822         }
1823         kvm_x86_ops->decache_regs(vcpu);
1824         kvm_x86_ops->skip_emulated_instruction(vcpu);
1825 }
1826 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
1827
1828 /*
1829  * Check if userspace requested an interrupt window, and that the
1830  * interrupt window is open.
1831  *
1832  * No need to exit to userspace if we already have an interrupt queued.
1833  */
1834 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu,
1835                                           struct kvm_run *kvm_run)
1836 {
1837         return (!vcpu->irq_summary &&
1838                 kvm_run->request_interrupt_window &&
1839                 vcpu->interrupt_window_open &&
1840                 (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF));
1841 }
1842
1843 static void post_kvm_run_save(struct kvm_vcpu *vcpu,
1844                               struct kvm_run *kvm_run)
1845 {
1846         kvm_run->if_flag = (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
1847         kvm_run->cr8 = get_cr8(vcpu);
1848         kvm_run->apic_base = kvm_get_apic_base(vcpu);
1849         if (irqchip_in_kernel(vcpu->kvm))
1850                 kvm_run->ready_for_interrupt_injection = 1;
1851         else
1852                 kvm_run->ready_for_interrupt_injection =
1853                                         (vcpu->interrupt_window_open &&
1854                                          vcpu->irq_summary == 0);
1855 }
1856
1857 static int __vcpu_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
1858 {
1859         int r;
1860
1861         if (unlikely(vcpu->mp_state == VCPU_MP_STATE_SIPI_RECEIVED)) {
1862                 pr_debug("vcpu %d received sipi with vector # %x\n",
1863                        vcpu->vcpu_id, vcpu->sipi_vector);
1864                 kvm_lapic_reset(vcpu);
1865                 r = kvm_x86_ops->vcpu_reset(vcpu);
1866                 if (r)
1867                         return r;
1868                 vcpu->mp_state = VCPU_MP_STATE_RUNNABLE;
1869         }
1870
1871 preempted:
1872         if (vcpu->guest_debug.enabled)
1873                 kvm_x86_ops->guest_debug_pre(vcpu);
1874
1875 again:
1876         r = kvm_mmu_reload(vcpu);
1877         if (unlikely(r))
1878                 goto out;
1879
1880         kvm_inject_pending_timer_irqs(vcpu);
1881
1882         preempt_disable();
1883
1884         kvm_x86_ops->prepare_guest_switch(vcpu);
1885         kvm_load_guest_fpu(vcpu);
1886
1887         local_irq_disable();
1888
1889         if (signal_pending(current)) {
1890                 local_irq_enable();
1891                 preempt_enable();
1892                 r = -EINTR;
1893                 kvm_run->exit_reason = KVM_EXIT_INTR;
1894                 ++vcpu->stat.signal_exits;
1895                 goto out;
1896         }
1897
1898         if (irqchip_in_kernel(vcpu->kvm))
1899                 kvm_x86_ops->inject_pending_irq(vcpu);
1900         else if (!vcpu->mmio_read_completed)
1901                 kvm_x86_ops->inject_pending_vectors(vcpu, kvm_run);
1902
1903         vcpu->guest_mode = 1;
1904         kvm_guest_enter();
1905
1906         if (vcpu->requests)
1907                 if (test_and_clear_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
1908                         kvm_x86_ops->tlb_flush(vcpu);
1909
1910         kvm_x86_ops->run(vcpu, kvm_run);
1911
1912         vcpu->guest_mode = 0;
1913         local_irq_enable();
1914
1915         ++vcpu->stat.exits;
1916
1917         /*
1918          * We must have an instruction between local_irq_enable() and
1919          * kvm_guest_exit(), so the timer interrupt isn't delayed by
1920          * the interrupt shadow.  The stat.exits increment will do nicely.
1921          * But we need to prevent reordering, hence this barrier():
1922          */
1923         barrier();
1924
1925         kvm_guest_exit();
1926
1927         preempt_enable();
1928
1929         /*
1930          * Profile KVM exit RIPs:
1931          */
1932         if (unlikely(prof_on == KVM_PROFILING)) {
1933                 kvm_x86_ops->cache_regs(vcpu);
1934                 profile_hit(KVM_PROFILING, (void *)vcpu->rip);
1935         }
1936
1937         r = kvm_x86_ops->handle_exit(kvm_run, vcpu);
1938
1939         if (r > 0) {
1940                 if (dm_request_for_irq_injection(vcpu, kvm_run)) {
1941                         r = -EINTR;
1942                         kvm_run->exit_reason = KVM_EXIT_INTR;
1943                         ++vcpu->stat.request_irq_exits;
1944                         goto out;
1945                 }
1946                 if (!need_resched()) {
1947                         ++vcpu->stat.light_exits;
1948                         goto again;
1949                 }
1950         }
1951
1952 out:
1953         if (r > 0) {
1954                 kvm_resched(vcpu);
1955                 goto preempted;
1956         }
1957
1958         post_kvm_run_save(vcpu, kvm_run);
1959
1960         return r;
1961 }
1962
1963 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
1964 {
1965         int r;
1966         sigset_t sigsaved;
1967
1968         vcpu_load(vcpu);
1969
1970         if (unlikely(vcpu->mp_state == VCPU_MP_STATE_UNINITIALIZED)) {
1971                 kvm_vcpu_block(vcpu);
1972                 vcpu_put(vcpu);
1973                 return -EAGAIN;
1974         }
1975
1976         if (vcpu->sigset_active)
1977                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
1978
1979         /* re-sync apic's tpr */
1980         if (!irqchip_in_kernel(vcpu->kvm))
1981                 set_cr8(vcpu, kvm_run->cr8);
1982
1983         if (vcpu->pio.cur_count) {
1984                 r = complete_pio(vcpu);
1985                 if (r)
1986                         goto out;
1987         }
1988 #if CONFIG_HAS_IOMEM
1989         if (vcpu->mmio_needed) {
1990                 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
1991                 vcpu->mmio_read_completed = 1;
1992                 vcpu->mmio_needed = 0;
1993                 r = emulate_instruction(vcpu, kvm_run,
1994                                         vcpu->mmio_fault_cr2, 0, 1);
1995                 if (r == EMULATE_DO_MMIO) {
1996                         /*
1997                          * Read-modify-write.  Back to userspace.
1998                          */
1999                         r = 0;
2000                         goto out;
2001                 }
2002         }
2003 #endif
2004         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL) {
2005                 kvm_x86_ops->cache_regs(vcpu);
2006                 vcpu->regs[VCPU_REGS_RAX] = kvm_run->hypercall.ret;
2007                 kvm_x86_ops->decache_regs(vcpu);
2008         }
2009
2010         r = __vcpu_run(vcpu, kvm_run);
2011
2012 out:
2013         if (vcpu->sigset_active)
2014                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
2015
2016         vcpu_put(vcpu);
2017         return r;
2018 }
2019
2020 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
2021 {
2022         vcpu_load(vcpu);
2023
2024         kvm_x86_ops->cache_regs(vcpu);
2025
2026         regs->rax = vcpu->regs[VCPU_REGS_RAX];
2027         regs->rbx = vcpu->regs[VCPU_REGS_RBX];
2028         regs->rcx = vcpu->regs[VCPU_REGS_RCX];
2029         regs->rdx = vcpu->regs[VCPU_REGS_RDX];
2030         regs->rsi = vcpu->regs[VCPU_REGS_RSI];
2031         regs->rdi = vcpu->regs[VCPU_REGS_RDI];
2032         regs->rsp = vcpu->regs[VCPU_REGS_RSP];
2033         regs->rbp = vcpu->regs[VCPU_REGS_RBP];
2034 #ifdef CONFIG_X86_64
2035         regs->r8 = vcpu->regs[VCPU_REGS_R8];
2036         regs->r9 = vcpu->regs[VCPU_REGS_R9];
2037         regs->r10 = vcpu->regs[VCPU_REGS_R10];
2038         regs->r11 = vcpu->regs[VCPU_REGS_R11];
2039         regs->r12 = vcpu->regs[VCPU_REGS_R12];
2040         regs->r13 = vcpu->regs[VCPU_REGS_R13];
2041         regs->r14 = vcpu->regs[VCPU_REGS_R14];
2042         regs->r15 = vcpu->regs[VCPU_REGS_R15];
2043 #endif
2044
2045         regs->rip = vcpu->rip;
2046         regs->rflags = kvm_x86_ops->get_rflags(vcpu);
2047
2048         /*
2049          * Don't leak debug flags in case they were set for guest debugging
2050          */
2051         if (vcpu->guest_debug.enabled && vcpu->guest_debug.singlestep)
2052                 regs->rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
2053
2054         vcpu_put(vcpu);
2055
2056         return 0;
2057 }
2058
2059 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
2060 {
2061         vcpu_load(vcpu);
2062
2063         vcpu->regs[VCPU_REGS_RAX] = regs->rax;
2064         vcpu->regs[VCPU_REGS_RBX] = regs->rbx;
2065         vcpu->regs[VCPU_REGS_RCX] = regs->rcx;
2066         vcpu->regs[VCPU_REGS_RDX] = regs->rdx;
2067         vcpu->regs[VCPU_REGS_RSI] = regs->rsi;
2068         vcpu->regs[VCPU_REGS_RDI] = regs->rdi;
2069         vcpu->regs[VCPU_REGS_RSP] = regs->rsp;
2070         vcpu->regs[VCPU_REGS_RBP] = regs->rbp;
2071 #ifdef CONFIG_X86_64
2072         vcpu->regs[VCPU_REGS_R8] = regs->r8;
2073         vcpu->regs[VCPU_REGS_R9] = regs->r9;
2074         vcpu->regs[VCPU_REGS_R10] = regs->r10;
2075         vcpu->regs[VCPU_REGS_R11] = regs->r11;
2076         vcpu->regs[VCPU_REGS_R12] = regs->r12;
2077         vcpu->regs[VCPU_REGS_R13] = regs->r13;
2078         vcpu->regs[VCPU_REGS_R14] = regs->r14;
2079         vcpu->regs[VCPU_REGS_R15] = regs->r15;
2080 #endif
2081
2082         vcpu->rip = regs->rip;
2083         kvm_x86_ops->set_rflags(vcpu, regs->rflags);
2084
2085         kvm_x86_ops->decache_regs(vcpu);
2086
2087         vcpu_put(vcpu);
2088
2089         return 0;
2090 }
2091
2092 static void get_segment(struct kvm_vcpu *vcpu,
2093                         struct kvm_segment *var, int seg)
2094 {
2095         return kvm_x86_ops->get_segment(vcpu, var, seg);
2096 }
2097
2098 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
2099 {
2100         struct kvm_segment cs;
2101
2102         get_segment(vcpu, &cs, VCPU_SREG_CS);
2103         *db = cs.db;
2104         *l = cs.l;
2105 }
2106 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
2107
2108 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
2109                                   struct kvm_sregs *sregs)
2110 {
2111         struct descriptor_table dt;
2112         int pending_vec;
2113
2114         vcpu_load(vcpu);
2115
2116         get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
2117         get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
2118         get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
2119         get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
2120         get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
2121         get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
2122
2123         get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
2124         get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
2125
2126         kvm_x86_ops->get_idt(vcpu, &dt);
2127         sregs->idt.limit = dt.limit;
2128         sregs->idt.base = dt.base;
2129         kvm_x86_ops->get_gdt(vcpu, &dt);
2130         sregs->gdt.limit = dt.limit;
2131         sregs->gdt.base = dt.base;
2132
2133         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2134         sregs->cr0 = vcpu->cr0;
2135         sregs->cr2 = vcpu->cr2;
2136         sregs->cr3 = vcpu->cr3;
2137         sregs->cr4 = vcpu->cr4;
2138         sregs->cr8 = get_cr8(vcpu);
2139         sregs->efer = vcpu->shadow_efer;
2140         sregs->apic_base = kvm_get_apic_base(vcpu);
2141
2142         if (irqchip_in_kernel(vcpu->kvm)) {
2143                 memset(sregs->interrupt_bitmap, 0,
2144                        sizeof sregs->interrupt_bitmap);
2145                 pending_vec = kvm_x86_ops->get_irq(vcpu);
2146                 if (pending_vec >= 0)
2147                         set_bit(pending_vec,
2148                                 (unsigned long *)sregs->interrupt_bitmap);
2149         } else
2150                 memcpy(sregs->interrupt_bitmap, vcpu->irq_pending,
2151                        sizeof sregs->interrupt_bitmap);
2152
2153         vcpu_put(vcpu);
2154
2155         return 0;
2156 }
2157
2158 static void set_segment(struct kvm_vcpu *vcpu,
2159                         struct kvm_segment *var, int seg)
2160 {
2161         return kvm_x86_ops->set_segment(vcpu, var, seg);
2162 }
2163
2164 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
2165                                   struct kvm_sregs *sregs)
2166 {
2167         int mmu_reset_needed = 0;
2168         int i, pending_vec, max_bits;
2169         struct descriptor_table dt;
2170
2171         vcpu_load(vcpu);
2172
2173         dt.limit = sregs->idt.limit;
2174         dt.base = sregs->idt.base;
2175         kvm_x86_ops->set_idt(vcpu, &dt);
2176         dt.limit = sregs->gdt.limit;
2177         dt.base = sregs->gdt.base;
2178         kvm_x86_ops->set_gdt(vcpu, &dt);
2179
2180         vcpu->cr2 = sregs->cr2;
2181         mmu_reset_needed |= vcpu->cr3 != sregs->cr3;
2182         vcpu->cr3 = sregs->cr3;
2183
2184         set_cr8(vcpu, sregs->cr8);
2185
2186         mmu_reset_needed |= vcpu->shadow_efer != sregs->efer;
2187 #ifdef CONFIG_X86_64
2188         kvm_x86_ops->set_efer(vcpu, sregs->efer);
2189 #endif
2190         kvm_set_apic_base(vcpu, sregs->apic_base);
2191
2192         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2193
2194         mmu_reset_needed |= vcpu->cr0 != sregs->cr0;
2195         vcpu->cr0 = sregs->cr0;
2196         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
2197
2198         mmu_reset_needed |= vcpu->cr4 != sregs->cr4;
2199         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
2200         if (!is_long_mode(vcpu) && is_pae(vcpu))
2201                 load_pdptrs(vcpu, vcpu->cr3);
2202
2203         if (mmu_reset_needed)
2204                 kvm_mmu_reset_context(vcpu);
2205
2206         if (!irqchip_in_kernel(vcpu->kvm)) {
2207                 memcpy(vcpu->irq_pending, sregs->interrupt_bitmap,
2208                        sizeof vcpu->irq_pending);
2209                 vcpu->irq_summary = 0;
2210                 for (i = 0; i < ARRAY_SIZE(vcpu->irq_pending); ++i)
2211                         if (vcpu->irq_pending[i])
2212                                 __set_bit(i, &vcpu->irq_summary);
2213         } else {
2214                 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
2215                 pending_vec = find_first_bit(
2216                         (const unsigned long *)sregs->interrupt_bitmap,
2217                         max_bits);
2218                 /* Only pending external irq is handled here */
2219                 if (pending_vec < max_bits) {
2220                         kvm_x86_ops->set_irq(vcpu, pending_vec);
2221                         pr_debug("Set back pending irq %d\n",
2222                                  pending_vec);
2223                 }
2224         }
2225
2226         set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
2227         set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
2228         set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
2229         set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
2230         set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
2231         set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
2232
2233         set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
2234         set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
2235
2236         vcpu_put(vcpu);
2237
2238         return 0;
2239 }
2240
2241 int kvm_arch_vcpu_ioctl_debug_guest(struct kvm_vcpu *vcpu,
2242                                     struct kvm_debug_guest *dbg)
2243 {
2244         int r;
2245
2246         vcpu_load(vcpu);
2247
2248         r = kvm_x86_ops->set_guest_debug(vcpu, dbg);
2249
2250         vcpu_put(vcpu);
2251
2252         return r;
2253 }
2254
2255 /*
2256  * fxsave fpu state.  Taken from x86_64/processor.h.  To be killed when
2257  * we have asm/x86/processor.h
2258  */
2259 struct fxsave {
2260         u16     cwd;
2261         u16     swd;
2262         u16     twd;
2263         u16     fop;
2264         u64     rip;
2265         u64     rdp;
2266         u32     mxcsr;
2267         u32     mxcsr_mask;
2268         u32     st_space[32];   /* 8*16 bytes for each FP-reg = 128 bytes */
2269 #ifdef CONFIG_X86_64
2270         u32     xmm_space[64];  /* 16*16 bytes for each XMM-reg = 256 bytes */
2271 #else
2272         u32     xmm_space[32];  /* 8*16 bytes for each XMM-reg = 128 bytes */
2273 #endif
2274 };
2275
2276 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2277 {
2278         struct fxsave *fxsave = (struct fxsave *)&vcpu->guest_fx_image;
2279
2280         vcpu_load(vcpu);
2281
2282         memcpy(fpu->fpr, fxsave->st_space, 128);
2283         fpu->fcw = fxsave->cwd;
2284         fpu->fsw = fxsave->swd;
2285         fpu->ftwx = fxsave->twd;
2286         fpu->last_opcode = fxsave->fop;
2287         fpu->last_ip = fxsave->rip;
2288         fpu->last_dp = fxsave->rdp;
2289         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
2290
2291         vcpu_put(vcpu);
2292
2293         return 0;
2294 }
2295
2296 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
2297 {
2298         struct fxsave *fxsave = (struct fxsave *)&vcpu->guest_fx_image;
2299
2300         vcpu_load(vcpu);
2301
2302         memcpy(fxsave->st_space, fpu->fpr, 128);
2303         fxsave->cwd = fpu->fcw;
2304         fxsave->swd = fpu->fsw;
2305         fxsave->twd = fpu->ftwx;
2306         fxsave->fop = fpu->last_opcode;
2307         fxsave->rip = fpu->last_ip;
2308         fxsave->rdp = fpu->last_dp;
2309         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
2310
2311         vcpu_put(vcpu);
2312
2313         return 0;
2314 }
2315
2316 void fx_init(struct kvm_vcpu *vcpu)
2317 {
2318         unsigned after_mxcsr_mask;
2319
2320         /* Initialize guest FPU by resetting ours and saving into guest's */
2321         preempt_disable();
2322         fx_save(&vcpu->host_fx_image);
2323         fpu_init();
2324         fx_save(&vcpu->guest_fx_image);
2325         fx_restore(&vcpu->host_fx_image);
2326         preempt_enable();
2327
2328         vcpu->cr0 |= X86_CR0_ET;
2329         after_mxcsr_mask = offsetof(struct i387_fxsave_struct, st_space);
2330         vcpu->guest_fx_image.mxcsr = 0x1f80;
2331         memset((void *)&vcpu->guest_fx_image + after_mxcsr_mask,
2332                0, sizeof(struct i387_fxsave_struct) - after_mxcsr_mask);
2333 }
2334 EXPORT_SYMBOL_GPL(fx_init);
2335
2336 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
2337 {
2338         if (!vcpu->fpu_active || vcpu->guest_fpu_loaded)
2339                 return;
2340
2341         vcpu->guest_fpu_loaded = 1;
2342         fx_save(&vcpu->host_fx_image);
2343         fx_restore(&vcpu->guest_fx_image);
2344 }
2345 EXPORT_SYMBOL_GPL(kvm_load_guest_fpu);
2346
2347 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
2348 {
2349         if (!vcpu->guest_fpu_loaded)
2350                 return;
2351
2352         vcpu->guest_fpu_loaded = 0;
2353         fx_save(&vcpu->guest_fx_image);
2354         fx_restore(&vcpu->host_fx_image);
2355 }
2356 EXPORT_SYMBOL_GPL(kvm_put_guest_fpu);
2357
2358 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
2359 {
2360         kvm_x86_ops->vcpu_free(vcpu);
2361 }
2362
2363 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
2364                                                 unsigned int id)
2365 {
2366         int r;
2367         struct kvm_vcpu *vcpu = kvm_x86_ops->vcpu_create(kvm, id);
2368
2369         if (IS_ERR(vcpu)) {
2370                 r = -ENOMEM;
2371                 goto fail;
2372         }
2373
2374         /* We do fxsave: this must be aligned. */
2375         BUG_ON((unsigned long)&vcpu->host_fx_image & 0xF);
2376
2377         vcpu_load(vcpu);
2378         r = kvm_arch_vcpu_reset(vcpu);
2379         if (r == 0)
2380                 r = kvm_mmu_setup(vcpu);
2381         vcpu_put(vcpu);
2382         if (r < 0)
2383                 goto free_vcpu;
2384
2385         return vcpu;
2386 free_vcpu:
2387         kvm_x86_ops->vcpu_free(vcpu);
2388 fail:
2389         return ERR_PTR(r);
2390 }
2391
2392 void kvm_arch_vcpu_destory(struct kvm_vcpu *vcpu)
2393 {
2394         vcpu_load(vcpu);
2395         kvm_mmu_unload(vcpu);
2396         vcpu_put(vcpu);
2397
2398         kvm_x86_ops->vcpu_free(vcpu);
2399 }
2400
2401 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
2402 {
2403         return kvm_x86_ops->vcpu_reset(vcpu);
2404 }
2405
2406 void kvm_arch_hardware_enable(void *garbage)
2407 {
2408         kvm_x86_ops->hardware_enable(garbage);
2409 }
2410
2411 void kvm_arch_hardware_disable(void *garbage)
2412 {
2413         kvm_x86_ops->hardware_disable(garbage);
2414 }
2415
2416 int kvm_arch_hardware_setup(void)
2417 {
2418         return kvm_x86_ops->hardware_setup();
2419 }
2420
2421 void kvm_arch_hardware_unsetup(void)
2422 {
2423         kvm_x86_ops->hardware_unsetup();
2424 }
2425
2426 void kvm_arch_check_processor_compat(void *rtn)
2427 {
2428         kvm_x86_ops->check_processor_compatibility(rtn);
2429 }
2430
2431 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
2432 {
2433         struct page *page;
2434         struct kvm *kvm;
2435         int r;
2436
2437         BUG_ON(vcpu->kvm == NULL);
2438         kvm = vcpu->kvm;
2439
2440         vcpu->mmu.root_hpa = INVALID_PAGE;
2441         if (!irqchip_in_kernel(kvm) || vcpu->vcpu_id == 0)
2442                 vcpu->mp_state = VCPU_MP_STATE_RUNNABLE;
2443         else
2444                 vcpu->mp_state = VCPU_MP_STATE_UNINITIALIZED;
2445
2446         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
2447         if (!page) {
2448                 r = -ENOMEM;
2449                 goto fail;
2450         }
2451         vcpu->pio_data = page_address(page);
2452
2453         r = kvm_mmu_create(vcpu);
2454         if (r < 0)
2455                 goto fail_free_pio_data;
2456
2457         if (irqchip_in_kernel(kvm)) {
2458                 r = kvm_create_lapic(vcpu);
2459                 if (r < 0)
2460                         goto fail_mmu_destroy;
2461         }
2462
2463         return 0;
2464
2465 fail_mmu_destroy:
2466         kvm_mmu_destroy(vcpu);
2467 fail_free_pio_data:
2468         free_page((unsigned long)vcpu->pio_data);
2469 fail:
2470         return r;
2471 }
2472
2473 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
2474 {
2475         kvm_free_lapic(vcpu);
2476         kvm_mmu_destroy(vcpu);
2477         free_page((unsigned long)vcpu->pio_data);
2478 }