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