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