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