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