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