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