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