]> pilppa.org Git - linux-2.6-omap-h63xx.git/blob - arch/x86/kvm/x86.c
KVM: VMX: Add list of potentially locally cached vcpus
[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 /*
821  * Make sure that a cpu that is being hot-unplugged does not have any vcpus
822  * cached on it.
823  */
824 void decache_vcpus_on_cpu(int cpu)
825 {
826 }
827
828 int kvm_dev_ioctl_check_extension(long ext)
829 {
830         int r;
831
832         switch (ext) {
833         case KVM_CAP_IRQCHIP:
834         case KVM_CAP_HLT:
835         case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
836         case KVM_CAP_USER_MEMORY:
837         case KVM_CAP_SET_TSS_ADDR:
838         case KVM_CAP_EXT_CPUID:
839         case KVM_CAP_CLOCKSOURCE:
840         case KVM_CAP_PIT:
841         case KVM_CAP_NOP_IO_DELAY:
842         case KVM_CAP_MP_STATE:
843                 r = 1;
844                 break;
845         case KVM_CAP_VAPIC:
846                 r = !kvm_x86_ops->cpu_has_accelerated_tpr();
847                 break;
848         case KVM_CAP_NR_VCPUS:
849                 r = KVM_MAX_VCPUS;
850                 break;
851         case KVM_CAP_NR_MEMSLOTS:
852                 r = KVM_MEMORY_SLOTS;
853                 break;
854         case KVM_CAP_PV_MMU:
855                 r = !tdp_enabled;
856                 break;
857         default:
858                 r = 0;
859                 break;
860         }
861         return r;
862
863 }
864
865 long kvm_arch_dev_ioctl(struct file *filp,
866                         unsigned int ioctl, unsigned long arg)
867 {
868         void __user *argp = (void __user *)arg;
869         long r;
870
871         switch (ioctl) {
872         case KVM_GET_MSR_INDEX_LIST: {
873                 struct kvm_msr_list __user *user_msr_list = argp;
874                 struct kvm_msr_list msr_list;
875                 unsigned n;
876
877                 r = -EFAULT;
878                 if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
879                         goto out;
880                 n = msr_list.nmsrs;
881                 msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
882                 if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
883                         goto out;
884                 r = -E2BIG;
885                 if (n < num_msrs_to_save)
886                         goto out;
887                 r = -EFAULT;
888                 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
889                                  num_msrs_to_save * sizeof(u32)))
890                         goto out;
891                 if (copy_to_user(user_msr_list->indices
892                                  + num_msrs_to_save * sizeof(u32),
893                                  &emulated_msrs,
894                                  ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
895                         goto out;
896                 r = 0;
897                 break;
898         }
899         case KVM_GET_SUPPORTED_CPUID: {
900                 struct kvm_cpuid2 __user *cpuid_arg = argp;
901                 struct kvm_cpuid2 cpuid;
902
903                 r = -EFAULT;
904                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
905                         goto out;
906                 r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
907                         cpuid_arg->entries);
908                 if (r)
909                         goto out;
910
911                 r = -EFAULT;
912                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
913                         goto out;
914                 r = 0;
915                 break;
916         }
917         default:
918                 r = -EINVAL;
919         }
920 out:
921         return r;
922 }
923
924 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
925 {
926         kvm_x86_ops->vcpu_load(vcpu, cpu);
927         kvm_write_guest_time(vcpu);
928 }
929
930 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
931 {
932         kvm_x86_ops->vcpu_put(vcpu);
933         kvm_put_guest_fpu(vcpu);
934 }
935
936 static int is_efer_nx(void)
937 {
938         u64 efer;
939
940         rdmsrl(MSR_EFER, efer);
941         return efer & EFER_NX;
942 }
943
944 static void cpuid_fix_nx_cap(struct kvm_vcpu *vcpu)
945 {
946         int i;
947         struct kvm_cpuid_entry2 *e, *entry;
948
949         entry = NULL;
950         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
951                 e = &vcpu->arch.cpuid_entries[i];
952                 if (e->function == 0x80000001) {
953                         entry = e;
954                         break;
955                 }
956         }
957         if (entry && (entry->edx & (1 << 20)) && !is_efer_nx()) {
958                 entry->edx &= ~(1 << 20);
959                 printk(KERN_INFO "kvm: guest NX capability removed\n");
960         }
961 }
962
963 /* when an old userspace process fills a new kernel module */
964 static int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
965                                     struct kvm_cpuid *cpuid,
966                                     struct kvm_cpuid_entry __user *entries)
967 {
968         int r, i;
969         struct kvm_cpuid_entry *cpuid_entries;
970
971         r = -E2BIG;
972         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
973                 goto out;
974         r = -ENOMEM;
975         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry) * cpuid->nent);
976         if (!cpuid_entries)
977                 goto out;
978         r = -EFAULT;
979         if (copy_from_user(cpuid_entries, entries,
980                            cpuid->nent * sizeof(struct kvm_cpuid_entry)))
981                 goto out_free;
982         for (i = 0; i < cpuid->nent; i++) {
983                 vcpu->arch.cpuid_entries[i].function = cpuid_entries[i].function;
984                 vcpu->arch.cpuid_entries[i].eax = cpuid_entries[i].eax;
985                 vcpu->arch.cpuid_entries[i].ebx = cpuid_entries[i].ebx;
986                 vcpu->arch.cpuid_entries[i].ecx = cpuid_entries[i].ecx;
987                 vcpu->arch.cpuid_entries[i].edx = cpuid_entries[i].edx;
988                 vcpu->arch.cpuid_entries[i].index = 0;
989                 vcpu->arch.cpuid_entries[i].flags = 0;
990                 vcpu->arch.cpuid_entries[i].padding[0] = 0;
991                 vcpu->arch.cpuid_entries[i].padding[1] = 0;
992                 vcpu->arch.cpuid_entries[i].padding[2] = 0;
993         }
994         vcpu->arch.cpuid_nent = cpuid->nent;
995         cpuid_fix_nx_cap(vcpu);
996         r = 0;
997
998 out_free:
999         vfree(cpuid_entries);
1000 out:
1001         return r;
1002 }
1003
1004 static int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
1005                                     struct kvm_cpuid2 *cpuid,
1006                                     struct kvm_cpuid_entry2 __user *entries)
1007 {
1008         int r;
1009
1010         r = -E2BIG;
1011         if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1012                 goto out;
1013         r = -EFAULT;
1014         if (copy_from_user(&vcpu->arch.cpuid_entries, entries,
1015                            cpuid->nent * sizeof(struct kvm_cpuid_entry2)))
1016                 goto out;
1017         vcpu->arch.cpuid_nent = cpuid->nent;
1018         return 0;
1019
1020 out:
1021         return r;
1022 }
1023
1024 static int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
1025                                     struct kvm_cpuid2 *cpuid,
1026                                     struct kvm_cpuid_entry2 __user *entries)
1027 {
1028         int r;
1029
1030         r = -E2BIG;
1031         if (cpuid->nent < vcpu->arch.cpuid_nent)
1032                 goto out;
1033         r = -EFAULT;
1034         if (copy_to_user(entries, &vcpu->arch.cpuid_entries,
1035                            vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
1036                 goto out;
1037         return 0;
1038
1039 out:
1040         cpuid->nent = vcpu->arch.cpuid_nent;
1041         return r;
1042 }
1043
1044 static inline u32 bit(int bitno)
1045 {
1046         return 1 << (bitno & 31);
1047 }
1048
1049 static void do_cpuid_1_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1050                           u32 index)
1051 {
1052         entry->function = function;
1053         entry->index = index;
1054         cpuid_count(entry->function, entry->index,
1055                 &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
1056         entry->flags = 0;
1057 }
1058
1059 static void do_cpuid_ent(struct kvm_cpuid_entry2 *entry, u32 function,
1060                          u32 index, int *nent, int maxnent)
1061 {
1062         const u32 kvm_supported_word0_x86_features = bit(X86_FEATURE_FPU) |
1063                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
1064                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
1065                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
1066                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
1067                 bit(X86_FEATURE_SEP) | bit(X86_FEATURE_PGE) |
1068                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
1069                 bit(X86_FEATURE_CLFLSH) | bit(X86_FEATURE_MMX) |
1070                 bit(X86_FEATURE_FXSR) | bit(X86_FEATURE_XMM) |
1071                 bit(X86_FEATURE_XMM2) | bit(X86_FEATURE_SELFSNOOP);
1072         const u32 kvm_supported_word1_x86_features = bit(X86_FEATURE_FPU) |
1073                 bit(X86_FEATURE_VME) | bit(X86_FEATURE_DE) |
1074                 bit(X86_FEATURE_PSE) | bit(X86_FEATURE_TSC) |
1075                 bit(X86_FEATURE_MSR) | bit(X86_FEATURE_PAE) |
1076                 bit(X86_FEATURE_CX8) | bit(X86_FEATURE_APIC) |
1077                 bit(X86_FEATURE_PGE) |
1078                 bit(X86_FEATURE_CMOV) | bit(X86_FEATURE_PSE36) |
1079                 bit(X86_FEATURE_MMX) | bit(X86_FEATURE_FXSR) |
1080                 bit(X86_FEATURE_SYSCALL) |
1081                 (bit(X86_FEATURE_NX) && is_efer_nx()) |
1082 #ifdef CONFIG_X86_64
1083                 bit(X86_FEATURE_LM) |
1084 #endif
1085                 bit(X86_FEATURE_MMXEXT) |
1086                 bit(X86_FEATURE_3DNOWEXT) |
1087                 bit(X86_FEATURE_3DNOW);
1088         const u32 kvm_supported_word3_x86_features =
1089                 bit(X86_FEATURE_XMM3) | bit(X86_FEATURE_CX16);
1090         const u32 kvm_supported_word6_x86_features =
1091                 bit(X86_FEATURE_LAHF_LM) | bit(X86_FEATURE_CMP_LEGACY);
1092
1093         /* all func 2 cpuid_count() should be called on the same cpu */
1094         get_cpu();
1095         do_cpuid_1_ent(entry, function, index);
1096         ++*nent;
1097
1098         switch (function) {
1099         case 0:
1100                 entry->eax = min(entry->eax, (u32)0xb);
1101                 break;
1102         case 1:
1103                 entry->edx &= kvm_supported_word0_x86_features;
1104                 entry->ecx &= kvm_supported_word3_x86_features;
1105                 break;
1106         /* function 2 entries are STATEFUL. That is, repeated cpuid commands
1107          * may return different values. This forces us to get_cpu() before
1108          * issuing the first command, and also to emulate this annoying behavior
1109          * in kvm_emulate_cpuid() using KVM_CPUID_FLAG_STATE_READ_NEXT */
1110         case 2: {
1111                 int t, times = entry->eax & 0xff;
1112
1113                 entry->flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1114                 for (t = 1; t < times && *nent < maxnent; ++t) {
1115                         do_cpuid_1_ent(&entry[t], function, 0);
1116                         entry[t].flags |= KVM_CPUID_FLAG_STATEFUL_FUNC;
1117                         ++*nent;
1118                 }
1119                 break;
1120         }
1121         /* function 4 and 0xb have additional index. */
1122         case 4: {
1123                 int i, cache_type;
1124
1125                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1126                 /* read more entries until cache_type is zero */
1127                 for (i = 1; *nent < maxnent; ++i) {
1128                         cache_type = entry[i - 1].eax & 0x1f;
1129                         if (!cache_type)
1130                                 break;
1131                         do_cpuid_1_ent(&entry[i], function, i);
1132                         entry[i].flags |=
1133                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1134                         ++*nent;
1135                 }
1136                 break;
1137         }
1138         case 0xb: {
1139                 int i, level_type;
1140
1141                 entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1142                 /* read more entries until level_type is zero */
1143                 for (i = 1; *nent < maxnent; ++i) {
1144                         level_type = entry[i - 1].ecx & 0xff;
1145                         if (!level_type)
1146                                 break;
1147                         do_cpuid_1_ent(&entry[i], function, i);
1148                         entry[i].flags |=
1149                                KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1150                         ++*nent;
1151                 }
1152                 break;
1153         }
1154         case 0x80000000:
1155                 entry->eax = min(entry->eax, 0x8000001a);
1156                 break;
1157         case 0x80000001:
1158                 entry->edx &= kvm_supported_word1_x86_features;
1159                 entry->ecx &= kvm_supported_word6_x86_features;
1160                 break;
1161         }
1162         put_cpu();
1163 }
1164
1165 static int kvm_dev_ioctl_get_supported_cpuid(struct kvm_cpuid2 *cpuid,
1166                                     struct kvm_cpuid_entry2 __user *entries)
1167 {
1168         struct kvm_cpuid_entry2 *cpuid_entries;
1169         int limit, nent = 0, r = -E2BIG;
1170         u32 func;
1171
1172         if (cpuid->nent < 1)
1173                 goto out;
1174         r = -ENOMEM;
1175         cpuid_entries = vmalloc(sizeof(struct kvm_cpuid_entry2) * cpuid->nent);
1176         if (!cpuid_entries)
1177                 goto out;
1178
1179         do_cpuid_ent(&cpuid_entries[0], 0, 0, &nent, cpuid->nent);
1180         limit = cpuid_entries[0].eax;
1181         for (func = 1; func <= limit && nent < cpuid->nent; ++func)
1182                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1183                                 &nent, cpuid->nent);
1184         r = -E2BIG;
1185         if (nent >= cpuid->nent)
1186                 goto out_free;
1187
1188         do_cpuid_ent(&cpuid_entries[nent], 0x80000000, 0, &nent, cpuid->nent);
1189         limit = cpuid_entries[nent - 1].eax;
1190         for (func = 0x80000001; func <= limit && nent < cpuid->nent; ++func)
1191                 do_cpuid_ent(&cpuid_entries[nent], func, 0,
1192                                &nent, cpuid->nent);
1193         r = -EFAULT;
1194         if (copy_to_user(entries, cpuid_entries,
1195                         nent * sizeof(struct kvm_cpuid_entry2)))
1196                 goto out_free;
1197         cpuid->nent = nent;
1198         r = 0;
1199
1200 out_free:
1201         vfree(cpuid_entries);
1202 out:
1203         return r;
1204 }
1205
1206 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
1207                                     struct kvm_lapic_state *s)
1208 {
1209         vcpu_load(vcpu);
1210         memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
1211         vcpu_put(vcpu);
1212
1213         return 0;
1214 }
1215
1216 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
1217                                     struct kvm_lapic_state *s)
1218 {
1219         vcpu_load(vcpu);
1220         memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
1221         kvm_apic_post_state_restore(vcpu);
1222         vcpu_put(vcpu);
1223
1224         return 0;
1225 }
1226
1227 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
1228                                     struct kvm_interrupt *irq)
1229 {
1230         if (irq->irq < 0 || irq->irq >= 256)
1231                 return -EINVAL;
1232         if (irqchip_in_kernel(vcpu->kvm))
1233                 return -ENXIO;
1234         vcpu_load(vcpu);
1235
1236         set_bit(irq->irq, vcpu->arch.irq_pending);
1237         set_bit(irq->irq / BITS_PER_LONG, &vcpu->arch.irq_summary);
1238
1239         vcpu_put(vcpu);
1240
1241         return 0;
1242 }
1243
1244 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
1245                                            struct kvm_tpr_access_ctl *tac)
1246 {
1247         if (tac->flags)
1248                 return -EINVAL;
1249         vcpu->arch.tpr_access_reporting = !!tac->enabled;
1250         return 0;
1251 }
1252
1253 long kvm_arch_vcpu_ioctl(struct file *filp,
1254                          unsigned int ioctl, unsigned long arg)
1255 {
1256         struct kvm_vcpu *vcpu = filp->private_data;
1257         void __user *argp = (void __user *)arg;
1258         int r;
1259
1260         switch (ioctl) {
1261         case KVM_GET_LAPIC: {
1262                 struct kvm_lapic_state lapic;
1263
1264                 memset(&lapic, 0, sizeof lapic);
1265                 r = kvm_vcpu_ioctl_get_lapic(vcpu, &lapic);
1266                 if (r)
1267                         goto out;
1268                 r = -EFAULT;
1269                 if (copy_to_user(argp, &lapic, sizeof lapic))
1270                         goto out;
1271                 r = 0;
1272                 break;
1273         }
1274         case KVM_SET_LAPIC: {
1275                 struct kvm_lapic_state lapic;
1276
1277                 r = -EFAULT;
1278                 if (copy_from_user(&lapic, argp, sizeof lapic))
1279                         goto out;
1280                 r = kvm_vcpu_ioctl_set_lapic(vcpu, &lapic);;
1281                 if (r)
1282                         goto out;
1283                 r = 0;
1284                 break;
1285         }
1286         case KVM_INTERRUPT: {
1287                 struct kvm_interrupt irq;
1288
1289                 r = -EFAULT;
1290                 if (copy_from_user(&irq, argp, sizeof irq))
1291                         goto out;
1292                 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
1293                 if (r)
1294                         goto out;
1295                 r = 0;
1296                 break;
1297         }
1298         case KVM_SET_CPUID: {
1299                 struct kvm_cpuid __user *cpuid_arg = argp;
1300                 struct kvm_cpuid cpuid;
1301
1302                 r = -EFAULT;
1303                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1304                         goto out;
1305                 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
1306                 if (r)
1307                         goto out;
1308                 break;
1309         }
1310         case KVM_SET_CPUID2: {
1311                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1312                 struct kvm_cpuid2 cpuid;
1313
1314                 r = -EFAULT;
1315                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1316                         goto out;
1317                 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
1318                                 cpuid_arg->entries);
1319                 if (r)
1320                         goto out;
1321                 break;
1322         }
1323         case KVM_GET_CPUID2: {
1324                 struct kvm_cpuid2 __user *cpuid_arg = argp;
1325                 struct kvm_cpuid2 cpuid;
1326
1327                 r = -EFAULT;
1328                 if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
1329                         goto out;
1330                 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
1331                                 cpuid_arg->entries);
1332                 if (r)
1333                         goto out;
1334                 r = -EFAULT;
1335                 if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
1336                         goto out;
1337                 r = 0;
1338                 break;
1339         }
1340         case KVM_GET_MSRS:
1341                 r = msr_io(vcpu, argp, kvm_get_msr, 1);
1342                 break;
1343         case KVM_SET_MSRS:
1344                 r = msr_io(vcpu, argp, do_set_msr, 0);
1345                 break;
1346         case KVM_TPR_ACCESS_REPORTING: {
1347                 struct kvm_tpr_access_ctl tac;
1348
1349                 r = -EFAULT;
1350                 if (copy_from_user(&tac, argp, sizeof tac))
1351                         goto out;
1352                 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
1353                 if (r)
1354                         goto out;
1355                 r = -EFAULT;
1356                 if (copy_to_user(argp, &tac, sizeof tac))
1357                         goto out;
1358                 r = 0;
1359                 break;
1360         };
1361         case KVM_SET_VAPIC_ADDR: {
1362                 struct kvm_vapic_addr va;
1363
1364                 r = -EINVAL;
1365                 if (!irqchip_in_kernel(vcpu->kvm))
1366                         goto out;
1367                 r = -EFAULT;
1368                 if (copy_from_user(&va, argp, sizeof va))
1369                         goto out;
1370                 r = 0;
1371                 kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
1372                 break;
1373         }
1374         default:
1375                 r = -EINVAL;
1376         }
1377 out:
1378         return r;
1379 }
1380
1381 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
1382 {
1383         int ret;
1384
1385         if (addr > (unsigned int)(-3 * PAGE_SIZE))
1386                 return -1;
1387         ret = kvm_x86_ops->set_tss_addr(kvm, addr);
1388         return ret;
1389 }
1390
1391 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
1392                                           u32 kvm_nr_mmu_pages)
1393 {
1394         if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
1395                 return -EINVAL;
1396
1397         down_write(&kvm->slots_lock);
1398
1399         kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
1400         kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
1401
1402         up_write(&kvm->slots_lock);
1403         return 0;
1404 }
1405
1406 static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
1407 {
1408         return kvm->arch.n_alloc_mmu_pages;
1409 }
1410
1411 gfn_t unalias_gfn(struct kvm *kvm, gfn_t gfn)
1412 {
1413         int i;
1414         struct kvm_mem_alias *alias;
1415
1416         for (i = 0; i < kvm->arch.naliases; ++i) {
1417                 alias = &kvm->arch.aliases[i];
1418                 if (gfn >= alias->base_gfn
1419                     && gfn < alias->base_gfn + alias->npages)
1420                         return alias->target_gfn + gfn - alias->base_gfn;
1421         }
1422         return gfn;
1423 }
1424
1425 /*
1426  * Set a new alias region.  Aliases map a portion of physical memory into
1427  * another portion.  This is useful for memory windows, for example the PC
1428  * VGA region.
1429  */
1430 static int kvm_vm_ioctl_set_memory_alias(struct kvm *kvm,
1431                                          struct kvm_memory_alias *alias)
1432 {
1433         int r, n;
1434         struct kvm_mem_alias *p;
1435
1436         r = -EINVAL;
1437         /* General sanity checks */
1438         if (alias->memory_size & (PAGE_SIZE - 1))
1439                 goto out;
1440         if (alias->guest_phys_addr & (PAGE_SIZE - 1))
1441                 goto out;
1442         if (alias->slot >= KVM_ALIAS_SLOTS)
1443                 goto out;
1444         if (alias->guest_phys_addr + alias->memory_size
1445             < alias->guest_phys_addr)
1446                 goto out;
1447         if (alias->target_phys_addr + alias->memory_size
1448             < alias->target_phys_addr)
1449                 goto out;
1450
1451         down_write(&kvm->slots_lock);
1452
1453         p = &kvm->arch.aliases[alias->slot];
1454         p->base_gfn = alias->guest_phys_addr >> PAGE_SHIFT;
1455         p->npages = alias->memory_size >> PAGE_SHIFT;
1456         p->target_gfn = alias->target_phys_addr >> PAGE_SHIFT;
1457
1458         for (n = KVM_ALIAS_SLOTS; n > 0; --n)
1459                 if (kvm->arch.aliases[n - 1].npages)
1460                         break;
1461         kvm->arch.naliases = n;
1462
1463         kvm_mmu_zap_all(kvm);
1464
1465         up_write(&kvm->slots_lock);
1466
1467         return 0;
1468
1469 out:
1470         return r;
1471 }
1472
1473 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1474 {
1475         int r;
1476
1477         r = 0;
1478         switch (chip->chip_id) {
1479         case KVM_IRQCHIP_PIC_MASTER:
1480                 memcpy(&chip->chip.pic,
1481                         &pic_irqchip(kvm)->pics[0],
1482                         sizeof(struct kvm_pic_state));
1483                 break;
1484         case KVM_IRQCHIP_PIC_SLAVE:
1485                 memcpy(&chip->chip.pic,
1486                         &pic_irqchip(kvm)->pics[1],
1487                         sizeof(struct kvm_pic_state));
1488                 break;
1489         case KVM_IRQCHIP_IOAPIC:
1490                 memcpy(&chip->chip.ioapic,
1491                         ioapic_irqchip(kvm),
1492                         sizeof(struct kvm_ioapic_state));
1493                 break;
1494         default:
1495                 r = -EINVAL;
1496                 break;
1497         }
1498         return r;
1499 }
1500
1501 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
1502 {
1503         int r;
1504
1505         r = 0;
1506         switch (chip->chip_id) {
1507         case KVM_IRQCHIP_PIC_MASTER:
1508                 memcpy(&pic_irqchip(kvm)->pics[0],
1509                         &chip->chip.pic,
1510                         sizeof(struct kvm_pic_state));
1511                 break;
1512         case KVM_IRQCHIP_PIC_SLAVE:
1513                 memcpy(&pic_irqchip(kvm)->pics[1],
1514                         &chip->chip.pic,
1515                         sizeof(struct kvm_pic_state));
1516                 break;
1517         case KVM_IRQCHIP_IOAPIC:
1518                 memcpy(ioapic_irqchip(kvm),
1519                         &chip->chip.ioapic,
1520                         sizeof(struct kvm_ioapic_state));
1521                 break;
1522         default:
1523                 r = -EINVAL;
1524                 break;
1525         }
1526         kvm_pic_update_irq(pic_irqchip(kvm));
1527         return r;
1528 }
1529
1530 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
1531 {
1532         int r = 0;
1533
1534         memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
1535         return r;
1536 }
1537
1538 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
1539 {
1540         int r = 0;
1541
1542         memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
1543         kvm_pit_load_count(kvm, 0, ps->channels[0].count);
1544         return r;
1545 }
1546
1547 /*
1548  * Get (and clear) the dirty memory log for a memory slot.
1549  */
1550 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1551                                       struct kvm_dirty_log *log)
1552 {
1553         int r;
1554         int n;
1555         struct kvm_memory_slot *memslot;
1556         int is_dirty = 0;
1557
1558         down_write(&kvm->slots_lock);
1559
1560         r = kvm_get_dirty_log(kvm, log, &is_dirty);
1561         if (r)
1562                 goto out;
1563
1564         /* If nothing is dirty, don't bother messing with page tables. */
1565         if (is_dirty) {
1566                 kvm_mmu_slot_remove_write_access(kvm, log->slot);
1567                 kvm_flush_remote_tlbs(kvm);
1568                 memslot = &kvm->memslots[log->slot];
1569                 n = ALIGN(memslot->npages, BITS_PER_LONG) / 8;
1570                 memset(memslot->dirty_bitmap, 0, n);
1571         }
1572         r = 0;
1573 out:
1574         up_write(&kvm->slots_lock);
1575         return r;
1576 }
1577
1578 long kvm_arch_vm_ioctl(struct file *filp,
1579                        unsigned int ioctl, unsigned long arg)
1580 {
1581         struct kvm *kvm = filp->private_data;
1582         void __user *argp = (void __user *)arg;
1583         int r = -EINVAL;
1584
1585         switch (ioctl) {
1586         case KVM_SET_TSS_ADDR:
1587                 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
1588                 if (r < 0)
1589                         goto out;
1590                 break;
1591         case KVM_SET_MEMORY_REGION: {
1592                 struct kvm_memory_region kvm_mem;
1593                 struct kvm_userspace_memory_region kvm_userspace_mem;
1594
1595                 r = -EFAULT;
1596                 if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
1597                         goto out;
1598                 kvm_userspace_mem.slot = kvm_mem.slot;
1599                 kvm_userspace_mem.flags = kvm_mem.flags;
1600                 kvm_userspace_mem.guest_phys_addr = kvm_mem.guest_phys_addr;
1601                 kvm_userspace_mem.memory_size = kvm_mem.memory_size;
1602                 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 0);
1603                 if (r)
1604                         goto out;
1605                 break;
1606         }
1607         case KVM_SET_NR_MMU_PAGES:
1608                 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
1609                 if (r)
1610                         goto out;
1611                 break;
1612         case KVM_GET_NR_MMU_PAGES:
1613                 r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
1614                 break;
1615         case KVM_SET_MEMORY_ALIAS: {
1616                 struct kvm_memory_alias alias;
1617
1618                 r = -EFAULT;
1619                 if (copy_from_user(&alias, argp, sizeof alias))
1620                         goto out;
1621                 r = kvm_vm_ioctl_set_memory_alias(kvm, &alias);
1622                 if (r)
1623                         goto out;
1624                 break;
1625         }
1626         case KVM_CREATE_IRQCHIP:
1627                 r = -ENOMEM;
1628                 kvm->arch.vpic = kvm_create_pic(kvm);
1629                 if (kvm->arch.vpic) {
1630                         r = kvm_ioapic_init(kvm);
1631                         if (r) {
1632                                 kfree(kvm->arch.vpic);
1633                                 kvm->arch.vpic = NULL;
1634                                 goto out;
1635                         }
1636                 } else
1637                         goto out;
1638                 break;
1639         case KVM_CREATE_PIT:
1640                 r = -ENOMEM;
1641                 kvm->arch.vpit = kvm_create_pit(kvm);
1642                 if (kvm->arch.vpit)
1643                         r = 0;
1644                 break;
1645         case KVM_IRQ_LINE: {
1646                 struct kvm_irq_level irq_event;
1647
1648                 r = -EFAULT;
1649                 if (copy_from_user(&irq_event, argp, sizeof irq_event))
1650                         goto out;
1651                 if (irqchip_in_kernel(kvm)) {
1652                         mutex_lock(&kvm->lock);
1653                         if (irq_event.irq < 16)
1654                                 kvm_pic_set_irq(pic_irqchip(kvm),
1655                                         irq_event.irq,
1656                                         irq_event.level);
1657                         kvm_ioapic_set_irq(kvm->arch.vioapic,
1658                                         irq_event.irq,
1659                                         irq_event.level);
1660                         mutex_unlock(&kvm->lock);
1661                         r = 0;
1662                 }
1663                 break;
1664         }
1665         case KVM_GET_IRQCHIP: {
1666                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1667                 struct kvm_irqchip chip;
1668
1669                 r = -EFAULT;
1670                 if (copy_from_user(&chip, argp, sizeof chip))
1671                         goto out;
1672                 r = -ENXIO;
1673                 if (!irqchip_in_kernel(kvm))
1674                         goto out;
1675                 r = kvm_vm_ioctl_get_irqchip(kvm, &chip);
1676                 if (r)
1677                         goto out;
1678                 r = -EFAULT;
1679                 if (copy_to_user(argp, &chip, sizeof chip))
1680                         goto out;
1681                 r = 0;
1682                 break;
1683         }
1684         case KVM_SET_IRQCHIP: {
1685                 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
1686                 struct kvm_irqchip chip;
1687
1688                 r = -EFAULT;
1689                 if (copy_from_user(&chip, argp, sizeof chip))
1690                         goto out;
1691                 r = -ENXIO;
1692                 if (!irqchip_in_kernel(kvm))
1693                         goto out;
1694                 r = kvm_vm_ioctl_set_irqchip(kvm, &chip);
1695                 if (r)
1696                         goto out;
1697                 r = 0;
1698                 break;
1699         }
1700         case KVM_GET_PIT: {
1701                 struct kvm_pit_state ps;
1702                 r = -EFAULT;
1703                 if (copy_from_user(&ps, argp, sizeof ps))
1704                         goto out;
1705                 r = -ENXIO;
1706                 if (!kvm->arch.vpit)
1707                         goto out;
1708                 r = kvm_vm_ioctl_get_pit(kvm, &ps);
1709                 if (r)
1710                         goto out;
1711                 r = -EFAULT;
1712                 if (copy_to_user(argp, &ps, sizeof ps))
1713                         goto out;
1714                 r = 0;
1715                 break;
1716         }
1717         case KVM_SET_PIT: {
1718                 struct kvm_pit_state ps;
1719                 r = -EFAULT;
1720                 if (copy_from_user(&ps, argp, sizeof ps))
1721                         goto out;
1722                 r = -ENXIO;
1723                 if (!kvm->arch.vpit)
1724                         goto out;
1725                 r = kvm_vm_ioctl_set_pit(kvm, &ps);
1726                 if (r)
1727                         goto out;
1728                 r = 0;
1729                 break;
1730         }
1731         default:
1732                 ;
1733         }
1734 out:
1735         return r;
1736 }
1737
1738 static void kvm_init_msr_list(void)
1739 {
1740         u32 dummy[2];
1741         unsigned i, j;
1742
1743         for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
1744                 if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
1745                         continue;
1746                 if (j < i)
1747                         msrs_to_save[j] = msrs_to_save[i];
1748                 j++;
1749         }
1750         num_msrs_to_save = j;
1751 }
1752
1753 /*
1754  * Only apic need an MMIO device hook, so shortcut now..
1755  */
1756 static struct kvm_io_device *vcpu_find_pervcpu_dev(struct kvm_vcpu *vcpu,
1757                                                 gpa_t addr)
1758 {
1759         struct kvm_io_device *dev;
1760
1761         if (vcpu->arch.apic) {
1762                 dev = &vcpu->arch.apic->dev;
1763                 if (dev->in_range(dev, addr))
1764                         return dev;
1765         }
1766         return NULL;
1767 }
1768
1769
1770 static struct kvm_io_device *vcpu_find_mmio_dev(struct kvm_vcpu *vcpu,
1771                                                 gpa_t addr)
1772 {
1773         struct kvm_io_device *dev;
1774
1775         dev = vcpu_find_pervcpu_dev(vcpu, addr);
1776         if (dev == NULL)
1777                 dev = kvm_io_bus_find_dev(&vcpu->kvm->mmio_bus, addr);
1778         return dev;
1779 }
1780
1781 int emulator_read_std(unsigned long addr,
1782                              void *val,
1783                              unsigned int bytes,
1784                              struct kvm_vcpu *vcpu)
1785 {
1786         void *data = val;
1787         int r = X86EMUL_CONTINUE;
1788
1789         while (bytes) {
1790                 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1791                 unsigned offset = addr & (PAGE_SIZE-1);
1792                 unsigned tocopy = min(bytes, (unsigned)PAGE_SIZE - offset);
1793                 int ret;
1794
1795                 if (gpa == UNMAPPED_GVA) {
1796                         r = X86EMUL_PROPAGATE_FAULT;
1797                         goto out;
1798                 }
1799                 ret = kvm_read_guest(vcpu->kvm, gpa, data, tocopy);
1800                 if (ret < 0) {
1801                         r = X86EMUL_UNHANDLEABLE;
1802                         goto out;
1803                 }
1804
1805                 bytes -= tocopy;
1806                 data += tocopy;
1807                 addr += tocopy;
1808         }
1809 out:
1810         return r;
1811 }
1812 EXPORT_SYMBOL_GPL(emulator_read_std);
1813
1814 static int emulator_read_emulated(unsigned long addr,
1815                                   void *val,
1816                                   unsigned int bytes,
1817                                   struct kvm_vcpu *vcpu)
1818 {
1819         struct kvm_io_device *mmio_dev;
1820         gpa_t                 gpa;
1821
1822         if (vcpu->mmio_read_completed) {
1823                 memcpy(val, vcpu->mmio_data, bytes);
1824                 vcpu->mmio_read_completed = 0;
1825                 return X86EMUL_CONTINUE;
1826         }
1827
1828         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1829
1830         /* For APIC access vmexit */
1831         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1832                 goto mmio;
1833
1834         if (emulator_read_std(addr, val, bytes, vcpu)
1835                         == X86EMUL_CONTINUE)
1836                 return X86EMUL_CONTINUE;
1837         if (gpa == UNMAPPED_GVA)
1838                 return X86EMUL_PROPAGATE_FAULT;
1839
1840 mmio:
1841         /*
1842          * Is this MMIO handled locally?
1843          */
1844         mutex_lock(&vcpu->kvm->lock);
1845         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa);
1846         if (mmio_dev) {
1847                 kvm_iodevice_read(mmio_dev, gpa, bytes, val);
1848                 mutex_unlock(&vcpu->kvm->lock);
1849                 return X86EMUL_CONTINUE;
1850         }
1851         mutex_unlock(&vcpu->kvm->lock);
1852
1853         vcpu->mmio_needed = 1;
1854         vcpu->mmio_phys_addr = gpa;
1855         vcpu->mmio_size = bytes;
1856         vcpu->mmio_is_write = 0;
1857
1858         return X86EMUL_UNHANDLEABLE;
1859 }
1860
1861 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
1862                           const void *val, int bytes)
1863 {
1864         int ret;
1865
1866         ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
1867         if (ret < 0)
1868                 return 0;
1869         kvm_mmu_pte_write(vcpu, gpa, val, bytes);
1870         return 1;
1871 }
1872
1873 static int emulator_write_emulated_onepage(unsigned long addr,
1874                                            const void *val,
1875                                            unsigned int bytes,
1876                                            struct kvm_vcpu *vcpu)
1877 {
1878         struct kvm_io_device *mmio_dev;
1879         gpa_t                 gpa;
1880
1881         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1882
1883         if (gpa == UNMAPPED_GVA) {
1884                 kvm_inject_page_fault(vcpu, addr, 2);
1885                 return X86EMUL_PROPAGATE_FAULT;
1886         }
1887
1888         /* For APIC access vmexit */
1889         if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1890                 goto mmio;
1891
1892         if (emulator_write_phys(vcpu, gpa, val, bytes))
1893                 return X86EMUL_CONTINUE;
1894
1895 mmio:
1896         /*
1897          * Is this MMIO handled locally?
1898          */
1899         mutex_lock(&vcpu->kvm->lock);
1900         mmio_dev = vcpu_find_mmio_dev(vcpu, gpa);
1901         if (mmio_dev) {
1902                 kvm_iodevice_write(mmio_dev, gpa, bytes, val);
1903                 mutex_unlock(&vcpu->kvm->lock);
1904                 return X86EMUL_CONTINUE;
1905         }
1906         mutex_unlock(&vcpu->kvm->lock);
1907
1908         vcpu->mmio_needed = 1;
1909         vcpu->mmio_phys_addr = gpa;
1910         vcpu->mmio_size = bytes;
1911         vcpu->mmio_is_write = 1;
1912         memcpy(vcpu->mmio_data, val, bytes);
1913
1914         return X86EMUL_CONTINUE;
1915 }
1916
1917 int emulator_write_emulated(unsigned long addr,
1918                                    const void *val,
1919                                    unsigned int bytes,
1920                                    struct kvm_vcpu *vcpu)
1921 {
1922         /* Crossing a page boundary? */
1923         if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
1924                 int rc, now;
1925
1926                 now = -addr & ~PAGE_MASK;
1927                 rc = emulator_write_emulated_onepage(addr, val, now, vcpu);
1928                 if (rc != X86EMUL_CONTINUE)
1929                         return rc;
1930                 addr += now;
1931                 val += now;
1932                 bytes -= now;
1933         }
1934         return emulator_write_emulated_onepage(addr, val, bytes, vcpu);
1935 }
1936 EXPORT_SYMBOL_GPL(emulator_write_emulated);
1937
1938 static int emulator_cmpxchg_emulated(unsigned long addr,
1939                                      const void *old,
1940                                      const void *new,
1941                                      unsigned int bytes,
1942                                      struct kvm_vcpu *vcpu)
1943 {
1944         static int reported;
1945
1946         if (!reported) {
1947                 reported = 1;
1948                 printk(KERN_WARNING "kvm: emulating exchange as write\n");
1949         }
1950 #ifndef CONFIG_X86_64
1951         /* guests cmpxchg8b have to be emulated atomically */
1952         if (bytes == 8) {
1953                 gpa_t gpa;
1954                 struct page *page;
1955                 char *kaddr;
1956                 u64 val;
1957
1958                 gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, addr);
1959
1960                 if (gpa == UNMAPPED_GVA ||
1961                    (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
1962                         goto emul_write;
1963
1964                 if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
1965                         goto emul_write;
1966
1967                 val = *(u64 *)new;
1968
1969                 down_read(&current->mm->mmap_sem);
1970                 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
1971                 up_read(&current->mm->mmap_sem);
1972
1973                 kaddr = kmap_atomic(page, KM_USER0);
1974                 set_64bit((u64 *)(kaddr + offset_in_page(gpa)), val);
1975                 kunmap_atomic(kaddr, KM_USER0);
1976                 kvm_release_page_dirty(page);
1977         }
1978 emul_write:
1979 #endif
1980
1981         return emulator_write_emulated(addr, new, bytes, vcpu);
1982 }
1983
1984 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
1985 {
1986         return kvm_x86_ops->get_segment_base(vcpu, seg);
1987 }
1988
1989 int emulate_invlpg(struct kvm_vcpu *vcpu, gva_t address)
1990 {
1991         return X86EMUL_CONTINUE;
1992 }
1993
1994 int emulate_clts(struct kvm_vcpu *vcpu)
1995 {
1996         KVMTRACE_0D(CLTS, vcpu, handler);
1997         kvm_x86_ops->set_cr0(vcpu, vcpu->arch.cr0 & ~X86_CR0_TS);
1998         return X86EMUL_CONTINUE;
1999 }
2000
2001 int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
2002 {
2003         struct kvm_vcpu *vcpu = ctxt->vcpu;
2004
2005         switch (dr) {
2006         case 0 ... 3:
2007                 *dest = kvm_x86_ops->get_dr(vcpu, dr);
2008                 return X86EMUL_CONTINUE;
2009         default:
2010                 pr_unimpl(vcpu, "%s: unexpected dr %u\n", __func__, dr);
2011                 return X86EMUL_UNHANDLEABLE;
2012         }
2013 }
2014
2015 int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
2016 {
2017         unsigned long mask = (ctxt->mode == X86EMUL_MODE_PROT64) ? ~0ULL : ~0U;
2018         int exception;
2019
2020         kvm_x86_ops->set_dr(ctxt->vcpu, dr, value & mask, &exception);
2021         if (exception) {
2022                 /* FIXME: better handling */
2023                 return X86EMUL_UNHANDLEABLE;
2024         }
2025         return X86EMUL_CONTINUE;
2026 }
2027
2028 void kvm_report_emulation_failure(struct kvm_vcpu *vcpu, const char *context)
2029 {
2030         static int reported;
2031         u8 opcodes[4];
2032         unsigned long rip = vcpu->arch.rip;
2033         unsigned long rip_linear;
2034
2035         rip_linear = rip + get_segment_base(vcpu, VCPU_SREG_CS);
2036
2037         if (reported)
2038                 return;
2039
2040         emulator_read_std(rip_linear, (void *)opcodes, 4, vcpu);
2041
2042         printk(KERN_ERR "emulation failed (%s) rip %lx %02x %02x %02x %02x\n",
2043                context, rip, opcodes[0], opcodes[1], opcodes[2], opcodes[3]);
2044         reported = 1;
2045 }
2046 EXPORT_SYMBOL_GPL(kvm_report_emulation_failure);
2047
2048 static struct x86_emulate_ops emulate_ops = {
2049         .read_std            = emulator_read_std,
2050         .read_emulated       = emulator_read_emulated,
2051         .write_emulated      = emulator_write_emulated,
2052         .cmpxchg_emulated    = emulator_cmpxchg_emulated,
2053 };
2054
2055 int emulate_instruction(struct kvm_vcpu *vcpu,
2056                         struct kvm_run *run,
2057                         unsigned long cr2,
2058                         u16 error_code,
2059                         int emulation_type)
2060 {
2061         int r;
2062         struct decode_cache *c;
2063
2064         vcpu->arch.mmio_fault_cr2 = cr2;
2065         kvm_x86_ops->cache_regs(vcpu);
2066
2067         vcpu->mmio_is_write = 0;
2068         vcpu->arch.pio.string = 0;
2069
2070         if (!(emulation_type & EMULTYPE_NO_DECODE)) {
2071                 int cs_db, cs_l;
2072                 kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
2073
2074                 vcpu->arch.emulate_ctxt.vcpu = vcpu;
2075                 vcpu->arch.emulate_ctxt.eflags = kvm_x86_ops->get_rflags(vcpu);
2076                 vcpu->arch.emulate_ctxt.mode =
2077                         (vcpu->arch.emulate_ctxt.eflags & X86_EFLAGS_VM)
2078                         ? X86EMUL_MODE_REAL : cs_l
2079                         ? X86EMUL_MODE_PROT64 : cs_db
2080                         ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
2081
2082                 if (vcpu->arch.emulate_ctxt.mode == X86EMUL_MODE_PROT64) {
2083                         vcpu->arch.emulate_ctxt.cs_base = 0;
2084                         vcpu->arch.emulate_ctxt.ds_base = 0;
2085                         vcpu->arch.emulate_ctxt.es_base = 0;
2086                         vcpu->arch.emulate_ctxt.ss_base = 0;
2087                 } else {
2088                         vcpu->arch.emulate_ctxt.cs_base =
2089                                         get_segment_base(vcpu, VCPU_SREG_CS);
2090                         vcpu->arch.emulate_ctxt.ds_base =
2091                                         get_segment_base(vcpu, VCPU_SREG_DS);
2092                         vcpu->arch.emulate_ctxt.es_base =
2093                                         get_segment_base(vcpu, VCPU_SREG_ES);
2094                         vcpu->arch.emulate_ctxt.ss_base =
2095                                         get_segment_base(vcpu, VCPU_SREG_SS);
2096                 }
2097
2098                 vcpu->arch.emulate_ctxt.gs_base =
2099                                         get_segment_base(vcpu, VCPU_SREG_GS);
2100                 vcpu->arch.emulate_ctxt.fs_base =
2101                                         get_segment_base(vcpu, VCPU_SREG_FS);
2102
2103                 r = x86_decode_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
2104
2105                 /* Reject the instructions other than VMCALL/VMMCALL when
2106                  * try to emulate invalid opcode */
2107                 c = &vcpu->arch.emulate_ctxt.decode;
2108                 if ((emulation_type & EMULTYPE_TRAP_UD) &&
2109                     (!(c->twobyte && c->b == 0x01 &&
2110                       (c->modrm_reg == 0 || c->modrm_reg == 3) &&
2111                        c->modrm_mod == 3 && c->modrm_rm == 1)))
2112                         return EMULATE_FAIL;
2113
2114                 ++vcpu->stat.insn_emulation;
2115                 if (r)  {
2116                         ++vcpu->stat.insn_emulation_fail;
2117                         if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
2118                                 return EMULATE_DONE;
2119                         return EMULATE_FAIL;
2120                 }
2121         }
2122
2123         r = x86_emulate_insn(&vcpu->arch.emulate_ctxt, &emulate_ops);
2124
2125         if (vcpu->arch.pio.string)
2126                 return EMULATE_DO_MMIO;
2127
2128         if ((r || vcpu->mmio_is_write) && run) {
2129                 run->exit_reason = KVM_EXIT_MMIO;
2130                 run->mmio.phys_addr = vcpu->mmio_phys_addr;
2131                 memcpy(run->mmio.data, vcpu->mmio_data, 8);
2132                 run->mmio.len = vcpu->mmio_size;
2133                 run->mmio.is_write = vcpu->mmio_is_write;
2134         }
2135
2136         if (r) {
2137                 if (kvm_mmu_unprotect_page_virt(vcpu, cr2))
2138                         return EMULATE_DONE;
2139                 if (!vcpu->mmio_needed) {
2140                         kvm_report_emulation_failure(vcpu, "mmio");
2141                         return EMULATE_FAIL;
2142                 }
2143                 return EMULATE_DO_MMIO;
2144         }
2145
2146         kvm_x86_ops->decache_regs(vcpu);
2147         kvm_x86_ops->set_rflags(vcpu, vcpu->arch.emulate_ctxt.eflags);
2148
2149         if (vcpu->mmio_is_write) {
2150                 vcpu->mmio_needed = 0;
2151                 return EMULATE_DO_MMIO;
2152         }
2153
2154         return EMULATE_DONE;
2155 }
2156 EXPORT_SYMBOL_GPL(emulate_instruction);
2157
2158 static void free_pio_guest_pages(struct kvm_vcpu *vcpu)
2159 {
2160         int i;
2161
2162         for (i = 0; i < ARRAY_SIZE(vcpu->arch.pio.guest_pages); ++i)
2163                 if (vcpu->arch.pio.guest_pages[i]) {
2164                         kvm_release_page_dirty(vcpu->arch.pio.guest_pages[i]);
2165                         vcpu->arch.pio.guest_pages[i] = NULL;
2166                 }
2167 }
2168
2169 static int pio_copy_data(struct kvm_vcpu *vcpu)
2170 {
2171         void *p = vcpu->arch.pio_data;
2172         void *q;
2173         unsigned bytes;
2174         int nr_pages = vcpu->arch.pio.guest_pages[1] ? 2 : 1;
2175
2176         q = vmap(vcpu->arch.pio.guest_pages, nr_pages, VM_READ|VM_WRITE,
2177                  PAGE_KERNEL);
2178         if (!q) {
2179                 free_pio_guest_pages(vcpu);
2180                 return -ENOMEM;
2181         }
2182         q += vcpu->arch.pio.guest_page_offset;
2183         bytes = vcpu->arch.pio.size * vcpu->arch.pio.cur_count;
2184         if (vcpu->arch.pio.in)
2185                 memcpy(q, p, bytes);
2186         else
2187                 memcpy(p, q, bytes);
2188         q -= vcpu->arch.pio.guest_page_offset;
2189         vunmap(q);
2190         free_pio_guest_pages(vcpu);
2191         return 0;
2192 }
2193
2194 int complete_pio(struct kvm_vcpu *vcpu)
2195 {
2196         struct kvm_pio_request *io = &vcpu->arch.pio;
2197         long delta;
2198         int r;
2199
2200         kvm_x86_ops->cache_regs(vcpu);
2201
2202         if (!io->string) {
2203                 if (io->in)
2204                         memcpy(&vcpu->arch.regs[VCPU_REGS_RAX], vcpu->arch.pio_data,
2205                                io->size);
2206         } else {
2207                 if (io->in) {
2208                         r = pio_copy_data(vcpu);
2209                         if (r) {
2210                                 kvm_x86_ops->cache_regs(vcpu);
2211                                 return r;
2212                         }
2213                 }
2214
2215                 delta = 1;
2216                 if (io->rep) {
2217                         delta *= io->cur_count;
2218                         /*
2219                          * The size of the register should really depend on
2220                          * current address size.
2221                          */
2222                         vcpu->arch.regs[VCPU_REGS_RCX] -= delta;
2223                 }
2224                 if (io->down)
2225                         delta = -delta;
2226                 delta *= io->size;
2227                 if (io->in)
2228                         vcpu->arch.regs[VCPU_REGS_RDI] += delta;
2229                 else
2230                         vcpu->arch.regs[VCPU_REGS_RSI] += delta;
2231         }
2232
2233         kvm_x86_ops->decache_regs(vcpu);
2234
2235         io->count -= io->cur_count;
2236         io->cur_count = 0;
2237
2238         return 0;
2239 }
2240
2241 static void kernel_pio(struct kvm_io_device *pio_dev,
2242                        struct kvm_vcpu *vcpu,
2243                        void *pd)
2244 {
2245         /* TODO: String I/O for in kernel device */
2246
2247         mutex_lock(&vcpu->kvm->lock);
2248         if (vcpu->arch.pio.in)
2249                 kvm_iodevice_read(pio_dev, vcpu->arch.pio.port,
2250                                   vcpu->arch.pio.size,
2251                                   pd);
2252         else
2253                 kvm_iodevice_write(pio_dev, vcpu->arch.pio.port,
2254                                    vcpu->arch.pio.size,
2255                                    pd);
2256         mutex_unlock(&vcpu->kvm->lock);
2257 }
2258
2259 static void pio_string_write(struct kvm_io_device *pio_dev,
2260                              struct kvm_vcpu *vcpu)
2261 {
2262         struct kvm_pio_request *io = &vcpu->arch.pio;
2263         void *pd = vcpu->arch.pio_data;
2264         int i;
2265
2266         mutex_lock(&vcpu->kvm->lock);
2267         for (i = 0; i < io->cur_count; i++) {
2268                 kvm_iodevice_write(pio_dev, io->port,
2269                                    io->size,
2270                                    pd);
2271                 pd += io->size;
2272         }
2273         mutex_unlock(&vcpu->kvm->lock);
2274 }
2275
2276 static struct kvm_io_device *vcpu_find_pio_dev(struct kvm_vcpu *vcpu,
2277                                                gpa_t addr)
2278 {
2279         return kvm_io_bus_find_dev(&vcpu->kvm->pio_bus, addr);
2280 }
2281
2282 int kvm_emulate_pio(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
2283                   int size, unsigned port)
2284 {
2285         struct kvm_io_device *pio_dev;
2286
2287         vcpu->run->exit_reason = KVM_EXIT_IO;
2288         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2289         vcpu->run->io.size = vcpu->arch.pio.size = size;
2290         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2291         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = 1;
2292         vcpu->run->io.port = vcpu->arch.pio.port = port;
2293         vcpu->arch.pio.in = in;
2294         vcpu->arch.pio.string = 0;
2295         vcpu->arch.pio.down = 0;
2296         vcpu->arch.pio.guest_page_offset = 0;
2297         vcpu->arch.pio.rep = 0;
2298
2299         if (vcpu->run->io.direction == KVM_EXIT_IO_IN)
2300                 KVMTRACE_2D(IO_READ, vcpu, vcpu->run->io.port, (u32)size,
2301                             handler);
2302         else
2303                 KVMTRACE_2D(IO_WRITE, vcpu, vcpu->run->io.port, (u32)size,
2304                             handler);
2305
2306         kvm_x86_ops->cache_regs(vcpu);
2307         memcpy(vcpu->arch.pio_data, &vcpu->arch.regs[VCPU_REGS_RAX], 4);
2308         kvm_x86_ops->decache_regs(vcpu);
2309
2310         kvm_x86_ops->skip_emulated_instruction(vcpu);
2311
2312         pio_dev = vcpu_find_pio_dev(vcpu, port);
2313         if (pio_dev) {
2314                 kernel_pio(pio_dev, vcpu, vcpu->arch.pio_data);
2315                 complete_pio(vcpu);
2316                 return 1;
2317         }
2318         return 0;
2319 }
2320 EXPORT_SYMBOL_GPL(kvm_emulate_pio);
2321
2322 int kvm_emulate_pio_string(struct kvm_vcpu *vcpu, struct kvm_run *run, int in,
2323                   int size, unsigned long count, int down,
2324                   gva_t address, int rep, unsigned port)
2325 {
2326         unsigned now, in_page;
2327         int i, ret = 0;
2328         int nr_pages = 1;
2329         struct page *page;
2330         struct kvm_io_device *pio_dev;
2331
2332         vcpu->run->exit_reason = KVM_EXIT_IO;
2333         vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
2334         vcpu->run->io.size = vcpu->arch.pio.size = size;
2335         vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
2336         vcpu->run->io.count = vcpu->arch.pio.count = vcpu->arch.pio.cur_count = count;
2337         vcpu->run->io.port = vcpu->arch.pio.port = port;
2338         vcpu->arch.pio.in = in;
2339         vcpu->arch.pio.string = 1;
2340         vcpu->arch.pio.down = down;
2341         vcpu->arch.pio.guest_page_offset = offset_in_page(address);
2342         vcpu->arch.pio.rep = rep;
2343
2344         if (vcpu->run->io.direction == KVM_EXIT_IO_IN)
2345                 KVMTRACE_2D(IO_READ, vcpu, vcpu->run->io.port, (u32)size,
2346                             handler);
2347         else
2348                 KVMTRACE_2D(IO_WRITE, vcpu, vcpu->run->io.port, (u32)size,
2349                             handler);
2350
2351         if (!count) {
2352                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2353                 return 1;
2354         }
2355
2356         if (!down)
2357                 in_page = PAGE_SIZE - offset_in_page(address);
2358         else
2359                 in_page = offset_in_page(address) + size;
2360         now = min(count, (unsigned long)in_page / size);
2361         if (!now) {
2362                 /*
2363                  * String I/O straddles page boundary.  Pin two guest pages
2364                  * so that we satisfy atomicity constraints.  Do just one
2365                  * transaction to avoid complexity.
2366                  */
2367                 nr_pages = 2;
2368                 now = 1;
2369         }
2370         if (down) {
2371                 /*
2372                  * String I/O in reverse.  Yuck.  Kill the guest, fix later.
2373                  */
2374                 pr_unimpl(vcpu, "guest string pio down\n");
2375                 kvm_inject_gp(vcpu, 0);
2376                 return 1;
2377         }
2378         vcpu->run->io.count = now;
2379         vcpu->arch.pio.cur_count = now;
2380
2381         if (vcpu->arch.pio.cur_count == vcpu->arch.pio.count)
2382                 kvm_x86_ops->skip_emulated_instruction(vcpu);
2383
2384         for (i = 0; i < nr_pages; ++i) {
2385                 page = gva_to_page(vcpu, address + i * PAGE_SIZE);
2386                 vcpu->arch.pio.guest_pages[i] = page;
2387                 if (!page) {
2388                         kvm_inject_gp(vcpu, 0);
2389                         free_pio_guest_pages(vcpu);
2390                         return 1;
2391                 }
2392         }
2393
2394         pio_dev = vcpu_find_pio_dev(vcpu, port);
2395         if (!vcpu->arch.pio.in) {
2396                 /* string PIO write */
2397                 ret = pio_copy_data(vcpu);
2398                 if (ret >= 0 && pio_dev) {
2399                         pio_string_write(pio_dev, vcpu);
2400                         complete_pio(vcpu);
2401                         if (vcpu->arch.pio.count == 0)
2402                                 ret = 1;
2403                 }
2404         } else if (pio_dev)
2405                 pr_unimpl(vcpu, "no string pio read support yet, "
2406                        "port %x size %d count %ld\n",
2407                         port, size, count);
2408
2409         return ret;
2410 }
2411 EXPORT_SYMBOL_GPL(kvm_emulate_pio_string);
2412
2413 int kvm_arch_init(void *opaque)
2414 {
2415         int r;
2416         struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
2417
2418         if (kvm_x86_ops) {
2419                 printk(KERN_ERR "kvm: already loaded the other module\n");
2420                 r = -EEXIST;
2421                 goto out;
2422         }
2423
2424         if (!ops->cpu_has_kvm_support()) {
2425                 printk(KERN_ERR "kvm: no hardware support\n");
2426                 r = -EOPNOTSUPP;
2427                 goto out;
2428         }
2429         if (ops->disabled_by_bios()) {
2430                 printk(KERN_ERR "kvm: disabled by bios\n");
2431                 r = -EOPNOTSUPP;
2432                 goto out;
2433         }
2434
2435         r = kvm_mmu_module_init();
2436         if (r)
2437                 goto out;
2438
2439         kvm_init_msr_list();
2440
2441         kvm_x86_ops = ops;
2442         kvm_mmu_set_nonpresent_ptes(0ull, 0ull);
2443         kvm_mmu_set_base_ptes(PT_PRESENT_MASK);
2444         kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
2445                         PT_DIRTY_MASK, PT64_NX_MASK, 0);
2446         return 0;
2447
2448 out:
2449         return r;
2450 }
2451
2452 void kvm_arch_exit(void)
2453 {
2454         kvm_x86_ops = NULL;
2455         kvm_mmu_module_exit();
2456 }
2457
2458 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
2459 {
2460         ++vcpu->stat.halt_exits;
2461         KVMTRACE_0D(HLT, vcpu, handler);
2462         if (irqchip_in_kernel(vcpu->kvm)) {
2463                 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
2464                 up_read(&vcpu->kvm->slots_lock);
2465                 kvm_vcpu_block(vcpu);
2466                 down_read(&vcpu->kvm->slots_lock);
2467                 if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE)
2468                         return -EINTR;
2469                 return 1;
2470         } else {
2471                 vcpu->run->exit_reason = KVM_EXIT_HLT;
2472                 return 0;
2473         }
2474 }
2475 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
2476
2477 static inline gpa_t hc_gpa(struct kvm_vcpu *vcpu, unsigned long a0,
2478                            unsigned long a1)
2479 {
2480         if (is_long_mode(vcpu))
2481                 return a0;
2482         else
2483                 return a0 | ((gpa_t)a1 << 32);
2484 }
2485
2486 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
2487 {
2488         unsigned long nr, a0, a1, a2, a3, ret;
2489         int r = 1;
2490
2491         kvm_x86_ops->cache_regs(vcpu);
2492
2493         nr = vcpu->arch.regs[VCPU_REGS_RAX];
2494         a0 = vcpu->arch.regs[VCPU_REGS_RBX];
2495         a1 = vcpu->arch.regs[VCPU_REGS_RCX];
2496         a2 = vcpu->arch.regs[VCPU_REGS_RDX];
2497         a3 = vcpu->arch.regs[VCPU_REGS_RSI];
2498
2499         KVMTRACE_1D(VMMCALL, vcpu, (u32)nr, handler);
2500
2501         if (!is_long_mode(vcpu)) {
2502                 nr &= 0xFFFFFFFF;
2503                 a0 &= 0xFFFFFFFF;
2504                 a1 &= 0xFFFFFFFF;
2505                 a2 &= 0xFFFFFFFF;
2506                 a3 &= 0xFFFFFFFF;
2507         }
2508
2509         switch (nr) {
2510         case KVM_HC_VAPIC_POLL_IRQ:
2511                 ret = 0;
2512                 break;
2513         case KVM_HC_MMU_OP:
2514                 r = kvm_pv_mmu_op(vcpu, a0, hc_gpa(vcpu, a1, a2), &ret);
2515                 break;
2516         default:
2517                 ret = -KVM_ENOSYS;
2518                 break;
2519         }
2520         vcpu->arch.regs[VCPU_REGS_RAX] = ret;
2521         kvm_x86_ops->decache_regs(vcpu);
2522         ++vcpu->stat.hypercalls;
2523         return r;
2524 }
2525 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
2526
2527 int kvm_fix_hypercall(struct kvm_vcpu *vcpu)
2528 {
2529         char instruction[3];
2530         int ret = 0;
2531
2532
2533         /*
2534          * Blow out the MMU to ensure that no other VCPU has an active mapping
2535          * to ensure that the updated hypercall appears atomically across all
2536          * VCPUs.
2537          */
2538         kvm_mmu_zap_all(vcpu->kvm);
2539
2540         kvm_x86_ops->cache_regs(vcpu);
2541         kvm_x86_ops->patch_hypercall(vcpu, instruction);
2542         if (emulator_write_emulated(vcpu->arch.rip, instruction, 3, vcpu)
2543             != X86EMUL_CONTINUE)
2544                 ret = -EFAULT;
2545
2546         return ret;
2547 }
2548
2549 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
2550 {
2551         return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
2552 }
2553
2554 void realmode_lgdt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2555 {
2556         struct descriptor_table dt = { limit, base };
2557
2558         kvm_x86_ops->set_gdt(vcpu, &dt);
2559 }
2560
2561 void realmode_lidt(struct kvm_vcpu *vcpu, u16 limit, unsigned long base)
2562 {
2563         struct descriptor_table dt = { limit, base };
2564
2565         kvm_x86_ops->set_idt(vcpu, &dt);
2566 }
2567
2568 void realmode_lmsw(struct kvm_vcpu *vcpu, unsigned long msw,
2569                    unsigned long *rflags)
2570 {
2571         kvm_lmsw(vcpu, msw);
2572         *rflags = kvm_x86_ops->get_rflags(vcpu);
2573 }
2574
2575 unsigned long realmode_get_cr(struct kvm_vcpu *vcpu, int cr)
2576 {
2577         unsigned long value;
2578
2579         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
2580         switch (cr) {
2581         case 0:
2582                 value = vcpu->arch.cr0;
2583                 break;
2584         case 2:
2585                 value = vcpu->arch.cr2;
2586                 break;
2587         case 3:
2588                 value = vcpu->arch.cr3;
2589                 break;
2590         case 4:
2591                 value = vcpu->arch.cr4;
2592                 break;
2593         case 8:
2594                 value = kvm_get_cr8(vcpu);
2595                 break;
2596         default:
2597                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
2598                 return 0;
2599         }
2600         KVMTRACE_3D(CR_READ, vcpu, (u32)cr, (u32)value,
2601                     (u32)((u64)value >> 32), handler);
2602
2603         return value;
2604 }
2605
2606 void realmode_set_cr(struct kvm_vcpu *vcpu, int cr, unsigned long val,
2607                      unsigned long *rflags)
2608 {
2609         KVMTRACE_3D(CR_WRITE, vcpu, (u32)cr, (u32)val,
2610                     (u32)((u64)val >> 32), handler);
2611
2612         switch (cr) {
2613         case 0:
2614                 kvm_set_cr0(vcpu, mk_cr_64(vcpu->arch.cr0, val));
2615                 *rflags = kvm_x86_ops->get_rflags(vcpu);
2616                 break;
2617         case 2:
2618                 vcpu->arch.cr2 = val;
2619                 break;
2620         case 3:
2621                 kvm_set_cr3(vcpu, val);
2622                 break;
2623         case 4:
2624                 kvm_set_cr4(vcpu, mk_cr_64(vcpu->arch.cr4, val));
2625                 break;
2626         case 8:
2627                 kvm_set_cr8(vcpu, val & 0xfUL);
2628                 break;
2629         default:
2630                 vcpu_printf(vcpu, "%s: unexpected cr %u\n", __func__, cr);
2631         }
2632 }
2633
2634 static int move_to_next_stateful_cpuid_entry(struct kvm_vcpu *vcpu, int i)
2635 {
2636         struct kvm_cpuid_entry2 *e = &vcpu->arch.cpuid_entries[i];
2637         int j, nent = vcpu->arch.cpuid_nent;
2638
2639         e->flags &= ~KVM_CPUID_FLAG_STATE_READ_NEXT;
2640         /* when no next entry is found, the current entry[i] is reselected */
2641         for (j = i + 1; j == i; j = (j + 1) % nent) {
2642                 struct kvm_cpuid_entry2 *ej = &vcpu->arch.cpuid_entries[j];
2643                 if (ej->function == e->function) {
2644                         ej->flags |= KVM_CPUID_FLAG_STATE_READ_NEXT;
2645                         return j;
2646                 }
2647         }
2648         return 0; /* silence gcc, even though control never reaches here */
2649 }
2650
2651 /* find an entry with matching function, matching index (if needed), and that
2652  * should be read next (if it's stateful) */
2653 static int is_matching_cpuid_entry(struct kvm_cpuid_entry2 *e,
2654         u32 function, u32 index)
2655 {
2656         if (e->function != function)
2657                 return 0;
2658         if ((e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) && e->index != index)
2659                 return 0;
2660         if ((e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC) &&
2661                 !(e->flags & KVM_CPUID_FLAG_STATE_READ_NEXT))
2662                 return 0;
2663         return 1;
2664 }
2665
2666 void kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
2667 {
2668         int i;
2669         u32 function, index;
2670         struct kvm_cpuid_entry2 *e, *best;
2671
2672         kvm_x86_ops->cache_regs(vcpu);
2673         function = vcpu->arch.regs[VCPU_REGS_RAX];
2674         index = vcpu->arch.regs[VCPU_REGS_RCX];
2675         vcpu->arch.regs[VCPU_REGS_RAX] = 0;
2676         vcpu->arch.regs[VCPU_REGS_RBX] = 0;
2677         vcpu->arch.regs[VCPU_REGS_RCX] = 0;
2678         vcpu->arch.regs[VCPU_REGS_RDX] = 0;
2679         best = NULL;
2680         for (i = 0; i < vcpu->arch.cpuid_nent; ++i) {
2681                 e = &vcpu->arch.cpuid_entries[i];
2682                 if (is_matching_cpuid_entry(e, function, index)) {
2683                         if (e->flags & KVM_CPUID_FLAG_STATEFUL_FUNC)
2684                                 move_to_next_stateful_cpuid_entry(vcpu, i);
2685                         best = e;
2686                         break;
2687                 }
2688                 /*
2689                  * Both basic or both extended?
2690                  */
2691                 if (((e->function ^ function) & 0x80000000) == 0)
2692                         if (!best || e->function > best->function)
2693                                 best = e;
2694         }
2695         if (best) {
2696                 vcpu->arch.regs[VCPU_REGS_RAX] = best->eax;
2697                 vcpu->arch.regs[VCPU_REGS_RBX] = best->ebx;
2698                 vcpu->arch.regs[VCPU_REGS_RCX] = best->ecx;
2699                 vcpu->arch.regs[VCPU_REGS_RDX] = best->edx;
2700         }
2701         kvm_x86_ops->decache_regs(vcpu);
2702         kvm_x86_ops->skip_emulated_instruction(vcpu);
2703         KVMTRACE_5D(CPUID, vcpu, function,
2704                     (u32)vcpu->arch.regs[VCPU_REGS_RAX],
2705                     (u32)vcpu->arch.regs[VCPU_REGS_RBX],
2706                     (u32)vcpu->arch.regs[VCPU_REGS_RCX],
2707                     (u32)vcpu->arch.regs[VCPU_REGS_RDX], handler);
2708 }
2709 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
2710
2711 /*
2712  * Check if userspace requested an interrupt window, and that the
2713  * interrupt window is open.
2714  *
2715  * No need to exit to userspace if we already have an interrupt queued.
2716  */
2717 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu,
2718                                           struct kvm_run *kvm_run)
2719 {
2720         return (!vcpu->arch.irq_summary &&
2721                 kvm_run->request_interrupt_window &&
2722                 vcpu->arch.interrupt_window_open &&
2723                 (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF));
2724 }
2725
2726 static void post_kvm_run_save(struct kvm_vcpu *vcpu,
2727                               struct kvm_run *kvm_run)
2728 {
2729         kvm_run->if_flag = (kvm_x86_ops->get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
2730         kvm_run->cr8 = kvm_get_cr8(vcpu);
2731         kvm_run->apic_base = kvm_get_apic_base(vcpu);
2732         if (irqchip_in_kernel(vcpu->kvm))
2733                 kvm_run->ready_for_interrupt_injection = 1;
2734         else
2735                 kvm_run->ready_for_interrupt_injection =
2736                                         (vcpu->arch.interrupt_window_open &&
2737                                          vcpu->arch.irq_summary == 0);
2738 }
2739
2740 static void vapic_enter(struct kvm_vcpu *vcpu)
2741 {
2742         struct kvm_lapic *apic = vcpu->arch.apic;
2743         struct page *page;
2744
2745         if (!apic || !apic->vapic_addr)
2746                 return;
2747
2748         down_read(&current->mm->mmap_sem);
2749         page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
2750         up_read(&current->mm->mmap_sem);
2751
2752         vcpu->arch.apic->vapic_page = page;
2753 }
2754
2755 static void vapic_exit(struct kvm_vcpu *vcpu)
2756 {
2757         struct kvm_lapic *apic = vcpu->arch.apic;
2758
2759         if (!apic || !apic->vapic_addr)
2760                 return;
2761
2762         kvm_release_page_dirty(apic->vapic_page);
2763         mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
2764 }
2765
2766 static int __vcpu_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2767 {
2768         int r;
2769
2770         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED)) {
2771                 pr_debug("vcpu %d received sipi with vector # %x\n",
2772                        vcpu->vcpu_id, vcpu->arch.sipi_vector);
2773                 kvm_lapic_reset(vcpu);
2774                 r = kvm_x86_ops->vcpu_reset(vcpu);
2775                 if (r)
2776                         return r;
2777                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
2778         }
2779
2780         down_read(&vcpu->kvm->slots_lock);
2781         vapic_enter(vcpu);
2782
2783 preempted:
2784         if (vcpu->guest_debug.enabled)
2785                 kvm_x86_ops->guest_debug_pre(vcpu);
2786
2787 again:
2788         if (vcpu->requests)
2789                 if (test_and_clear_bit(KVM_REQ_MMU_RELOAD, &vcpu->requests))
2790                         kvm_mmu_unload(vcpu);
2791
2792         r = kvm_mmu_reload(vcpu);
2793         if (unlikely(r))
2794                 goto out;
2795
2796         if (vcpu->requests) {
2797                 if (test_and_clear_bit(KVM_REQ_MIGRATE_TIMER, &vcpu->requests))
2798                         __kvm_migrate_timers(vcpu);
2799                 if (test_and_clear_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))
2800                         kvm_x86_ops->tlb_flush(vcpu);
2801                 if (test_and_clear_bit(KVM_REQ_REPORT_TPR_ACCESS,
2802                                        &vcpu->requests)) {
2803                         kvm_run->exit_reason = KVM_EXIT_TPR_ACCESS;
2804                         r = 0;
2805                         goto out;
2806                 }
2807                 if (test_and_clear_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests)) {
2808                         kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2809                         r = 0;
2810                         goto out;
2811                 }
2812         }
2813
2814         clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
2815         kvm_inject_pending_timer_irqs(vcpu);
2816
2817         preempt_disable();
2818
2819         kvm_x86_ops->prepare_guest_switch(vcpu);
2820         kvm_load_guest_fpu(vcpu);
2821
2822         local_irq_disable();
2823
2824         if (vcpu->requests || need_resched()) {
2825                 local_irq_enable();
2826                 preempt_enable();
2827                 r = 1;
2828                 goto out;
2829         }
2830
2831         if (signal_pending(current)) {
2832                 local_irq_enable();
2833                 preempt_enable();
2834                 r = -EINTR;
2835                 kvm_run->exit_reason = KVM_EXIT_INTR;
2836                 ++vcpu->stat.signal_exits;
2837                 goto out;
2838         }
2839
2840         vcpu->guest_mode = 1;
2841         /*
2842          * Make sure that guest_mode assignment won't happen after
2843          * testing the pending IRQ vector bitmap.
2844          */
2845         smp_wmb();
2846
2847         if (vcpu->arch.exception.pending)
2848                 __queue_exception(vcpu);
2849         else if (irqchip_in_kernel(vcpu->kvm))
2850                 kvm_x86_ops->inject_pending_irq(vcpu);
2851         else
2852                 kvm_x86_ops->inject_pending_vectors(vcpu, kvm_run);
2853
2854         kvm_lapic_sync_to_vapic(vcpu);
2855
2856         up_read(&vcpu->kvm->slots_lock);
2857
2858         kvm_guest_enter();
2859
2860
2861         KVMTRACE_0D(VMENTRY, vcpu, entryexit);
2862         kvm_x86_ops->run(vcpu, kvm_run);
2863
2864         vcpu->guest_mode = 0;
2865         local_irq_enable();
2866
2867         ++vcpu->stat.exits;
2868
2869         /*
2870          * We must have an instruction between local_irq_enable() and
2871          * kvm_guest_exit(), so the timer interrupt isn't delayed by
2872          * the interrupt shadow.  The stat.exits increment will do nicely.
2873          * But we need to prevent reordering, hence this barrier():
2874          */
2875         barrier();
2876
2877         kvm_guest_exit();
2878
2879         preempt_enable();
2880
2881         down_read(&vcpu->kvm->slots_lock);
2882
2883         /*
2884          * Profile KVM exit RIPs:
2885          */
2886         if (unlikely(prof_on == KVM_PROFILING)) {
2887                 kvm_x86_ops->cache_regs(vcpu);
2888                 profile_hit(KVM_PROFILING, (void *)vcpu->arch.rip);
2889         }
2890
2891         if (vcpu->arch.exception.pending && kvm_x86_ops->exception_injected(vcpu))
2892                 vcpu->arch.exception.pending = false;
2893
2894         kvm_lapic_sync_from_vapic(vcpu);
2895
2896         r = kvm_x86_ops->handle_exit(kvm_run, vcpu);
2897
2898         if (r > 0) {
2899                 if (dm_request_for_irq_injection(vcpu, kvm_run)) {
2900                         r = -EINTR;
2901                         kvm_run->exit_reason = KVM_EXIT_INTR;
2902                         ++vcpu->stat.request_irq_exits;
2903                         goto out;
2904                 }
2905                 if (!need_resched())
2906                         goto again;
2907         }
2908
2909 out:
2910         up_read(&vcpu->kvm->slots_lock);
2911         if (r > 0) {
2912                 kvm_resched(vcpu);
2913                 down_read(&vcpu->kvm->slots_lock);
2914                 goto preempted;
2915         }
2916
2917         post_kvm_run_save(vcpu, kvm_run);
2918
2919         down_read(&vcpu->kvm->slots_lock);
2920         vapic_exit(vcpu);
2921         up_read(&vcpu->kvm->slots_lock);
2922
2923         return r;
2924 }
2925
2926 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
2927 {
2928         int r;
2929         sigset_t sigsaved;
2930
2931         vcpu_load(vcpu);
2932
2933         if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
2934                 kvm_vcpu_block(vcpu);
2935                 vcpu_put(vcpu);
2936                 return -EAGAIN;
2937         }
2938
2939         if (vcpu->sigset_active)
2940                 sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
2941
2942         /* re-sync apic's tpr */
2943         if (!irqchip_in_kernel(vcpu->kvm))
2944                 kvm_set_cr8(vcpu, kvm_run->cr8);
2945
2946         if (vcpu->arch.pio.cur_count) {
2947                 r = complete_pio(vcpu);
2948                 if (r)
2949                         goto out;
2950         }
2951 #if CONFIG_HAS_IOMEM
2952         if (vcpu->mmio_needed) {
2953                 memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8);
2954                 vcpu->mmio_read_completed = 1;
2955                 vcpu->mmio_needed = 0;
2956
2957                 down_read(&vcpu->kvm->slots_lock);
2958                 r = emulate_instruction(vcpu, kvm_run,
2959                                         vcpu->arch.mmio_fault_cr2, 0,
2960                                         EMULTYPE_NO_DECODE);
2961                 up_read(&vcpu->kvm->slots_lock);
2962                 if (r == EMULATE_DO_MMIO) {
2963                         /*
2964                          * Read-modify-write.  Back to userspace.
2965                          */
2966                         r = 0;
2967                         goto out;
2968                 }
2969         }
2970 #endif
2971         if (kvm_run->exit_reason == KVM_EXIT_HYPERCALL) {
2972                 kvm_x86_ops->cache_regs(vcpu);
2973                 vcpu->arch.regs[VCPU_REGS_RAX] = kvm_run->hypercall.ret;
2974                 kvm_x86_ops->decache_regs(vcpu);
2975         }
2976
2977         r = __vcpu_run(vcpu, kvm_run);
2978
2979 out:
2980         if (vcpu->sigset_active)
2981                 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
2982
2983         vcpu_put(vcpu);
2984         return r;
2985 }
2986
2987 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
2988 {
2989         vcpu_load(vcpu);
2990
2991         kvm_x86_ops->cache_regs(vcpu);
2992
2993         regs->rax = vcpu->arch.regs[VCPU_REGS_RAX];
2994         regs->rbx = vcpu->arch.regs[VCPU_REGS_RBX];
2995         regs->rcx = vcpu->arch.regs[VCPU_REGS_RCX];
2996         regs->rdx = vcpu->arch.regs[VCPU_REGS_RDX];
2997         regs->rsi = vcpu->arch.regs[VCPU_REGS_RSI];
2998         regs->rdi = vcpu->arch.regs[VCPU_REGS_RDI];
2999         regs->rsp = vcpu->arch.regs[VCPU_REGS_RSP];
3000         regs->rbp = vcpu->arch.regs[VCPU_REGS_RBP];
3001 #ifdef CONFIG_X86_64
3002         regs->r8 = vcpu->arch.regs[VCPU_REGS_R8];
3003         regs->r9 = vcpu->arch.regs[VCPU_REGS_R9];
3004         regs->r10 = vcpu->arch.regs[VCPU_REGS_R10];
3005         regs->r11 = vcpu->arch.regs[VCPU_REGS_R11];
3006         regs->r12 = vcpu->arch.regs[VCPU_REGS_R12];
3007         regs->r13 = vcpu->arch.regs[VCPU_REGS_R13];
3008         regs->r14 = vcpu->arch.regs[VCPU_REGS_R14];
3009         regs->r15 = vcpu->arch.regs[VCPU_REGS_R15];
3010 #endif
3011
3012         regs->rip = vcpu->arch.rip;
3013         regs->rflags = kvm_x86_ops->get_rflags(vcpu);
3014
3015         /*
3016          * Don't leak debug flags in case they were set for guest debugging
3017          */
3018         if (vcpu->guest_debug.enabled && vcpu->guest_debug.singlestep)
3019                 regs->rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
3020
3021         vcpu_put(vcpu);
3022
3023         return 0;
3024 }
3025
3026 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
3027 {
3028         vcpu_load(vcpu);
3029
3030         vcpu->arch.regs[VCPU_REGS_RAX] = regs->rax;
3031         vcpu->arch.regs[VCPU_REGS_RBX] = regs->rbx;
3032         vcpu->arch.regs[VCPU_REGS_RCX] = regs->rcx;
3033         vcpu->arch.regs[VCPU_REGS_RDX] = regs->rdx;
3034         vcpu->arch.regs[VCPU_REGS_RSI] = regs->rsi;
3035         vcpu->arch.regs[VCPU_REGS_RDI] = regs->rdi;
3036         vcpu->arch.regs[VCPU_REGS_RSP] = regs->rsp;
3037         vcpu->arch.regs[VCPU_REGS_RBP] = regs->rbp;
3038 #ifdef CONFIG_X86_64
3039         vcpu->arch.regs[VCPU_REGS_R8] = regs->r8;
3040         vcpu->arch.regs[VCPU_REGS_R9] = regs->r9;
3041         vcpu->arch.regs[VCPU_REGS_R10] = regs->r10;
3042         vcpu->arch.regs[VCPU_REGS_R11] = regs->r11;
3043         vcpu->arch.regs[VCPU_REGS_R12] = regs->r12;
3044         vcpu->arch.regs[VCPU_REGS_R13] = regs->r13;
3045         vcpu->arch.regs[VCPU_REGS_R14] = regs->r14;
3046         vcpu->arch.regs[VCPU_REGS_R15] = regs->r15;
3047 #endif
3048
3049         vcpu->arch.rip = regs->rip;
3050         kvm_x86_ops->set_rflags(vcpu, regs->rflags);
3051
3052         kvm_x86_ops->decache_regs(vcpu);
3053
3054         vcpu->arch.exception.pending = false;
3055
3056         vcpu_put(vcpu);
3057
3058         return 0;
3059 }
3060
3061 static void get_segment(struct kvm_vcpu *vcpu,
3062                         struct kvm_segment *var, int seg)
3063 {
3064         kvm_x86_ops->get_segment(vcpu, var, seg);
3065 }
3066
3067 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3068 {
3069         struct kvm_segment cs;
3070
3071         get_segment(vcpu, &cs, VCPU_SREG_CS);
3072         *db = cs.db;
3073         *l = cs.l;
3074 }
3075 EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
3076
3077 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
3078                                   struct kvm_sregs *sregs)
3079 {
3080         struct descriptor_table dt;
3081         int pending_vec;
3082
3083         vcpu_load(vcpu);
3084
3085         get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
3086         get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
3087         get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
3088         get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
3089         get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
3090         get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
3091
3092         get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
3093         get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
3094
3095         kvm_x86_ops->get_idt(vcpu, &dt);
3096         sregs->idt.limit = dt.limit;
3097         sregs->idt.base = dt.base;
3098         kvm_x86_ops->get_gdt(vcpu, &dt);
3099         sregs->gdt.limit = dt.limit;
3100         sregs->gdt.base = dt.base;
3101
3102         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
3103         sregs->cr0 = vcpu->arch.cr0;
3104         sregs->cr2 = vcpu->arch.cr2;
3105         sregs->cr3 = vcpu->arch.cr3;
3106         sregs->cr4 = vcpu->arch.cr4;
3107         sregs->cr8 = kvm_get_cr8(vcpu);
3108         sregs->efer = vcpu->arch.shadow_efer;
3109         sregs->apic_base = kvm_get_apic_base(vcpu);
3110
3111         if (irqchip_in_kernel(vcpu->kvm)) {
3112                 memset(sregs->interrupt_bitmap, 0,
3113                        sizeof sregs->interrupt_bitmap);
3114                 pending_vec = kvm_x86_ops->get_irq(vcpu);
3115                 if (pending_vec >= 0)
3116                         set_bit(pending_vec,
3117                                 (unsigned long *)sregs->interrupt_bitmap);
3118         } else
3119                 memcpy(sregs->interrupt_bitmap, vcpu->arch.irq_pending,
3120                        sizeof sregs->interrupt_bitmap);
3121
3122         vcpu_put(vcpu);
3123
3124         return 0;
3125 }
3126
3127 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
3128                                     struct kvm_mp_state *mp_state)
3129 {
3130         vcpu_load(vcpu);
3131         mp_state->mp_state = vcpu->arch.mp_state;
3132         vcpu_put(vcpu);
3133         return 0;
3134 }
3135
3136 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
3137                                     struct kvm_mp_state *mp_state)
3138 {
3139         vcpu_load(vcpu);
3140         vcpu->arch.mp_state = mp_state->mp_state;
3141         vcpu_put(vcpu);
3142         return 0;
3143 }
3144
3145 static void set_segment(struct kvm_vcpu *vcpu,
3146                         struct kvm_segment *var, int seg)
3147 {
3148         kvm_x86_ops->set_segment(vcpu, var, seg);
3149 }
3150
3151 static void seg_desct_to_kvm_desct(struct desc_struct *seg_desc, u16 selector,
3152                                    struct kvm_segment *kvm_desct)
3153 {
3154         kvm_desct->base = seg_desc->base0;
3155         kvm_desct->base |= seg_desc->base1 << 16;
3156         kvm_desct->base |= seg_desc->base2 << 24;
3157         kvm_desct->limit = seg_desc->limit0;
3158         kvm_desct->limit |= seg_desc->limit << 16;
3159         kvm_desct->selector = selector;
3160         kvm_desct->type = seg_desc->type;
3161         kvm_desct->present = seg_desc->p;
3162         kvm_desct->dpl = seg_desc->dpl;
3163         kvm_desct->db = seg_desc->d;
3164         kvm_desct->s = seg_desc->s;
3165         kvm_desct->l = seg_desc->l;
3166         kvm_desct->g = seg_desc->g;
3167         kvm_desct->avl = seg_desc->avl;
3168         if (!selector)
3169                 kvm_desct->unusable = 1;
3170         else
3171                 kvm_desct->unusable = 0;
3172         kvm_desct->padding = 0;
3173 }
3174
3175 static void get_segment_descritptor_dtable(struct kvm_vcpu *vcpu,
3176                                            u16 selector,
3177                                            struct descriptor_table *dtable)
3178 {
3179         if (selector & 1 << 2) {
3180                 struct kvm_segment kvm_seg;
3181
3182                 get_segment(vcpu, &kvm_seg, VCPU_SREG_LDTR);
3183
3184                 if (kvm_seg.unusable)
3185                         dtable->limit = 0;
3186                 else
3187                         dtable->limit = kvm_seg.limit;
3188                 dtable->base = kvm_seg.base;
3189         }
3190         else
3191                 kvm_x86_ops->get_gdt(vcpu, dtable);
3192 }
3193
3194 /* allowed just for 8 bytes segments */
3195 static int load_guest_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
3196                                          struct desc_struct *seg_desc)
3197 {
3198         struct descriptor_table dtable;
3199         u16 index = selector >> 3;
3200
3201         get_segment_descritptor_dtable(vcpu, selector, &dtable);
3202
3203         if (dtable.limit < index * 8 + 7) {
3204                 kvm_queue_exception_e(vcpu, GP_VECTOR, selector & 0xfffc);
3205                 return 1;
3206         }
3207         return kvm_read_guest(vcpu->kvm, dtable.base + index * 8, seg_desc, 8);
3208 }
3209
3210 /* allowed just for 8 bytes segments */
3211 static int save_guest_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
3212                                          struct desc_struct *seg_desc)
3213 {
3214         struct descriptor_table dtable;
3215         u16 index = selector >> 3;
3216
3217         get_segment_descritptor_dtable(vcpu, selector, &dtable);
3218
3219         if (dtable.limit < index * 8 + 7)
3220                 return 1;
3221         return kvm_write_guest(vcpu->kvm, dtable.base + index * 8, seg_desc, 8);
3222 }
3223
3224 static u32 get_tss_base_addr(struct kvm_vcpu *vcpu,
3225                              struct desc_struct *seg_desc)
3226 {
3227         u32 base_addr;
3228
3229         base_addr = seg_desc->base0;
3230         base_addr |= (seg_desc->base1 << 16);
3231         base_addr |= (seg_desc->base2 << 24);
3232
3233         return base_addr;
3234 }
3235
3236 static int load_tss_segment32(struct kvm_vcpu *vcpu,
3237                               struct desc_struct *seg_desc,
3238                               struct tss_segment_32 *tss)
3239 {
3240         u32 base_addr;
3241
3242         base_addr = get_tss_base_addr(vcpu, seg_desc);
3243
3244         return kvm_read_guest(vcpu->kvm, base_addr, tss,
3245                               sizeof(struct tss_segment_32));
3246 }
3247
3248 static int save_tss_segment32(struct kvm_vcpu *vcpu,
3249                               struct desc_struct *seg_desc,
3250                               struct tss_segment_32 *tss)
3251 {
3252         u32 base_addr;
3253
3254         base_addr = get_tss_base_addr(vcpu, seg_desc);
3255
3256         return kvm_write_guest(vcpu->kvm, base_addr, tss,
3257                                sizeof(struct tss_segment_32));
3258 }
3259
3260 static int load_tss_segment16(struct kvm_vcpu *vcpu,
3261                               struct desc_struct *seg_desc,
3262                               struct tss_segment_16 *tss)
3263 {
3264         u32 base_addr;
3265
3266         base_addr = get_tss_base_addr(vcpu, seg_desc);
3267
3268         return kvm_read_guest(vcpu->kvm, base_addr, tss,
3269                               sizeof(struct tss_segment_16));
3270 }
3271
3272 static int save_tss_segment16(struct kvm_vcpu *vcpu,
3273                               struct desc_struct *seg_desc,
3274                               struct tss_segment_16 *tss)
3275 {
3276         u32 base_addr;
3277
3278         base_addr = get_tss_base_addr(vcpu, seg_desc);
3279
3280         return kvm_write_guest(vcpu->kvm, base_addr, tss,
3281                                sizeof(struct tss_segment_16));
3282 }
3283
3284 static u16 get_segment_selector(struct kvm_vcpu *vcpu, int seg)
3285 {
3286         struct kvm_segment kvm_seg;
3287
3288         get_segment(vcpu, &kvm_seg, seg);
3289         return kvm_seg.selector;
3290 }
3291
3292 static int load_segment_descriptor_to_kvm_desct(struct kvm_vcpu *vcpu,
3293                                                 u16 selector,
3294                                                 struct kvm_segment *kvm_seg)
3295 {
3296         struct desc_struct seg_desc;
3297
3298         if (load_guest_segment_descriptor(vcpu, selector, &seg_desc))
3299                 return 1;
3300         seg_desct_to_kvm_desct(&seg_desc, selector, kvm_seg);
3301         return 0;
3302 }
3303
3304 static int load_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector,
3305                                    int type_bits, int seg)
3306 {
3307         struct kvm_segment kvm_seg;
3308
3309         if (load_segment_descriptor_to_kvm_desct(vcpu, selector, &kvm_seg))
3310                 return 1;
3311         kvm_seg.type |= type_bits;
3312
3313         if (seg != VCPU_SREG_SS && seg != VCPU_SREG_CS &&
3314             seg != VCPU_SREG_LDTR)
3315                 if (!kvm_seg.s)
3316                         kvm_seg.unusable = 1;
3317
3318         set_segment(vcpu, &kvm_seg, seg);
3319         return 0;
3320 }
3321
3322 static void save_state_to_tss32(struct kvm_vcpu *vcpu,
3323                                 struct tss_segment_32 *tss)
3324 {
3325         tss->cr3 = vcpu->arch.cr3;
3326         tss->eip = vcpu->arch.rip;
3327         tss->eflags = kvm_x86_ops->get_rflags(vcpu);
3328         tss->eax = vcpu->arch.regs[VCPU_REGS_RAX];
3329         tss->ecx = vcpu->arch.regs[VCPU_REGS_RCX];
3330         tss->edx = vcpu->arch.regs[VCPU_REGS_RDX];
3331         tss->ebx = vcpu->arch.regs[VCPU_REGS_RBX];
3332         tss->esp = vcpu->arch.regs[VCPU_REGS_RSP];
3333         tss->ebp = vcpu->arch.regs[VCPU_REGS_RBP];
3334         tss->esi = vcpu->arch.regs[VCPU_REGS_RSI];
3335         tss->edi = vcpu->arch.regs[VCPU_REGS_RDI];
3336
3337         tss->es = get_segment_selector(vcpu, VCPU_SREG_ES);
3338         tss->cs = get_segment_selector(vcpu, VCPU_SREG_CS);
3339         tss->ss = get_segment_selector(vcpu, VCPU_SREG_SS);
3340         tss->ds = get_segment_selector(vcpu, VCPU_SREG_DS);
3341         tss->fs = get_segment_selector(vcpu, VCPU_SREG_FS);
3342         tss->gs = get_segment_selector(vcpu, VCPU_SREG_GS);
3343         tss->ldt_selector = get_segment_selector(vcpu, VCPU_SREG_LDTR);
3344         tss->prev_task_link = get_segment_selector(vcpu, VCPU_SREG_TR);
3345 }
3346
3347 static int load_state_from_tss32(struct kvm_vcpu *vcpu,
3348                                   struct tss_segment_32 *tss)
3349 {
3350         kvm_set_cr3(vcpu, tss->cr3);
3351
3352         vcpu->arch.rip = tss->eip;
3353         kvm_x86_ops->set_rflags(vcpu, tss->eflags | 2);
3354
3355         vcpu->arch.regs[VCPU_REGS_RAX] = tss->eax;
3356         vcpu->arch.regs[VCPU_REGS_RCX] = tss->ecx;
3357         vcpu->arch.regs[VCPU_REGS_RDX] = tss->edx;
3358         vcpu->arch.regs[VCPU_REGS_RBX] = tss->ebx;
3359         vcpu->arch.regs[VCPU_REGS_RSP] = tss->esp;
3360         vcpu->arch.regs[VCPU_REGS_RBP] = tss->ebp;
3361         vcpu->arch.regs[VCPU_REGS_RSI] = tss->esi;
3362         vcpu->arch.regs[VCPU_REGS_RDI] = tss->edi;
3363
3364         if (load_segment_descriptor(vcpu, tss->ldt_selector, 0, VCPU_SREG_LDTR))
3365                 return 1;
3366
3367         if (load_segment_descriptor(vcpu, tss->es, 1, VCPU_SREG_ES))
3368                 return 1;
3369
3370         if (load_segment_descriptor(vcpu, tss->cs, 9, VCPU_SREG_CS))
3371                 return 1;
3372
3373         if (load_segment_descriptor(vcpu, tss->ss, 1, VCPU_SREG_SS))
3374                 return 1;
3375
3376         if (load_segment_descriptor(vcpu, tss->ds, 1, VCPU_SREG_DS))
3377                 return 1;
3378
3379         if (load_segment_descriptor(vcpu, tss->fs, 1, VCPU_SREG_FS))
3380                 return 1;
3381
3382         if (load_segment_descriptor(vcpu, tss->gs, 1, VCPU_SREG_GS))
3383                 return 1;
3384         return 0;
3385 }
3386
3387 static void save_state_to_tss16(struct kvm_vcpu *vcpu,
3388                                 struct tss_segment_16 *tss)
3389 {
3390         tss->ip = vcpu->arch.rip;
3391         tss->flag = kvm_x86_ops->get_rflags(vcpu);
3392         tss->ax = vcpu->arch.regs[VCPU_REGS_RAX];
3393         tss->cx = vcpu->arch.regs[VCPU_REGS_RCX];
3394         tss->dx = vcpu->arch.regs[VCPU_REGS_RDX];
3395         tss->bx = vcpu->arch.regs[VCPU_REGS_RBX];
3396         tss->sp = vcpu->arch.regs[VCPU_REGS_RSP];
3397         tss->bp = vcpu->arch.regs[VCPU_REGS_RBP];
3398         tss->si = vcpu->arch.regs[VCPU_REGS_RSI];
3399         tss->di = vcpu->arch.regs[VCPU_REGS_RDI];
3400
3401         tss->es = get_segment_selector(vcpu, VCPU_SREG_ES);
3402         tss->cs = get_segment_selector(vcpu, VCPU_SREG_CS);
3403         tss->ss = get_segment_selector(vcpu, VCPU_SREG_SS);
3404         tss->ds = get_segment_selector(vcpu, VCPU_SREG_DS);
3405         tss->ldt = get_segment_selector(vcpu, VCPU_SREG_LDTR);
3406         tss->prev_task_link = get_segment_selector(vcpu, VCPU_SREG_TR);
3407 }
3408
3409 static int load_state_from_tss16(struct kvm_vcpu *vcpu,
3410                                  struct tss_segment_16 *tss)
3411 {
3412         vcpu->arch.rip = tss->ip;
3413         kvm_x86_ops->set_rflags(vcpu, tss->flag | 2);
3414         vcpu->arch.regs[VCPU_REGS_RAX] = tss->ax;
3415         vcpu->arch.regs[VCPU_REGS_RCX] = tss->cx;
3416         vcpu->arch.regs[VCPU_REGS_RDX] = tss->dx;
3417         vcpu->arch.regs[VCPU_REGS_RBX] = tss->bx;
3418         vcpu->arch.regs[VCPU_REGS_RSP] = tss->sp;
3419         vcpu->arch.regs[VCPU_REGS_RBP] = tss->bp;
3420         vcpu->arch.regs[VCPU_REGS_RSI] = tss->si;
3421         vcpu->arch.regs[VCPU_REGS_RDI] = tss->di;
3422
3423         if (load_segment_descriptor(vcpu, tss->ldt, 0, VCPU_SREG_LDTR))
3424                 return 1;
3425
3426         if (load_segment_descriptor(vcpu, tss->es, 1, VCPU_SREG_ES))
3427                 return 1;
3428
3429         if (load_segment_descriptor(vcpu, tss->cs, 9, VCPU_SREG_CS))
3430                 return 1;
3431
3432         if (load_segment_descriptor(vcpu, tss->ss, 1, VCPU_SREG_SS))
3433                 return 1;
3434
3435         if (load_segment_descriptor(vcpu, tss->ds, 1, VCPU_SREG_DS))
3436                 return 1;
3437         return 0;
3438 }
3439
3440 static int kvm_task_switch_16(struct kvm_vcpu *vcpu, u16 tss_selector,
3441                        struct desc_struct *cseg_desc,
3442                        struct desc_struct *nseg_desc)
3443 {
3444         struct tss_segment_16 tss_segment_16;
3445         int ret = 0;
3446
3447         if (load_tss_segment16(vcpu, cseg_desc, &tss_segment_16))
3448                 goto out;
3449
3450         save_state_to_tss16(vcpu, &tss_segment_16);
3451         save_tss_segment16(vcpu, cseg_desc, &tss_segment_16);
3452
3453         if (load_tss_segment16(vcpu, nseg_desc, &tss_segment_16))
3454                 goto out;
3455         if (load_state_from_tss16(vcpu, &tss_segment_16))
3456                 goto out;
3457
3458         ret = 1;
3459 out:
3460         return ret;
3461 }
3462
3463 static int kvm_task_switch_32(struct kvm_vcpu *vcpu, u16 tss_selector,
3464                        struct desc_struct *cseg_desc,
3465                        struct desc_struct *nseg_desc)
3466 {
3467         struct tss_segment_32 tss_segment_32;
3468         int ret = 0;
3469
3470         if (load_tss_segment32(vcpu, cseg_desc, &tss_segment_32))
3471                 goto out;
3472
3473         save_state_to_tss32(vcpu, &tss_segment_32);
3474         save_tss_segment32(vcpu, cseg_desc, &tss_segment_32);
3475
3476         if (load_tss_segment32(vcpu, nseg_desc, &tss_segment_32))
3477                 goto out;
3478         if (load_state_from_tss32(vcpu, &tss_segment_32))
3479                 goto out;
3480
3481         ret = 1;
3482 out:
3483         return ret;
3484 }
3485
3486 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int reason)
3487 {
3488         struct kvm_segment tr_seg;
3489         struct desc_struct cseg_desc;
3490         struct desc_struct nseg_desc;
3491         int ret = 0;
3492
3493         get_segment(vcpu, &tr_seg, VCPU_SREG_TR);
3494
3495         if (load_guest_segment_descriptor(vcpu, tss_selector, &nseg_desc))
3496                 goto out;
3497
3498         if (load_guest_segment_descriptor(vcpu, tr_seg.selector, &cseg_desc))
3499                 goto out;
3500
3501
3502         if (reason != TASK_SWITCH_IRET) {
3503                 int cpl;
3504
3505                 cpl = kvm_x86_ops->get_cpl(vcpu);
3506                 if ((tss_selector & 3) > nseg_desc.dpl || cpl > nseg_desc.dpl) {
3507                         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
3508                         return 1;
3509                 }
3510         }
3511
3512         if (!nseg_desc.p || (nseg_desc.limit0 | nseg_desc.limit << 16) < 0x67) {
3513                 kvm_queue_exception_e(vcpu, TS_VECTOR, tss_selector & 0xfffc);
3514                 return 1;
3515         }
3516
3517         if (reason == TASK_SWITCH_IRET || reason == TASK_SWITCH_JMP) {
3518                 cseg_desc.type &= ~(1 << 1); //clear the B flag
3519                 save_guest_segment_descriptor(vcpu, tr_seg.selector,
3520                                               &cseg_desc);
3521         }
3522
3523         if (reason == TASK_SWITCH_IRET) {
3524                 u32 eflags = kvm_x86_ops->get_rflags(vcpu);
3525                 kvm_x86_ops->set_rflags(vcpu, eflags & ~X86_EFLAGS_NT);
3526         }
3527
3528         kvm_x86_ops->skip_emulated_instruction(vcpu);
3529         kvm_x86_ops->cache_regs(vcpu);
3530
3531         if (nseg_desc.type & 8)
3532                 ret = kvm_task_switch_32(vcpu, tss_selector, &cseg_desc,
3533                                          &nseg_desc);
3534         else
3535                 ret = kvm_task_switch_16(vcpu, tss_selector, &cseg_desc,
3536                                          &nseg_desc);
3537
3538         if (reason == TASK_SWITCH_CALL || reason == TASK_SWITCH_GATE) {
3539                 u32 eflags = kvm_x86_ops->get_rflags(vcpu);
3540                 kvm_x86_ops->set_rflags(vcpu, eflags | X86_EFLAGS_NT);
3541         }
3542
3543         if (reason != TASK_SWITCH_IRET) {
3544                 nseg_desc.type |= (1 << 1);
3545                 save_guest_segment_descriptor(vcpu, tss_selector,
3546                                               &nseg_desc);
3547         }
3548
3549         kvm_x86_ops->set_cr0(vcpu, vcpu->arch.cr0 | X86_CR0_TS);
3550         seg_desct_to_kvm_desct(&nseg_desc, tss_selector, &tr_seg);
3551         tr_seg.type = 11;
3552         set_segment(vcpu, &tr_seg, VCPU_SREG_TR);
3553 out:
3554         kvm_x86_ops->decache_regs(vcpu);
3555         return ret;
3556 }
3557 EXPORT_SYMBOL_GPL(kvm_task_switch);
3558
3559 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
3560                                   struct kvm_sregs *sregs)
3561 {
3562         int mmu_reset_needed = 0;
3563         int i, pending_vec, max_bits;
3564         struct descriptor_table dt;
3565
3566         vcpu_load(vcpu);
3567
3568         dt.limit = sregs->idt.limit;
3569         dt.base = sregs->idt.base;
3570         kvm_x86_ops->set_idt(vcpu, &dt);
3571         dt.limit = sregs->gdt.limit;
3572         dt.base = sregs->gdt.base;
3573         kvm_x86_ops->set_gdt(vcpu, &dt);
3574
3575         vcpu->arch.cr2 = sregs->cr2;
3576         mmu_reset_needed |= vcpu->arch.cr3 != sregs->cr3;
3577         vcpu->arch.cr3 = sregs->cr3;
3578
3579         kvm_set_cr8(vcpu, sregs->cr8);
3580
3581         mmu_reset_needed |= vcpu->arch.shadow_efer != sregs->efer;
3582         kvm_x86_ops->set_efer(vcpu, sregs->efer);
3583         kvm_set_apic_base(vcpu, sregs->apic_base);
3584
3585         kvm_x86_ops->decache_cr4_guest_bits(vcpu);
3586
3587         mmu_reset_needed |= vcpu->arch.cr0 != sregs->cr0;
3588         kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
3589         vcpu->arch.cr0 = sregs->cr0;
3590
3591         mmu_reset_needed |= vcpu->arch.cr4 != sregs->cr4;
3592         kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
3593         if (!is_long_mode(vcpu) && is_pae(vcpu))
3594                 load_pdptrs(vcpu, vcpu->arch.cr3);
3595
3596         if (mmu_reset_needed)
3597                 kvm_mmu_reset_context(vcpu);
3598
3599         if (!irqchip_in_kernel(vcpu->kvm)) {
3600                 memcpy(vcpu->arch.irq_pending, sregs->interrupt_bitmap,
3601                        sizeof vcpu->arch.irq_pending);
3602                 vcpu->arch.irq_summary = 0;
3603                 for (i = 0; i < ARRAY_SIZE(vcpu->arch.irq_pending); ++i)
3604                         if (vcpu->arch.irq_pending[i])
3605                                 __set_bit(i, &vcpu->arch.irq_summary);
3606         } else {
3607                 max_bits = (sizeof sregs->interrupt_bitmap) << 3;
3608                 pending_vec = find_first_bit(
3609                         (const unsigned long *)sregs->interrupt_bitmap,
3610                         max_bits);
3611                 /* Only pending external irq is handled here */
3612                 if (pending_vec < max_bits) {
3613                         kvm_x86_ops->set_irq(vcpu, pending_vec);
3614                         pr_debug("Set back pending irq %d\n",
3615                                  pending_vec);
3616                 }
3617         }
3618
3619         set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
3620         set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
3621         set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
3622         set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
3623         set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
3624         set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
3625
3626         set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
3627         set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
3628
3629         vcpu_put(vcpu);
3630
3631         return 0;
3632 }
3633
3634 int kvm_arch_vcpu_ioctl_debug_guest(struct kvm_vcpu *vcpu,
3635                                     struct kvm_debug_guest *dbg)
3636 {
3637         int r;
3638
3639         vcpu_load(vcpu);
3640
3641         r = kvm_x86_ops->set_guest_debug(vcpu, dbg);
3642
3643         vcpu_put(vcpu);
3644
3645         return r;
3646 }
3647
3648 /*
3649  * fxsave fpu state.  Taken from x86_64/processor.h.  To be killed when
3650  * we have asm/x86/processor.h
3651  */
3652 struct fxsave {
3653         u16     cwd;
3654         u16     swd;
3655         u16     twd;
3656         u16     fop;
3657         u64     rip;
3658         u64     rdp;
3659         u32     mxcsr;
3660         u32     mxcsr_mask;
3661         u32     st_space[32];   /* 8*16 bytes for each FP-reg = 128 bytes */
3662 #ifdef CONFIG_X86_64
3663         u32     xmm_space[64];  /* 16*16 bytes for each XMM-reg = 256 bytes */
3664 #else
3665         u32     xmm_space[32];  /* 8*16 bytes for each XMM-reg = 128 bytes */
3666 #endif
3667 };
3668
3669 /*
3670  * Translate a guest virtual address to a guest physical address.
3671  */
3672 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
3673                                     struct kvm_translation *tr)
3674 {
3675         unsigned long vaddr = tr->linear_address;
3676         gpa_t gpa;
3677
3678         vcpu_load(vcpu);
3679         down_read(&vcpu->kvm->slots_lock);
3680         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, vaddr);
3681         up_read(&vcpu->kvm->slots_lock);
3682         tr->physical_address = gpa;
3683         tr->valid = gpa != UNMAPPED_GVA;
3684         tr->writeable = 1;
3685         tr->usermode = 0;
3686         vcpu_put(vcpu);
3687
3688         return 0;
3689 }
3690
3691 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
3692 {
3693         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
3694
3695         vcpu_load(vcpu);
3696
3697         memcpy(fpu->fpr, fxsave->st_space, 128);
3698         fpu->fcw = fxsave->cwd;
3699         fpu->fsw = fxsave->swd;
3700         fpu->ftwx = fxsave->twd;
3701         fpu->last_opcode = fxsave->fop;
3702         fpu->last_ip = fxsave->rip;
3703         fpu->last_dp = fxsave->rdp;
3704         memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
3705
3706         vcpu_put(vcpu);
3707
3708         return 0;
3709 }
3710
3711 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
3712 {
3713         struct fxsave *fxsave = (struct fxsave *)&vcpu->arch.guest_fx_image;
3714
3715         vcpu_load(vcpu);
3716
3717         memcpy(fxsave->st_space, fpu->fpr, 128);
3718         fxsave->cwd = fpu->fcw;
3719         fxsave->swd = fpu->fsw;
3720         fxsave->twd = fpu->ftwx;
3721         fxsave->fop = fpu->last_opcode;
3722         fxsave->rip = fpu->last_ip;
3723         fxsave->rdp = fpu->last_dp;
3724         memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
3725
3726         vcpu_put(vcpu);
3727
3728         return 0;
3729 }
3730
3731 void fx_init(struct kvm_vcpu *vcpu)
3732 {
3733         unsigned after_mxcsr_mask;
3734
3735         /*
3736          * Touch the fpu the first time in non atomic context as if
3737          * this is the first fpu instruction the exception handler
3738          * will fire before the instruction returns and it'll have to
3739          * allocate ram with GFP_KERNEL.
3740          */
3741         if (!used_math())
3742                 fx_save(&vcpu->arch.host_fx_image);
3743
3744         /* Initialize guest FPU by resetting ours and saving into guest's */
3745         preempt_disable();
3746         fx_save(&vcpu->arch.host_fx_image);
3747         fx_finit();
3748         fx_save(&vcpu->arch.guest_fx_image);
3749         fx_restore(&vcpu->arch.host_fx_image);
3750         preempt_enable();
3751
3752         vcpu->arch.cr0 |= X86_CR0_ET;
3753         after_mxcsr_mask = offsetof(struct i387_fxsave_struct, st_space);
3754         vcpu->arch.guest_fx_image.mxcsr = 0x1f80;
3755         memset((void *)&vcpu->arch.guest_fx_image + after_mxcsr_mask,
3756                0, sizeof(struct i387_fxsave_struct) - after_mxcsr_mask);
3757 }
3758 EXPORT_SYMBOL_GPL(fx_init);
3759
3760 void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
3761 {
3762         if (!vcpu->fpu_active || vcpu->guest_fpu_loaded)
3763                 return;
3764
3765         vcpu->guest_fpu_loaded = 1;
3766         fx_save(&vcpu->arch.host_fx_image);
3767         fx_restore(&vcpu->arch.guest_fx_image);
3768 }
3769 EXPORT_SYMBOL_GPL(kvm_load_guest_fpu);
3770
3771 void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
3772 {
3773         if (!vcpu->guest_fpu_loaded)
3774                 return;
3775
3776         vcpu->guest_fpu_loaded = 0;
3777         fx_save(&vcpu->arch.guest_fx_image);
3778         fx_restore(&vcpu->arch.host_fx_image);
3779         ++vcpu->stat.fpu_reload;
3780 }
3781 EXPORT_SYMBOL_GPL(kvm_put_guest_fpu);
3782
3783 void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
3784 {
3785         kvm_x86_ops->vcpu_free(vcpu);
3786 }
3787
3788 struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
3789                                                 unsigned int id)
3790 {
3791         return kvm_x86_ops->vcpu_create(kvm, id);
3792 }
3793
3794 int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
3795 {
3796         int r;
3797
3798         /* We do fxsave: this must be aligned. */
3799         BUG_ON((unsigned long)&vcpu->arch.host_fx_image & 0xF);
3800
3801         vcpu_load(vcpu);
3802         r = kvm_arch_vcpu_reset(vcpu);
3803         if (r == 0)
3804                 r = kvm_mmu_setup(vcpu);
3805         vcpu_put(vcpu);
3806         if (r < 0)
3807                 goto free_vcpu;
3808
3809         return 0;
3810 free_vcpu:
3811         kvm_x86_ops->vcpu_free(vcpu);
3812         return r;
3813 }
3814
3815 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
3816 {
3817         vcpu_load(vcpu);
3818         kvm_mmu_unload(vcpu);
3819         vcpu_put(vcpu);
3820
3821         kvm_x86_ops->vcpu_free(vcpu);
3822 }
3823
3824 int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
3825 {
3826         return kvm_x86_ops->vcpu_reset(vcpu);
3827 }
3828
3829 void kvm_arch_hardware_enable(void *garbage)
3830 {
3831         kvm_x86_ops->hardware_enable(garbage);
3832 }
3833
3834 void kvm_arch_hardware_disable(void *garbage)
3835 {
3836         kvm_x86_ops->hardware_disable(garbage);
3837 }
3838
3839 int kvm_arch_hardware_setup(void)
3840 {
3841         return kvm_x86_ops->hardware_setup();
3842 }
3843
3844 void kvm_arch_hardware_unsetup(void)
3845 {
3846         kvm_x86_ops->hardware_unsetup();
3847 }
3848
3849 void kvm_arch_check_processor_compat(void *rtn)
3850 {
3851         kvm_x86_ops->check_processor_compatibility(rtn);
3852 }
3853
3854 int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
3855 {
3856         struct page *page;
3857         struct kvm *kvm;
3858         int r;
3859
3860         BUG_ON(vcpu->kvm == NULL);
3861         kvm = vcpu->kvm;
3862
3863         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
3864         if (!irqchip_in_kernel(kvm) || vcpu->vcpu_id == 0)
3865                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3866         else
3867                 vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
3868
3869         page = alloc_page(GFP_KERNEL | __GFP_ZERO);
3870         if (!page) {
3871                 r = -ENOMEM;
3872                 goto fail;
3873         }
3874         vcpu->arch.pio_data = page_address(page);
3875
3876         r = kvm_mmu_create(vcpu);
3877         if (r < 0)
3878                 goto fail_free_pio_data;
3879
3880         if (irqchip_in_kernel(kvm)) {
3881                 r = kvm_create_lapic(vcpu);
3882                 if (r < 0)
3883                         goto fail_mmu_destroy;
3884         }
3885
3886         return 0;
3887
3888 fail_mmu_destroy:
3889         kvm_mmu_destroy(vcpu);
3890 fail_free_pio_data:
3891         free_page((unsigned long)vcpu->arch.pio_data);
3892 fail:
3893         return r;
3894 }
3895
3896 void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
3897 {
3898         kvm_free_lapic(vcpu);
3899         down_read(&vcpu->kvm->slots_lock);
3900         kvm_mmu_destroy(vcpu);
3901         up_read(&vcpu->kvm->slots_lock);
3902         free_page((unsigned long)vcpu->arch.pio_data);
3903 }
3904
3905 struct  kvm *kvm_arch_create_vm(void)
3906 {
3907         struct kvm *kvm = kzalloc(sizeof(struct kvm), GFP_KERNEL);
3908
3909         if (!kvm)
3910                 return ERR_PTR(-ENOMEM);
3911
3912         INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
3913
3914         return kvm;
3915 }
3916
3917 static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
3918 {
3919         vcpu_load(vcpu);
3920         kvm_mmu_unload(vcpu);
3921         vcpu_put(vcpu);
3922 }
3923
3924 static void kvm_free_vcpus(struct kvm *kvm)
3925 {
3926         unsigned int i;
3927
3928         /*
3929          * Unpin any mmu pages first.
3930          */
3931         for (i = 0; i < KVM_MAX_VCPUS; ++i)
3932                 if (kvm->vcpus[i])
3933                         kvm_unload_vcpu_mmu(kvm->vcpus[i]);
3934         for (i = 0; i < KVM_MAX_VCPUS; ++i) {
3935                 if (kvm->vcpus[i]) {
3936                         kvm_arch_vcpu_free(kvm->vcpus[i]);
3937                         kvm->vcpus[i] = NULL;
3938                 }
3939         }
3940
3941 }
3942
3943 void kvm_arch_destroy_vm(struct kvm *kvm)
3944 {
3945         kvm_free_pit(kvm);
3946         kfree(kvm->arch.vpic);
3947         kfree(kvm->arch.vioapic);
3948         kvm_free_vcpus(kvm);
3949         kvm_free_physmem(kvm);
3950         if (kvm->arch.apic_access_page)
3951                 put_page(kvm->arch.apic_access_page);
3952         if (kvm->arch.ept_identity_pagetable)
3953                 put_page(kvm->arch.ept_identity_pagetable);
3954         kfree(kvm);
3955 }
3956
3957 int kvm_arch_set_memory_region(struct kvm *kvm,
3958                                 struct kvm_userspace_memory_region *mem,
3959                                 struct kvm_memory_slot old,
3960                                 int user_alloc)
3961 {
3962         int npages = mem->memory_size >> PAGE_SHIFT;
3963         struct kvm_memory_slot *memslot = &kvm->memslots[mem->slot];
3964
3965         /*To keep backward compatibility with older userspace,
3966          *x86 needs to hanlde !user_alloc case.
3967          */
3968         if (!user_alloc) {
3969                 if (npages && !old.rmap) {
3970                         down_write(&current->mm->mmap_sem);
3971                         memslot->userspace_addr = do_mmap(NULL, 0,
3972                                                      npages * PAGE_SIZE,
3973                                                      PROT_READ | PROT_WRITE,
3974                                                      MAP_SHARED | MAP_ANONYMOUS,
3975                                                      0);
3976                         up_write(&current->mm->mmap_sem);
3977
3978                         if (IS_ERR((void *)memslot->userspace_addr))
3979                                 return PTR_ERR((void *)memslot->userspace_addr);
3980                 } else {
3981                         if (!old.user_alloc && old.rmap) {
3982                                 int ret;
3983
3984                                 down_write(&current->mm->mmap_sem);
3985                                 ret = do_munmap(current->mm, old.userspace_addr,
3986                                                 old.npages * PAGE_SIZE);
3987                                 up_write(&current->mm->mmap_sem);
3988                                 if (ret < 0)
3989                                         printk(KERN_WARNING
3990                                        "kvm_vm_ioctl_set_memory_region: "
3991                                        "failed to munmap memory\n");
3992                         }
3993                 }
3994         }
3995
3996         if (!kvm->arch.n_requested_mmu_pages) {
3997                 unsigned int nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
3998                 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
3999         }
4000
4001         kvm_mmu_slot_remove_write_access(kvm, mem->slot);
4002         kvm_flush_remote_tlbs(kvm);
4003
4004         return 0;
4005 }
4006
4007 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
4008 {
4009         return vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE
4010                || vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED;
4011 }
4012
4013 static void vcpu_kick_intr(void *info)
4014 {
4015 #ifdef DEBUG
4016         struct kvm_vcpu *vcpu = (struct kvm_vcpu *)info;
4017         printk(KERN_DEBUG "vcpu_kick_intr %p \n", vcpu);
4018 #endif
4019 }
4020
4021 void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
4022 {
4023         int ipi_pcpu = vcpu->cpu;
4024         int cpu = get_cpu();
4025
4026         if (waitqueue_active(&vcpu->wq)) {
4027                 wake_up_interruptible(&vcpu->wq);
4028                 ++vcpu->stat.halt_wakeup;
4029         }
4030         /*
4031          * We may be called synchronously with irqs disabled in guest mode,
4032          * So need not to call smp_call_function_single() in that case.
4033          */
4034         if (vcpu->guest_mode && vcpu->cpu != cpu)
4035                 smp_call_function_single(ipi_pcpu, vcpu_kick_intr, vcpu, 0);
4036         put_cpu();
4037 }