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