Merge branch 'x86-trampoline-for-linus' of git://git.kernel.org/pub/scm/linux/kernel...
[linux-2.6-microblaze.git] / arch / x86 / kvm / vmx.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
9  *
10  * Authors:
11  *   Avi Kivity   <avi@qumranet.com>
12  *   Yaniv Kamay  <yaniv@qumranet.com>
13  *
14  * This work is licensed under the terms of the GNU GPL, version 2.  See
15  * the COPYING file in the top-level directory.
16  *
17  */
18
19 #include "irq.h"
20 #include "mmu.h"
21 #include "cpuid.h"
22
23 #include <linux/kvm_host.h>
24 #include <linux/module.h>
25 #include <linux/kernel.h>
26 #include <linux/mm.h>
27 #include <linux/highmem.h>
28 #include <linux/sched.h>
29 #include <linux/moduleparam.h>
30 #include <linux/mod_devicetable.h>
31 #include <linux/ftrace_event.h>
32 #include <linux/slab.h>
33 #include <linux/tboot.h>
34 #include "kvm_cache_regs.h"
35 #include "x86.h"
36
37 #include <asm/io.h>
38 #include <asm/desc.h>
39 #include <asm/vmx.h>
40 #include <asm/virtext.h>
41 #include <asm/mce.h>
42 #include <asm/i387.h>
43 #include <asm/xcr.h>
44 #include <asm/perf_event.h>
45
46 #include "trace.h"
47
48 #define __ex(x) __kvm_handle_fault_on_reboot(x)
49 #define __ex_clear(x, reg) \
50         ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
51
52 MODULE_AUTHOR("Qumranet");
53 MODULE_LICENSE("GPL");
54
55 static const struct x86_cpu_id vmx_cpu_id[] = {
56         X86_FEATURE_MATCH(X86_FEATURE_VMX),
57         {}
58 };
59 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
60
61 static bool __read_mostly enable_vpid = 1;
62 module_param_named(vpid, enable_vpid, bool, 0444);
63
64 static bool __read_mostly flexpriority_enabled = 1;
65 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
66
67 static bool __read_mostly enable_ept = 1;
68 module_param_named(ept, enable_ept, bool, S_IRUGO);
69
70 static bool __read_mostly enable_unrestricted_guest = 1;
71 module_param_named(unrestricted_guest,
72                         enable_unrestricted_guest, bool, S_IRUGO);
73
74 static bool __read_mostly emulate_invalid_guest_state = 0;
75 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
76
77 static bool __read_mostly vmm_exclusive = 1;
78 module_param(vmm_exclusive, bool, S_IRUGO);
79
80 static bool __read_mostly fasteoi = 1;
81 module_param(fasteoi, bool, S_IRUGO);
82
83 /*
84  * If nested=1, nested virtualization is supported, i.e., guests may use
85  * VMX and be a hypervisor for its own guests. If nested=0, guests may not
86  * use VMX instructions.
87  */
88 static bool __read_mostly nested = 0;
89 module_param(nested, bool, S_IRUGO);
90
91 #define KVM_GUEST_CR0_MASK_UNRESTRICTED_GUEST                           \
92         (X86_CR0_WP | X86_CR0_NE | X86_CR0_NW | X86_CR0_CD)
93 #define KVM_GUEST_CR0_MASK                                              \
94         (KVM_GUEST_CR0_MASK_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
95 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST                         \
96         (X86_CR0_WP | X86_CR0_NE)
97 #define KVM_VM_CR0_ALWAYS_ON                                            \
98         (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
99 #define KVM_CR4_GUEST_OWNED_BITS                                      \
100         (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR      \
101          | X86_CR4_OSXMMEXCPT)
102
103 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
104 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
105
106 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
107
108 /*
109  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
110  * ple_gap:    upper bound on the amount of time between two successive
111  *             executions of PAUSE in a loop. Also indicate if ple enabled.
112  *             According to test, this time is usually smaller than 128 cycles.
113  * ple_window: upper bound on the amount of time a guest is allowed to execute
114  *             in a PAUSE loop. Tests indicate that most spinlocks are held for
115  *             less than 2^12 cycles
116  * Time is measured based on a counter that runs at the same rate as the TSC,
117  * refer SDM volume 3b section 21.6.13 & 22.1.3.
118  */
119 #define KVM_VMX_DEFAULT_PLE_GAP    128
120 #define KVM_VMX_DEFAULT_PLE_WINDOW 4096
121 static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
122 module_param(ple_gap, int, S_IRUGO);
123
124 static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
125 module_param(ple_window, int, S_IRUGO);
126
127 #define NR_AUTOLOAD_MSRS 8
128 #define VMCS02_POOL_SIZE 1
129
130 struct vmcs {
131         u32 revision_id;
132         u32 abort;
133         char data[0];
134 };
135
136 /*
137  * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
138  * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
139  * loaded on this CPU (so we can clear them if the CPU goes down).
140  */
141 struct loaded_vmcs {
142         struct vmcs *vmcs;
143         int cpu;
144         int launched;
145         struct list_head loaded_vmcss_on_cpu_link;
146 };
147
148 struct shared_msr_entry {
149         unsigned index;
150         u64 data;
151         u64 mask;
152 };
153
154 /*
155  * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
156  * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
157  * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
158  * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
159  * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
160  * More than one of these structures may exist, if L1 runs multiple L2 guests.
161  * nested_vmx_run() will use the data here to build a vmcs02: a VMCS for the
162  * underlying hardware which will be used to run L2.
163  * This structure is packed to ensure that its layout is identical across
164  * machines (necessary for live migration).
165  * If there are changes in this struct, VMCS12_REVISION must be changed.
166  */
167 typedef u64 natural_width;
168 struct __packed vmcs12 {
169         /* According to the Intel spec, a VMCS region must start with the
170          * following two fields. Then follow implementation-specific data.
171          */
172         u32 revision_id;
173         u32 abort;
174
175         u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
176         u32 padding[7]; /* room for future expansion */
177
178         u64 io_bitmap_a;
179         u64 io_bitmap_b;
180         u64 msr_bitmap;
181         u64 vm_exit_msr_store_addr;
182         u64 vm_exit_msr_load_addr;
183         u64 vm_entry_msr_load_addr;
184         u64 tsc_offset;
185         u64 virtual_apic_page_addr;
186         u64 apic_access_addr;
187         u64 ept_pointer;
188         u64 guest_physical_address;
189         u64 vmcs_link_pointer;
190         u64 guest_ia32_debugctl;
191         u64 guest_ia32_pat;
192         u64 guest_ia32_efer;
193         u64 guest_ia32_perf_global_ctrl;
194         u64 guest_pdptr0;
195         u64 guest_pdptr1;
196         u64 guest_pdptr2;
197         u64 guest_pdptr3;
198         u64 host_ia32_pat;
199         u64 host_ia32_efer;
200         u64 host_ia32_perf_global_ctrl;
201         u64 padding64[8]; /* room for future expansion */
202         /*
203          * To allow migration of L1 (complete with its L2 guests) between
204          * machines of different natural widths (32 or 64 bit), we cannot have
205          * unsigned long fields with no explict size. We use u64 (aliased
206          * natural_width) instead. Luckily, x86 is little-endian.
207          */
208         natural_width cr0_guest_host_mask;
209         natural_width cr4_guest_host_mask;
210         natural_width cr0_read_shadow;
211         natural_width cr4_read_shadow;
212         natural_width cr3_target_value0;
213         natural_width cr3_target_value1;
214         natural_width cr3_target_value2;
215         natural_width cr3_target_value3;
216         natural_width exit_qualification;
217         natural_width guest_linear_address;
218         natural_width guest_cr0;
219         natural_width guest_cr3;
220         natural_width guest_cr4;
221         natural_width guest_es_base;
222         natural_width guest_cs_base;
223         natural_width guest_ss_base;
224         natural_width guest_ds_base;
225         natural_width guest_fs_base;
226         natural_width guest_gs_base;
227         natural_width guest_ldtr_base;
228         natural_width guest_tr_base;
229         natural_width guest_gdtr_base;
230         natural_width guest_idtr_base;
231         natural_width guest_dr7;
232         natural_width guest_rsp;
233         natural_width guest_rip;
234         natural_width guest_rflags;
235         natural_width guest_pending_dbg_exceptions;
236         natural_width guest_sysenter_esp;
237         natural_width guest_sysenter_eip;
238         natural_width host_cr0;
239         natural_width host_cr3;
240         natural_width host_cr4;
241         natural_width host_fs_base;
242         natural_width host_gs_base;
243         natural_width host_tr_base;
244         natural_width host_gdtr_base;
245         natural_width host_idtr_base;
246         natural_width host_ia32_sysenter_esp;
247         natural_width host_ia32_sysenter_eip;
248         natural_width host_rsp;
249         natural_width host_rip;
250         natural_width paddingl[8]; /* room for future expansion */
251         u32 pin_based_vm_exec_control;
252         u32 cpu_based_vm_exec_control;
253         u32 exception_bitmap;
254         u32 page_fault_error_code_mask;
255         u32 page_fault_error_code_match;
256         u32 cr3_target_count;
257         u32 vm_exit_controls;
258         u32 vm_exit_msr_store_count;
259         u32 vm_exit_msr_load_count;
260         u32 vm_entry_controls;
261         u32 vm_entry_msr_load_count;
262         u32 vm_entry_intr_info_field;
263         u32 vm_entry_exception_error_code;
264         u32 vm_entry_instruction_len;
265         u32 tpr_threshold;
266         u32 secondary_vm_exec_control;
267         u32 vm_instruction_error;
268         u32 vm_exit_reason;
269         u32 vm_exit_intr_info;
270         u32 vm_exit_intr_error_code;
271         u32 idt_vectoring_info_field;
272         u32 idt_vectoring_error_code;
273         u32 vm_exit_instruction_len;
274         u32 vmx_instruction_info;
275         u32 guest_es_limit;
276         u32 guest_cs_limit;
277         u32 guest_ss_limit;
278         u32 guest_ds_limit;
279         u32 guest_fs_limit;
280         u32 guest_gs_limit;
281         u32 guest_ldtr_limit;
282         u32 guest_tr_limit;
283         u32 guest_gdtr_limit;
284         u32 guest_idtr_limit;
285         u32 guest_es_ar_bytes;
286         u32 guest_cs_ar_bytes;
287         u32 guest_ss_ar_bytes;
288         u32 guest_ds_ar_bytes;
289         u32 guest_fs_ar_bytes;
290         u32 guest_gs_ar_bytes;
291         u32 guest_ldtr_ar_bytes;
292         u32 guest_tr_ar_bytes;
293         u32 guest_interruptibility_info;
294         u32 guest_activity_state;
295         u32 guest_sysenter_cs;
296         u32 host_ia32_sysenter_cs;
297         u32 padding32[8]; /* room for future expansion */
298         u16 virtual_processor_id;
299         u16 guest_es_selector;
300         u16 guest_cs_selector;
301         u16 guest_ss_selector;
302         u16 guest_ds_selector;
303         u16 guest_fs_selector;
304         u16 guest_gs_selector;
305         u16 guest_ldtr_selector;
306         u16 guest_tr_selector;
307         u16 host_es_selector;
308         u16 host_cs_selector;
309         u16 host_ss_selector;
310         u16 host_ds_selector;
311         u16 host_fs_selector;
312         u16 host_gs_selector;
313         u16 host_tr_selector;
314 };
315
316 /*
317  * VMCS12_REVISION is an arbitrary id that should be changed if the content or
318  * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
319  * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
320  */
321 #define VMCS12_REVISION 0x11e57ed0
322
323 /*
324  * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
325  * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
326  * current implementation, 4K are reserved to avoid future complications.
327  */
328 #define VMCS12_SIZE 0x1000
329
330 /* Used to remember the last vmcs02 used for some recently used vmcs12s */
331 struct vmcs02_list {
332         struct list_head list;
333         gpa_t vmptr;
334         struct loaded_vmcs vmcs02;
335 };
336
337 /*
338  * The nested_vmx structure is part of vcpu_vmx, and holds information we need
339  * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
340  */
341 struct nested_vmx {
342         /* Has the level1 guest done vmxon? */
343         bool vmxon;
344
345         /* The guest-physical address of the current VMCS L1 keeps for L2 */
346         gpa_t current_vmptr;
347         /* The host-usable pointer to the above */
348         struct page *current_vmcs12_page;
349         struct vmcs12 *current_vmcs12;
350
351         /* vmcs02_list cache of VMCSs recently used to run L2 guests */
352         struct list_head vmcs02_pool;
353         int vmcs02_num;
354         u64 vmcs01_tsc_offset;
355         /* L2 must run next, and mustn't decide to exit to L1. */
356         bool nested_run_pending;
357         /*
358          * Guest pages referred to in vmcs02 with host-physical pointers, so
359          * we must keep them pinned while L2 runs.
360          */
361         struct page *apic_access_page;
362 };
363
364 struct vcpu_vmx {
365         struct kvm_vcpu       vcpu;
366         unsigned long         host_rsp;
367         u8                    fail;
368         u8                    cpl;
369         bool                  nmi_known_unmasked;
370         u32                   exit_intr_info;
371         u32                   idt_vectoring_info;
372         ulong                 rflags;
373         struct shared_msr_entry *guest_msrs;
374         int                   nmsrs;
375         int                   save_nmsrs;
376 #ifdef CONFIG_X86_64
377         u64                   msr_host_kernel_gs_base;
378         u64                   msr_guest_kernel_gs_base;
379 #endif
380         /*
381          * loaded_vmcs points to the VMCS currently used in this vcpu. For a
382          * non-nested (L1) guest, it always points to vmcs01. For a nested
383          * guest (L2), it points to a different VMCS.
384          */
385         struct loaded_vmcs    vmcs01;
386         struct loaded_vmcs   *loaded_vmcs;
387         bool                  __launched; /* temporary, used in vmx_vcpu_run */
388         struct msr_autoload {
389                 unsigned nr;
390                 struct vmx_msr_entry guest[NR_AUTOLOAD_MSRS];
391                 struct vmx_msr_entry host[NR_AUTOLOAD_MSRS];
392         } msr_autoload;
393         struct {
394                 int           loaded;
395                 u16           fs_sel, gs_sel, ldt_sel;
396 #ifdef CONFIG_X86_64
397                 u16           ds_sel, es_sel;
398 #endif
399                 int           gs_ldt_reload_needed;
400                 int           fs_reload_needed;
401         } host_state;
402         struct {
403                 int vm86_active;
404                 ulong save_rflags;
405                 struct kvm_save_segment {
406                         u16 selector;
407                         unsigned long base;
408                         u32 limit;
409                         u32 ar;
410                 } tr, es, ds, fs, gs;
411         } rmode;
412         struct {
413                 u32 bitmask; /* 4 bits per segment (1 bit per field) */
414                 struct kvm_save_segment seg[8];
415         } segment_cache;
416         int vpid;
417         bool emulation_required;
418
419         /* Support for vnmi-less CPUs */
420         int soft_vnmi_blocked;
421         ktime_t entry_time;
422         s64 vnmi_blocked_time;
423         u32 exit_reason;
424
425         bool rdtscp_enabled;
426
427         /* Support for a guest hypervisor (nested VMX) */
428         struct nested_vmx nested;
429 };
430
431 enum segment_cache_field {
432         SEG_FIELD_SEL = 0,
433         SEG_FIELD_BASE = 1,
434         SEG_FIELD_LIMIT = 2,
435         SEG_FIELD_AR = 3,
436
437         SEG_FIELD_NR = 4
438 };
439
440 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
441 {
442         return container_of(vcpu, struct vcpu_vmx, vcpu);
443 }
444
445 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
446 #define FIELD(number, name)     [number] = VMCS12_OFFSET(name)
447 #define FIELD64(number, name)   [number] = VMCS12_OFFSET(name), \
448                                 [number##_HIGH] = VMCS12_OFFSET(name)+4
449
450 static unsigned short vmcs_field_to_offset_table[] = {
451         FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
452         FIELD(GUEST_ES_SELECTOR, guest_es_selector),
453         FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
454         FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
455         FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
456         FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
457         FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
458         FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
459         FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
460         FIELD(HOST_ES_SELECTOR, host_es_selector),
461         FIELD(HOST_CS_SELECTOR, host_cs_selector),
462         FIELD(HOST_SS_SELECTOR, host_ss_selector),
463         FIELD(HOST_DS_SELECTOR, host_ds_selector),
464         FIELD(HOST_FS_SELECTOR, host_fs_selector),
465         FIELD(HOST_GS_SELECTOR, host_gs_selector),
466         FIELD(HOST_TR_SELECTOR, host_tr_selector),
467         FIELD64(IO_BITMAP_A, io_bitmap_a),
468         FIELD64(IO_BITMAP_B, io_bitmap_b),
469         FIELD64(MSR_BITMAP, msr_bitmap),
470         FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
471         FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
472         FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
473         FIELD64(TSC_OFFSET, tsc_offset),
474         FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
475         FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
476         FIELD64(EPT_POINTER, ept_pointer),
477         FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
478         FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
479         FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
480         FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
481         FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
482         FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
483         FIELD64(GUEST_PDPTR0, guest_pdptr0),
484         FIELD64(GUEST_PDPTR1, guest_pdptr1),
485         FIELD64(GUEST_PDPTR2, guest_pdptr2),
486         FIELD64(GUEST_PDPTR3, guest_pdptr3),
487         FIELD64(HOST_IA32_PAT, host_ia32_pat),
488         FIELD64(HOST_IA32_EFER, host_ia32_efer),
489         FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
490         FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
491         FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
492         FIELD(EXCEPTION_BITMAP, exception_bitmap),
493         FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
494         FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
495         FIELD(CR3_TARGET_COUNT, cr3_target_count),
496         FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
497         FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
498         FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
499         FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
500         FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
501         FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
502         FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
503         FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
504         FIELD(TPR_THRESHOLD, tpr_threshold),
505         FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
506         FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
507         FIELD(VM_EXIT_REASON, vm_exit_reason),
508         FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
509         FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
510         FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
511         FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
512         FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
513         FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
514         FIELD(GUEST_ES_LIMIT, guest_es_limit),
515         FIELD(GUEST_CS_LIMIT, guest_cs_limit),
516         FIELD(GUEST_SS_LIMIT, guest_ss_limit),
517         FIELD(GUEST_DS_LIMIT, guest_ds_limit),
518         FIELD(GUEST_FS_LIMIT, guest_fs_limit),
519         FIELD(GUEST_GS_LIMIT, guest_gs_limit),
520         FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
521         FIELD(GUEST_TR_LIMIT, guest_tr_limit),
522         FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
523         FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
524         FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
525         FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
526         FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
527         FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
528         FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
529         FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
530         FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
531         FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
532         FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
533         FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
534         FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
535         FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
536         FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
537         FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
538         FIELD(CR0_READ_SHADOW, cr0_read_shadow),
539         FIELD(CR4_READ_SHADOW, cr4_read_shadow),
540         FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
541         FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
542         FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
543         FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
544         FIELD(EXIT_QUALIFICATION, exit_qualification),
545         FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
546         FIELD(GUEST_CR0, guest_cr0),
547         FIELD(GUEST_CR3, guest_cr3),
548         FIELD(GUEST_CR4, guest_cr4),
549         FIELD(GUEST_ES_BASE, guest_es_base),
550         FIELD(GUEST_CS_BASE, guest_cs_base),
551         FIELD(GUEST_SS_BASE, guest_ss_base),
552         FIELD(GUEST_DS_BASE, guest_ds_base),
553         FIELD(GUEST_FS_BASE, guest_fs_base),
554         FIELD(GUEST_GS_BASE, guest_gs_base),
555         FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
556         FIELD(GUEST_TR_BASE, guest_tr_base),
557         FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
558         FIELD(GUEST_IDTR_BASE, guest_idtr_base),
559         FIELD(GUEST_DR7, guest_dr7),
560         FIELD(GUEST_RSP, guest_rsp),
561         FIELD(GUEST_RIP, guest_rip),
562         FIELD(GUEST_RFLAGS, guest_rflags),
563         FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
564         FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
565         FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
566         FIELD(HOST_CR0, host_cr0),
567         FIELD(HOST_CR3, host_cr3),
568         FIELD(HOST_CR4, host_cr4),
569         FIELD(HOST_FS_BASE, host_fs_base),
570         FIELD(HOST_GS_BASE, host_gs_base),
571         FIELD(HOST_TR_BASE, host_tr_base),
572         FIELD(HOST_GDTR_BASE, host_gdtr_base),
573         FIELD(HOST_IDTR_BASE, host_idtr_base),
574         FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
575         FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
576         FIELD(HOST_RSP, host_rsp),
577         FIELD(HOST_RIP, host_rip),
578 };
579 static const int max_vmcs_field = ARRAY_SIZE(vmcs_field_to_offset_table);
580
581 static inline short vmcs_field_to_offset(unsigned long field)
582 {
583         if (field >= max_vmcs_field || vmcs_field_to_offset_table[field] == 0)
584                 return -1;
585         return vmcs_field_to_offset_table[field];
586 }
587
588 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
589 {
590         return to_vmx(vcpu)->nested.current_vmcs12;
591 }
592
593 static struct page *nested_get_page(struct kvm_vcpu *vcpu, gpa_t addr)
594 {
595         struct page *page = gfn_to_page(vcpu->kvm, addr >> PAGE_SHIFT);
596         if (is_error_page(page)) {
597                 kvm_release_page_clean(page);
598                 return NULL;
599         }
600         return page;
601 }
602
603 static void nested_release_page(struct page *page)
604 {
605         kvm_release_page_dirty(page);
606 }
607
608 static void nested_release_page_clean(struct page *page)
609 {
610         kvm_release_page_clean(page);
611 }
612
613 static u64 construct_eptp(unsigned long root_hpa);
614 static void kvm_cpu_vmxon(u64 addr);
615 static void kvm_cpu_vmxoff(void);
616 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3);
617 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr);
618
619 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
620 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
621 /*
622  * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
623  * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
624  */
625 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
626 static DEFINE_PER_CPU(struct desc_ptr, host_gdt);
627
628 static unsigned long *vmx_io_bitmap_a;
629 static unsigned long *vmx_io_bitmap_b;
630 static unsigned long *vmx_msr_bitmap_legacy;
631 static unsigned long *vmx_msr_bitmap_longmode;
632
633 static bool cpu_has_load_ia32_efer;
634 static bool cpu_has_load_perf_global_ctrl;
635
636 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
637 static DEFINE_SPINLOCK(vmx_vpid_lock);
638
639 static struct vmcs_config {
640         int size;
641         int order;
642         u32 revision_id;
643         u32 pin_based_exec_ctrl;
644         u32 cpu_based_exec_ctrl;
645         u32 cpu_based_2nd_exec_ctrl;
646         u32 vmexit_ctrl;
647         u32 vmentry_ctrl;
648 } vmcs_config;
649
650 static struct vmx_capability {
651         u32 ept;
652         u32 vpid;
653 } vmx_capability;
654
655 #define VMX_SEGMENT_FIELD(seg)                                  \
656         [VCPU_SREG_##seg] = {                                   \
657                 .selector = GUEST_##seg##_SELECTOR,             \
658                 .base = GUEST_##seg##_BASE,                     \
659                 .limit = GUEST_##seg##_LIMIT,                   \
660                 .ar_bytes = GUEST_##seg##_AR_BYTES,             \
661         }
662
663 static struct kvm_vmx_segment_field {
664         unsigned selector;
665         unsigned base;
666         unsigned limit;
667         unsigned ar_bytes;
668 } kvm_vmx_segment_fields[] = {
669         VMX_SEGMENT_FIELD(CS),
670         VMX_SEGMENT_FIELD(DS),
671         VMX_SEGMENT_FIELD(ES),
672         VMX_SEGMENT_FIELD(FS),
673         VMX_SEGMENT_FIELD(GS),
674         VMX_SEGMENT_FIELD(SS),
675         VMX_SEGMENT_FIELD(TR),
676         VMX_SEGMENT_FIELD(LDTR),
677 };
678
679 static u64 host_efer;
680
681 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
682
683 /*
684  * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
685  * away by decrementing the array size.
686  */
687 static const u32 vmx_msr_index[] = {
688 #ifdef CONFIG_X86_64
689         MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
690 #endif
691         MSR_EFER, MSR_TSC_AUX, MSR_STAR,
692 };
693 #define NR_VMX_MSR ARRAY_SIZE(vmx_msr_index)
694
695 static inline bool is_page_fault(u32 intr_info)
696 {
697         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
698                              INTR_INFO_VALID_MASK)) ==
699                 (INTR_TYPE_HARD_EXCEPTION | PF_VECTOR | INTR_INFO_VALID_MASK);
700 }
701
702 static inline bool is_no_device(u32 intr_info)
703 {
704         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
705                              INTR_INFO_VALID_MASK)) ==
706                 (INTR_TYPE_HARD_EXCEPTION | NM_VECTOR | INTR_INFO_VALID_MASK);
707 }
708
709 static inline bool is_invalid_opcode(u32 intr_info)
710 {
711         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
712                              INTR_INFO_VALID_MASK)) ==
713                 (INTR_TYPE_HARD_EXCEPTION | UD_VECTOR | INTR_INFO_VALID_MASK);
714 }
715
716 static inline bool is_external_interrupt(u32 intr_info)
717 {
718         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
719                 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
720 }
721
722 static inline bool is_machine_check(u32 intr_info)
723 {
724         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
725                              INTR_INFO_VALID_MASK)) ==
726                 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
727 }
728
729 static inline bool cpu_has_vmx_msr_bitmap(void)
730 {
731         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
732 }
733
734 static inline bool cpu_has_vmx_tpr_shadow(void)
735 {
736         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
737 }
738
739 static inline bool vm_need_tpr_shadow(struct kvm *kvm)
740 {
741         return (cpu_has_vmx_tpr_shadow()) && (irqchip_in_kernel(kvm));
742 }
743
744 static inline bool cpu_has_secondary_exec_ctrls(void)
745 {
746         return vmcs_config.cpu_based_exec_ctrl &
747                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
748 }
749
750 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
751 {
752         return vmcs_config.cpu_based_2nd_exec_ctrl &
753                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
754 }
755
756 static inline bool cpu_has_vmx_flexpriority(void)
757 {
758         return cpu_has_vmx_tpr_shadow() &&
759                 cpu_has_vmx_virtualize_apic_accesses();
760 }
761
762 static inline bool cpu_has_vmx_ept_execute_only(void)
763 {
764         return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
765 }
766
767 static inline bool cpu_has_vmx_eptp_uncacheable(void)
768 {
769         return vmx_capability.ept & VMX_EPTP_UC_BIT;
770 }
771
772 static inline bool cpu_has_vmx_eptp_writeback(void)
773 {
774         return vmx_capability.ept & VMX_EPTP_WB_BIT;
775 }
776
777 static inline bool cpu_has_vmx_ept_2m_page(void)
778 {
779         return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
780 }
781
782 static inline bool cpu_has_vmx_ept_1g_page(void)
783 {
784         return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
785 }
786
787 static inline bool cpu_has_vmx_ept_4levels(void)
788 {
789         return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
790 }
791
792 static inline bool cpu_has_vmx_invept_individual_addr(void)
793 {
794         return vmx_capability.ept & VMX_EPT_EXTENT_INDIVIDUAL_BIT;
795 }
796
797 static inline bool cpu_has_vmx_invept_context(void)
798 {
799         return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
800 }
801
802 static inline bool cpu_has_vmx_invept_global(void)
803 {
804         return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
805 }
806
807 static inline bool cpu_has_vmx_invvpid_single(void)
808 {
809         return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
810 }
811
812 static inline bool cpu_has_vmx_invvpid_global(void)
813 {
814         return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
815 }
816
817 static inline bool cpu_has_vmx_ept(void)
818 {
819         return vmcs_config.cpu_based_2nd_exec_ctrl &
820                 SECONDARY_EXEC_ENABLE_EPT;
821 }
822
823 static inline bool cpu_has_vmx_unrestricted_guest(void)
824 {
825         return vmcs_config.cpu_based_2nd_exec_ctrl &
826                 SECONDARY_EXEC_UNRESTRICTED_GUEST;
827 }
828
829 static inline bool cpu_has_vmx_ple(void)
830 {
831         return vmcs_config.cpu_based_2nd_exec_ctrl &
832                 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
833 }
834
835 static inline bool vm_need_virtualize_apic_accesses(struct kvm *kvm)
836 {
837         return flexpriority_enabled && irqchip_in_kernel(kvm);
838 }
839
840 static inline bool cpu_has_vmx_vpid(void)
841 {
842         return vmcs_config.cpu_based_2nd_exec_ctrl &
843                 SECONDARY_EXEC_ENABLE_VPID;
844 }
845
846 static inline bool cpu_has_vmx_rdtscp(void)
847 {
848         return vmcs_config.cpu_based_2nd_exec_ctrl &
849                 SECONDARY_EXEC_RDTSCP;
850 }
851
852 static inline bool cpu_has_virtual_nmis(void)
853 {
854         return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
855 }
856
857 static inline bool cpu_has_vmx_wbinvd_exit(void)
858 {
859         return vmcs_config.cpu_based_2nd_exec_ctrl &
860                 SECONDARY_EXEC_WBINVD_EXITING;
861 }
862
863 static inline bool report_flexpriority(void)
864 {
865         return flexpriority_enabled;
866 }
867
868 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
869 {
870         return vmcs12->cpu_based_vm_exec_control & bit;
871 }
872
873 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
874 {
875         return (vmcs12->cpu_based_vm_exec_control &
876                         CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
877                 (vmcs12->secondary_vm_exec_control & bit);
878 }
879
880 static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12,
881         struct kvm_vcpu *vcpu)
882 {
883         return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
884 }
885
886 static inline bool is_exception(u32 intr_info)
887 {
888         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
889                 == (INTR_TYPE_HARD_EXCEPTION | INTR_INFO_VALID_MASK);
890 }
891
892 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu);
893 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
894                         struct vmcs12 *vmcs12,
895                         u32 reason, unsigned long qualification);
896
897 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
898 {
899         int i;
900
901         for (i = 0; i < vmx->nmsrs; ++i)
902                 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
903                         return i;
904         return -1;
905 }
906
907 static inline void __invvpid(int ext, u16 vpid, gva_t gva)
908 {
909     struct {
910         u64 vpid : 16;
911         u64 rsvd : 48;
912         u64 gva;
913     } operand = { vpid, 0, gva };
914
915     asm volatile (__ex(ASM_VMX_INVVPID)
916                   /* CF==1 or ZF==1 --> rc = -1 */
917                   "; ja 1f ; ud2 ; 1:"
918                   : : "a"(&operand), "c"(ext) : "cc", "memory");
919 }
920
921 static inline void __invept(int ext, u64 eptp, gpa_t gpa)
922 {
923         struct {
924                 u64 eptp, gpa;
925         } operand = {eptp, gpa};
926
927         asm volatile (__ex(ASM_VMX_INVEPT)
928                         /* CF==1 or ZF==1 --> rc = -1 */
929                         "; ja 1f ; ud2 ; 1:\n"
930                         : : "a" (&operand), "c" (ext) : "cc", "memory");
931 }
932
933 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
934 {
935         int i;
936
937         i = __find_msr_index(vmx, msr);
938         if (i >= 0)
939                 return &vmx->guest_msrs[i];
940         return NULL;
941 }
942
943 static void vmcs_clear(struct vmcs *vmcs)
944 {
945         u64 phys_addr = __pa(vmcs);
946         u8 error;
947
948         asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
949                       : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
950                       : "cc", "memory");
951         if (error)
952                 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
953                        vmcs, phys_addr);
954 }
955
956 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
957 {
958         vmcs_clear(loaded_vmcs->vmcs);
959         loaded_vmcs->cpu = -1;
960         loaded_vmcs->launched = 0;
961 }
962
963 static void vmcs_load(struct vmcs *vmcs)
964 {
965         u64 phys_addr = __pa(vmcs);
966         u8 error;
967
968         asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
969                         : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
970                         : "cc", "memory");
971         if (error)
972                 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
973                        vmcs, phys_addr);
974 }
975
976 static void __loaded_vmcs_clear(void *arg)
977 {
978         struct loaded_vmcs *loaded_vmcs = arg;
979         int cpu = raw_smp_processor_id();
980
981         if (loaded_vmcs->cpu != cpu)
982                 return; /* vcpu migration can race with cpu offline */
983         if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
984                 per_cpu(current_vmcs, cpu) = NULL;
985         list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
986         loaded_vmcs_init(loaded_vmcs);
987 }
988
989 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
990 {
991         if (loaded_vmcs->cpu != -1)
992                 smp_call_function_single(
993                         loaded_vmcs->cpu, __loaded_vmcs_clear, loaded_vmcs, 1);
994 }
995
996 static inline void vpid_sync_vcpu_single(struct vcpu_vmx *vmx)
997 {
998         if (vmx->vpid == 0)
999                 return;
1000
1001         if (cpu_has_vmx_invvpid_single())
1002                 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vmx->vpid, 0);
1003 }
1004
1005 static inline void vpid_sync_vcpu_global(void)
1006 {
1007         if (cpu_has_vmx_invvpid_global())
1008                 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
1009 }
1010
1011 static inline void vpid_sync_context(struct vcpu_vmx *vmx)
1012 {
1013         if (cpu_has_vmx_invvpid_single())
1014                 vpid_sync_vcpu_single(vmx);
1015         else
1016                 vpid_sync_vcpu_global();
1017 }
1018
1019 static inline void ept_sync_global(void)
1020 {
1021         if (cpu_has_vmx_invept_global())
1022                 __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
1023 }
1024
1025 static inline void ept_sync_context(u64 eptp)
1026 {
1027         if (enable_ept) {
1028                 if (cpu_has_vmx_invept_context())
1029                         __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
1030                 else
1031                         ept_sync_global();
1032         }
1033 }
1034
1035 static inline void ept_sync_individual_addr(u64 eptp, gpa_t gpa)
1036 {
1037         if (enable_ept) {
1038                 if (cpu_has_vmx_invept_individual_addr())
1039                         __invept(VMX_EPT_EXTENT_INDIVIDUAL_ADDR,
1040                                         eptp, gpa);
1041                 else
1042                         ept_sync_context(eptp);
1043         }
1044 }
1045
1046 static __always_inline unsigned long vmcs_readl(unsigned long field)
1047 {
1048         unsigned long value;
1049
1050         asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
1051                       : "=a"(value) : "d"(field) : "cc");
1052         return value;
1053 }
1054
1055 static __always_inline u16 vmcs_read16(unsigned long field)
1056 {
1057         return vmcs_readl(field);
1058 }
1059
1060 static __always_inline u32 vmcs_read32(unsigned long field)
1061 {
1062         return vmcs_readl(field);
1063 }
1064
1065 static __always_inline u64 vmcs_read64(unsigned long field)
1066 {
1067 #ifdef CONFIG_X86_64
1068         return vmcs_readl(field);
1069 #else
1070         return vmcs_readl(field) | ((u64)vmcs_readl(field+1) << 32);
1071 #endif
1072 }
1073
1074 static noinline void vmwrite_error(unsigned long field, unsigned long value)
1075 {
1076         printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
1077                field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
1078         dump_stack();
1079 }
1080
1081 static void vmcs_writel(unsigned long field, unsigned long value)
1082 {
1083         u8 error;
1084
1085         asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
1086                        : "=q"(error) : "a"(value), "d"(field) : "cc");
1087         if (unlikely(error))
1088                 vmwrite_error(field, value);
1089 }
1090
1091 static void vmcs_write16(unsigned long field, u16 value)
1092 {
1093         vmcs_writel(field, value);
1094 }
1095
1096 static void vmcs_write32(unsigned long field, u32 value)
1097 {
1098         vmcs_writel(field, value);
1099 }
1100
1101 static void vmcs_write64(unsigned long field, u64 value)
1102 {
1103         vmcs_writel(field, value);
1104 #ifndef CONFIG_X86_64
1105         asm volatile ("");
1106         vmcs_writel(field+1, value >> 32);
1107 #endif
1108 }
1109
1110 static void vmcs_clear_bits(unsigned long field, u32 mask)
1111 {
1112         vmcs_writel(field, vmcs_readl(field) & ~mask);
1113 }
1114
1115 static void vmcs_set_bits(unsigned long field, u32 mask)
1116 {
1117         vmcs_writel(field, vmcs_readl(field) | mask);
1118 }
1119
1120 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
1121 {
1122         vmx->segment_cache.bitmask = 0;
1123 }
1124
1125 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
1126                                        unsigned field)
1127 {
1128         bool ret;
1129         u32 mask = 1 << (seg * SEG_FIELD_NR + field);
1130
1131         if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
1132                 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
1133                 vmx->segment_cache.bitmask = 0;
1134         }
1135         ret = vmx->segment_cache.bitmask & mask;
1136         vmx->segment_cache.bitmask |= mask;
1137         return ret;
1138 }
1139
1140 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
1141 {
1142         u16 *p = &vmx->segment_cache.seg[seg].selector;
1143
1144         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
1145                 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
1146         return *p;
1147 }
1148
1149 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
1150 {
1151         ulong *p = &vmx->segment_cache.seg[seg].base;
1152
1153         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
1154                 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
1155         return *p;
1156 }
1157
1158 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
1159 {
1160         u32 *p = &vmx->segment_cache.seg[seg].limit;
1161
1162         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
1163                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
1164         return *p;
1165 }
1166
1167 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
1168 {
1169         u32 *p = &vmx->segment_cache.seg[seg].ar;
1170
1171         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
1172                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
1173         return *p;
1174 }
1175
1176 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
1177 {
1178         u32 eb;
1179
1180         eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
1181              (1u << NM_VECTOR) | (1u << DB_VECTOR);
1182         if ((vcpu->guest_debug &
1183              (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
1184             (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
1185                 eb |= 1u << BP_VECTOR;
1186         if (to_vmx(vcpu)->rmode.vm86_active)
1187                 eb = ~0;
1188         if (enable_ept)
1189                 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
1190         if (vcpu->fpu_active)
1191                 eb &= ~(1u << NM_VECTOR);
1192
1193         /* When we are running a nested L2 guest and L1 specified for it a
1194          * certain exception bitmap, we must trap the same exceptions and pass
1195          * them to L1. When running L2, we will only handle the exceptions
1196          * specified above if L1 did not want them.
1197          */
1198         if (is_guest_mode(vcpu))
1199                 eb |= get_vmcs12(vcpu)->exception_bitmap;
1200
1201         vmcs_write32(EXCEPTION_BITMAP, eb);
1202 }
1203
1204 static void clear_atomic_switch_msr_special(unsigned long entry,
1205                 unsigned long exit)
1206 {
1207         vmcs_clear_bits(VM_ENTRY_CONTROLS, entry);
1208         vmcs_clear_bits(VM_EXIT_CONTROLS, exit);
1209 }
1210
1211 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
1212 {
1213         unsigned i;
1214         struct msr_autoload *m = &vmx->msr_autoload;
1215
1216         switch (msr) {
1217         case MSR_EFER:
1218                 if (cpu_has_load_ia32_efer) {
1219                         clear_atomic_switch_msr_special(VM_ENTRY_LOAD_IA32_EFER,
1220                                         VM_EXIT_LOAD_IA32_EFER);
1221                         return;
1222                 }
1223                 break;
1224         case MSR_CORE_PERF_GLOBAL_CTRL:
1225                 if (cpu_has_load_perf_global_ctrl) {
1226                         clear_atomic_switch_msr_special(
1227                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1228                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
1229                         return;
1230                 }
1231                 break;
1232         }
1233
1234         for (i = 0; i < m->nr; ++i)
1235                 if (m->guest[i].index == msr)
1236                         break;
1237
1238         if (i == m->nr)
1239                 return;
1240         --m->nr;
1241         m->guest[i] = m->guest[m->nr];
1242         m->host[i] = m->host[m->nr];
1243         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1244         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1245 }
1246
1247 static void add_atomic_switch_msr_special(unsigned long entry,
1248                 unsigned long exit, unsigned long guest_val_vmcs,
1249                 unsigned long host_val_vmcs, u64 guest_val, u64 host_val)
1250 {
1251         vmcs_write64(guest_val_vmcs, guest_val);
1252         vmcs_write64(host_val_vmcs, host_val);
1253         vmcs_set_bits(VM_ENTRY_CONTROLS, entry);
1254         vmcs_set_bits(VM_EXIT_CONTROLS, exit);
1255 }
1256
1257 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
1258                                   u64 guest_val, u64 host_val)
1259 {
1260         unsigned i;
1261         struct msr_autoload *m = &vmx->msr_autoload;
1262
1263         switch (msr) {
1264         case MSR_EFER:
1265                 if (cpu_has_load_ia32_efer) {
1266                         add_atomic_switch_msr_special(VM_ENTRY_LOAD_IA32_EFER,
1267                                         VM_EXIT_LOAD_IA32_EFER,
1268                                         GUEST_IA32_EFER,
1269                                         HOST_IA32_EFER,
1270                                         guest_val, host_val);
1271                         return;
1272                 }
1273                 break;
1274         case MSR_CORE_PERF_GLOBAL_CTRL:
1275                 if (cpu_has_load_perf_global_ctrl) {
1276                         add_atomic_switch_msr_special(
1277                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1278                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
1279                                         GUEST_IA32_PERF_GLOBAL_CTRL,
1280                                         HOST_IA32_PERF_GLOBAL_CTRL,
1281                                         guest_val, host_val);
1282                         return;
1283                 }
1284                 break;
1285         }
1286
1287         for (i = 0; i < m->nr; ++i)
1288                 if (m->guest[i].index == msr)
1289                         break;
1290
1291         if (i == NR_AUTOLOAD_MSRS) {
1292                 printk_once(KERN_WARNING"Not enough mst switch entries. "
1293                                 "Can't add msr %x\n", msr);
1294                 return;
1295         } else if (i == m->nr) {
1296                 ++m->nr;
1297                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1298                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1299         }
1300
1301         m->guest[i].index = msr;
1302         m->guest[i].value = guest_val;
1303         m->host[i].index = msr;
1304         m->host[i].value = host_val;
1305 }
1306
1307 static void reload_tss(void)
1308 {
1309         /*
1310          * VT restores TR but not its size.  Useless.
1311          */
1312         struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
1313         struct desc_struct *descs;
1314
1315         descs = (void *)gdt->address;
1316         descs[GDT_ENTRY_TSS].type = 9; /* available TSS */
1317         load_TR_desc();
1318 }
1319
1320 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
1321 {
1322         u64 guest_efer;
1323         u64 ignore_bits;
1324
1325         guest_efer = vmx->vcpu.arch.efer;
1326
1327         /*
1328          * NX is emulated; LMA and LME handled by hardware; SCE meaninless
1329          * outside long mode
1330          */
1331         ignore_bits = EFER_NX | EFER_SCE;
1332 #ifdef CONFIG_X86_64
1333         ignore_bits |= EFER_LMA | EFER_LME;
1334         /* SCE is meaningful only in long mode on Intel */
1335         if (guest_efer & EFER_LMA)
1336                 ignore_bits &= ~(u64)EFER_SCE;
1337 #endif
1338         guest_efer &= ~ignore_bits;
1339         guest_efer |= host_efer & ignore_bits;
1340         vmx->guest_msrs[efer_offset].data = guest_efer;
1341         vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
1342
1343         clear_atomic_switch_msr(vmx, MSR_EFER);
1344         /* On ept, can't emulate nx, and must switch nx atomically */
1345         if (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX)) {
1346                 guest_efer = vmx->vcpu.arch.efer;
1347                 if (!(guest_efer & EFER_LMA))
1348                         guest_efer &= ~EFER_LME;
1349                 add_atomic_switch_msr(vmx, MSR_EFER, guest_efer, host_efer);
1350                 return false;
1351         }
1352
1353         return true;
1354 }
1355
1356 static unsigned long segment_base(u16 selector)
1357 {
1358         struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
1359         struct desc_struct *d;
1360         unsigned long table_base;
1361         unsigned long v;
1362
1363         if (!(selector & ~3))
1364                 return 0;
1365
1366         table_base = gdt->address;
1367
1368         if (selector & 4) {           /* from ldt */
1369                 u16 ldt_selector = kvm_read_ldt();
1370
1371                 if (!(ldt_selector & ~3))
1372                         return 0;
1373
1374                 table_base = segment_base(ldt_selector);
1375         }
1376         d = (struct desc_struct *)(table_base + (selector & ~7));
1377         v = get_desc_base(d);
1378 #ifdef CONFIG_X86_64
1379        if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
1380                v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
1381 #endif
1382         return v;
1383 }
1384
1385 static inline unsigned long kvm_read_tr_base(void)
1386 {
1387         u16 tr;
1388         asm("str %0" : "=g"(tr));
1389         return segment_base(tr);
1390 }
1391
1392 static void vmx_save_host_state(struct kvm_vcpu *vcpu)
1393 {
1394         struct vcpu_vmx *vmx = to_vmx(vcpu);
1395         int i;
1396
1397         if (vmx->host_state.loaded)
1398                 return;
1399
1400         vmx->host_state.loaded = 1;
1401         /*
1402          * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
1403          * allow segment selectors with cpl > 0 or ti == 1.
1404          */
1405         vmx->host_state.ldt_sel = kvm_read_ldt();
1406         vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
1407         savesegment(fs, vmx->host_state.fs_sel);
1408         if (!(vmx->host_state.fs_sel & 7)) {
1409                 vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
1410                 vmx->host_state.fs_reload_needed = 0;
1411         } else {
1412                 vmcs_write16(HOST_FS_SELECTOR, 0);
1413                 vmx->host_state.fs_reload_needed = 1;
1414         }
1415         savesegment(gs, vmx->host_state.gs_sel);
1416         if (!(vmx->host_state.gs_sel & 7))
1417                 vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
1418         else {
1419                 vmcs_write16(HOST_GS_SELECTOR, 0);
1420                 vmx->host_state.gs_ldt_reload_needed = 1;
1421         }
1422
1423 #ifdef CONFIG_X86_64
1424         savesegment(ds, vmx->host_state.ds_sel);
1425         savesegment(es, vmx->host_state.es_sel);
1426 #endif
1427
1428 #ifdef CONFIG_X86_64
1429         vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
1430         vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
1431 #else
1432         vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
1433         vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
1434 #endif
1435
1436 #ifdef CONFIG_X86_64
1437         rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1438         if (is_long_mode(&vmx->vcpu))
1439                 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1440 #endif
1441         for (i = 0; i < vmx->save_nmsrs; ++i)
1442                 kvm_set_shared_msr(vmx->guest_msrs[i].index,
1443                                    vmx->guest_msrs[i].data,
1444                                    vmx->guest_msrs[i].mask);
1445 }
1446
1447 static void __vmx_load_host_state(struct vcpu_vmx *vmx)
1448 {
1449         if (!vmx->host_state.loaded)
1450                 return;
1451
1452         ++vmx->vcpu.stat.host_state_reload;
1453         vmx->host_state.loaded = 0;
1454 #ifdef CONFIG_X86_64
1455         if (is_long_mode(&vmx->vcpu))
1456                 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1457 #endif
1458         if (vmx->host_state.gs_ldt_reload_needed) {
1459                 kvm_load_ldt(vmx->host_state.ldt_sel);
1460 #ifdef CONFIG_X86_64
1461                 load_gs_index(vmx->host_state.gs_sel);
1462 #else
1463                 loadsegment(gs, vmx->host_state.gs_sel);
1464 #endif
1465         }
1466         if (vmx->host_state.fs_reload_needed)
1467                 loadsegment(fs, vmx->host_state.fs_sel);
1468 #ifdef CONFIG_X86_64
1469         if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
1470                 loadsegment(ds, vmx->host_state.ds_sel);
1471                 loadsegment(es, vmx->host_state.es_sel);
1472         }
1473 #else
1474         /*
1475          * The sysexit path does not restore ds/es, so we must set them to
1476          * a reasonable value ourselves.
1477          */
1478         loadsegment(ds, __USER_DS);
1479         loadsegment(es, __USER_DS);
1480 #endif
1481         reload_tss();
1482 #ifdef CONFIG_X86_64
1483         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1484 #endif
1485         if (user_has_fpu())
1486                 clts();
1487         load_gdt(&__get_cpu_var(host_gdt));
1488 }
1489
1490 static void vmx_load_host_state(struct vcpu_vmx *vmx)
1491 {
1492         preempt_disable();
1493         __vmx_load_host_state(vmx);
1494         preempt_enable();
1495 }
1496
1497 /*
1498  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1499  * vcpu mutex is already taken.
1500  */
1501 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1502 {
1503         struct vcpu_vmx *vmx = to_vmx(vcpu);
1504         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
1505
1506         if (!vmm_exclusive)
1507                 kvm_cpu_vmxon(phys_addr);
1508         else if (vmx->loaded_vmcs->cpu != cpu)
1509                 loaded_vmcs_clear(vmx->loaded_vmcs);
1510
1511         if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
1512                 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1513                 vmcs_load(vmx->loaded_vmcs->vmcs);
1514         }
1515
1516         if (vmx->loaded_vmcs->cpu != cpu) {
1517                 struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
1518                 unsigned long sysenter_esp;
1519
1520                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1521                 local_irq_disable();
1522                 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1523                          &per_cpu(loaded_vmcss_on_cpu, cpu));
1524                 local_irq_enable();
1525
1526                 /*
1527                  * Linux uses per-cpu TSS and GDT, so set these when switching
1528                  * processors.
1529                  */
1530                 vmcs_writel(HOST_TR_BASE, kvm_read_tr_base()); /* 22.2.4 */
1531                 vmcs_writel(HOST_GDTR_BASE, gdt->address);   /* 22.2.4 */
1532
1533                 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1534                 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1535                 vmx->loaded_vmcs->cpu = cpu;
1536         }
1537 }
1538
1539 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1540 {
1541         __vmx_load_host_state(to_vmx(vcpu));
1542         if (!vmm_exclusive) {
1543                 __loaded_vmcs_clear(to_vmx(vcpu)->loaded_vmcs);
1544                 vcpu->cpu = -1;
1545                 kvm_cpu_vmxoff();
1546         }
1547 }
1548
1549 static void vmx_fpu_activate(struct kvm_vcpu *vcpu)
1550 {
1551         ulong cr0;
1552
1553         if (vcpu->fpu_active)
1554                 return;
1555         vcpu->fpu_active = 1;
1556         cr0 = vmcs_readl(GUEST_CR0);
1557         cr0 &= ~(X86_CR0_TS | X86_CR0_MP);
1558         cr0 |= kvm_read_cr0_bits(vcpu, X86_CR0_TS | X86_CR0_MP);
1559         vmcs_writel(GUEST_CR0, cr0);
1560         update_exception_bitmap(vcpu);
1561         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
1562         if (is_guest_mode(vcpu))
1563                 vcpu->arch.cr0_guest_owned_bits &=
1564                         ~get_vmcs12(vcpu)->cr0_guest_host_mask;
1565         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
1566 }
1567
1568 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
1569
1570 /*
1571  * Return the cr0 value that a nested guest would read. This is a combination
1572  * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
1573  * its hypervisor (cr0_read_shadow).
1574  */
1575 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
1576 {
1577         return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
1578                 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
1579 }
1580 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
1581 {
1582         return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
1583                 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
1584 }
1585
1586 static void vmx_fpu_deactivate(struct kvm_vcpu *vcpu)
1587 {
1588         /* Note that there is no vcpu->fpu_active = 0 here. The caller must
1589          * set this *before* calling this function.
1590          */
1591         vmx_decache_cr0_guest_bits(vcpu);
1592         vmcs_set_bits(GUEST_CR0, X86_CR0_TS | X86_CR0_MP);
1593         update_exception_bitmap(vcpu);
1594         vcpu->arch.cr0_guest_owned_bits = 0;
1595         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
1596         if (is_guest_mode(vcpu)) {
1597                 /*
1598                  * L1's specified read shadow might not contain the TS bit,
1599                  * so now that we turned on shadowing of this bit, we need to
1600                  * set this bit of the shadow. Like in nested_vmx_run we need
1601                  * nested_read_cr0(vmcs12), but vmcs12->guest_cr0 is not yet
1602                  * up-to-date here because we just decached cr0.TS (and we'll
1603                  * only update vmcs12->guest_cr0 on nested exit).
1604                  */
1605                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1606                 vmcs12->guest_cr0 = (vmcs12->guest_cr0 & ~X86_CR0_TS) |
1607                         (vcpu->arch.cr0 & X86_CR0_TS);
1608                 vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
1609         } else
1610                 vmcs_writel(CR0_READ_SHADOW, vcpu->arch.cr0);
1611 }
1612
1613 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1614 {
1615         unsigned long rflags, save_rflags;
1616
1617         if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
1618                 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1619                 rflags = vmcs_readl(GUEST_RFLAGS);
1620                 if (to_vmx(vcpu)->rmode.vm86_active) {
1621                         rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1622                         save_rflags = to_vmx(vcpu)->rmode.save_rflags;
1623                         rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1624                 }
1625                 to_vmx(vcpu)->rflags = rflags;
1626         }
1627         return to_vmx(vcpu)->rflags;
1628 }
1629
1630 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1631 {
1632         __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1633         __clear_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
1634         to_vmx(vcpu)->rflags = rflags;
1635         if (to_vmx(vcpu)->rmode.vm86_active) {
1636                 to_vmx(vcpu)->rmode.save_rflags = rflags;
1637                 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1638         }
1639         vmcs_writel(GUEST_RFLAGS, rflags);
1640 }
1641
1642 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1643 {
1644         u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1645         int ret = 0;
1646
1647         if (interruptibility & GUEST_INTR_STATE_STI)
1648                 ret |= KVM_X86_SHADOW_INT_STI;
1649         if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1650                 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1651
1652         return ret & mask;
1653 }
1654
1655 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1656 {
1657         u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1658         u32 interruptibility = interruptibility_old;
1659
1660         interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1661
1662         if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1663                 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1664         else if (mask & KVM_X86_SHADOW_INT_STI)
1665                 interruptibility |= GUEST_INTR_STATE_STI;
1666
1667         if ((interruptibility != interruptibility_old))
1668                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1669 }
1670
1671 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
1672 {
1673         unsigned long rip;
1674
1675         rip = kvm_rip_read(vcpu);
1676         rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1677         kvm_rip_write(vcpu, rip);
1678
1679         /* skipping an emulated instruction also counts */
1680         vmx_set_interrupt_shadow(vcpu, 0);
1681 }
1682
1683 /*
1684  * KVM wants to inject page-faults which it got to the guest. This function
1685  * checks whether in a nested guest, we need to inject them to L1 or L2.
1686  * This function assumes it is called with the exit reason in vmcs02 being
1687  * a #PF exception (this is the only case in which KVM injects a #PF when L2
1688  * is running).
1689  */
1690 static int nested_pf_handled(struct kvm_vcpu *vcpu)
1691 {
1692         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1693
1694         /* TODO: also check PFEC_MATCH/MASK, not just EB.PF. */
1695         if (!(vmcs12->exception_bitmap & (1u << PF_VECTOR)))
1696                 return 0;
1697
1698         nested_vmx_vmexit(vcpu);
1699         return 1;
1700 }
1701
1702 static void vmx_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
1703                                 bool has_error_code, u32 error_code,
1704                                 bool reinject)
1705 {
1706         struct vcpu_vmx *vmx = to_vmx(vcpu);
1707         u32 intr_info = nr | INTR_INFO_VALID_MASK;
1708
1709         if (nr == PF_VECTOR && is_guest_mode(vcpu) &&
1710                 nested_pf_handled(vcpu))
1711                 return;
1712
1713         if (has_error_code) {
1714                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1715                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1716         }
1717
1718         if (vmx->rmode.vm86_active) {
1719                 int inc_eip = 0;
1720                 if (kvm_exception_is_soft(nr))
1721                         inc_eip = vcpu->arch.event_exit_inst_len;
1722                 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
1723                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
1724                 return;
1725         }
1726
1727         if (kvm_exception_is_soft(nr)) {
1728                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1729                              vmx->vcpu.arch.event_exit_inst_len);
1730                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1731         } else
1732                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1733
1734         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1735 }
1736
1737 static bool vmx_rdtscp_supported(void)
1738 {
1739         return cpu_has_vmx_rdtscp();
1740 }
1741
1742 /*
1743  * Swap MSR entry in host/guest MSR entry array.
1744  */
1745 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
1746 {
1747         struct shared_msr_entry tmp;
1748
1749         tmp = vmx->guest_msrs[to];
1750         vmx->guest_msrs[to] = vmx->guest_msrs[from];
1751         vmx->guest_msrs[from] = tmp;
1752 }
1753
1754 /*
1755  * Set up the vmcs to automatically save and restore system
1756  * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
1757  * mode, as fiddling with msrs is very expensive.
1758  */
1759 static void setup_msrs(struct vcpu_vmx *vmx)
1760 {
1761         int save_nmsrs, index;
1762         unsigned long *msr_bitmap;
1763
1764         save_nmsrs = 0;
1765 #ifdef CONFIG_X86_64
1766         if (is_long_mode(&vmx->vcpu)) {
1767                 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
1768                 if (index >= 0)
1769                         move_msr_up(vmx, index, save_nmsrs++);
1770                 index = __find_msr_index(vmx, MSR_LSTAR);
1771                 if (index >= 0)
1772                         move_msr_up(vmx, index, save_nmsrs++);
1773                 index = __find_msr_index(vmx, MSR_CSTAR);
1774                 if (index >= 0)
1775                         move_msr_up(vmx, index, save_nmsrs++);
1776                 index = __find_msr_index(vmx, MSR_TSC_AUX);
1777                 if (index >= 0 && vmx->rdtscp_enabled)
1778                         move_msr_up(vmx, index, save_nmsrs++);
1779                 /*
1780                  * MSR_STAR is only needed on long mode guests, and only
1781                  * if efer.sce is enabled.
1782                  */
1783                 index = __find_msr_index(vmx, MSR_STAR);
1784                 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
1785                         move_msr_up(vmx, index, save_nmsrs++);
1786         }
1787 #endif
1788         index = __find_msr_index(vmx, MSR_EFER);
1789         if (index >= 0 && update_transition_efer(vmx, index))
1790                 move_msr_up(vmx, index, save_nmsrs++);
1791
1792         vmx->save_nmsrs = save_nmsrs;
1793
1794         if (cpu_has_vmx_msr_bitmap()) {
1795                 if (is_long_mode(&vmx->vcpu))
1796                         msr_bitmap = vmx_msr_bitmap_longmode;
1797                 else
1798                         msr_bitmap = vmx_msr_bitmap_legacy;
1799
1800                 vmcs_write64(MSR_BITMAP, __pa(msr_bitmap));
1801         }
1802 }
1803
1804 /*
1805  * reads and returns guest's timestamp counter "register"
1806  * guest_tsc = host_tsc + tsc_offset    -- 21.3
1807  */
1808 static u64 guest_read_tsc(void)
1809 {
1810         u64 host_tsc, tsc_offset;
1811
1812         rdtscll(host_tsc);
1813         tsc_offset = vmcs_read64(TSC_OFFSET);
1814         return host_tsc + tsc_offset;
1815 }
1816
1817 /*
1818  * Like guest_read_tsc, but always returns L1's notion of the timestamp
1819  * counter, even if a nested guest (L2) is currently running.
1820  */
1821 u64 vmx_read_l1_tsc(struct kvm_vcpu *vcpu)
1822 {
1823         u64 host_tsc, tsc_offset;
1824
1825         rdtscll(host_tsc);
1826         tsc_offset = is_guest_mode(vcpu) ?
1827                 to_vmx(vcpu)->nested.vmcs01_tsc_offset :
1828                 vmcs_read64(TSC_OFFSET);
1829         return host_tsc + tsc_offset;
1830 }
1831
1832 /*
1833  * Engage any workarounds for mis-matched TSC rates.  Currently limited to
1834  * software catchup for faster rates on slower CPUs.
1835  */
1836 static void vmx_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
1837 {
1838         if (!scale)
1839                 return;
1840
1841         if (user_tsc_khz > tsc_khz) {
1842                 vcpu->arch.tsc_catchup = 1;
1843                 vcpu->arch.tsc_always_catchup = 1;
1844         } else
1845                 WARN(1, "user requested TSC rate below hardware speed\n");
1846 }
1847
1848 /*
1849  * writes 'offset' into guest's timestamp counter offset register
1850  */
1851 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1852 {
1853         if (is_guest_mode(vcpu)) {
1854                 /*
1855                  * We're here if L1 chose not to trap WRMSR to TSC. According
1856                  * to the spec, this should set L1's TSC; The offset that L1
1857                  * set for L2 remains unchanged, and still needs to be added
1858                  * to the newly set TSC to get L2's TSC.
1859                  */
1860                 struct vmcs12 *vmcs12;
1861                 to_vmx(vcpu)->nested.vmcs01_tsc_offset = offset;
1862                 /* recalculate vmcs02.TSC_OFFSET: */
1863                 vmcs12 = get_vmcs12(vcpu);
1864                 vmcs_write64(TSC_OFFSET, offset +
1865                         (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
1866                          vmcs12->tsc_offset : 0));
1867         } else {
1868                 vmcs_write64(TSC_OFFSET, offset);
1869         }
1870 }
1871
1872 static void vmx_adjust_tsc_offset(struct kvm_vcpu *vcpu, s64 adjustment, bool host)
1873 {
1874         u64 offset = vmcs_read64(TSC_OFFSET);
1875         vmcs_write64(TSC_OFFSET, offset + adjustment);
1876         if (is_guest_mode(vcpu)) {
1877                 /* Even when running L2, the adjustment needs to apply to L1 */
1878                 to_vmx(vcpu)->nested.vmcs01_tsc_offset += adjustment;
1879         }
1880 }
1881
1882 static u64 vmx_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1883 {
1884         return target_tsc - native_read_tsc();
1885 }
1886
1887 static bool guest_cpuid_has_vmx(struct kvm_vcpu *vcpu)
1888 {
1889         struct kvm_cpuid_entry2 *best = kvm_find_cpuid_entry(vcpu, 1, 0);
1890         return best && (best->ecx & (1 << (X86_FEATURE_VMX & 31)));
1891 }
1892
1893 /*
1894  * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1895  * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1896  * all guests if the "nested" module option is off, and can also be disabled
1897  * for a single guest by disabling its VMX cpuid bit.
1898  */
1899 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1900 {
1901         return nested && guest_cpuid_has_vmx(vcpu);
1902 }
1903
1904 /*
1905  * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
1906  * returned for the various VMX controls MSRs when nested VMX is enabled.
1907  * The same values should also be used to verify that vmcs12 control fields are
1908  * valid during nested entry from L1 to L2.
1909  * Each of these control msrs has a low and high 32-bit half: A low bit is on
1910  * if the corresponding bit in the (32-bit) control field *must* be on, and a
1911  * bit in the high half is on if the corresponding bit in the control field
1912  * may be on. See also vmx_control_verify().
1913  * TODO: allow these variables to be modified (downgraded) by module options
1914  * or other means.
1915  */
1916 static u32 nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high;
1917 static u32 nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high;
1918 static u32 nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high;
1919 static u32 nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high;
1920 static u32 nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high;
1921 static __init void nested_vmx_setup_ctls_msrs(void)
1922 {
1923         /*
1924          * Note that as a general rule, the high half of the MSRs (bits in
1925          * the control fields which may be 1) should be initialized by the
1926          * intersection of the underlying hardware's MSR (i.e., features which
1927          * can be supported) and the list of features we want to expose -
1928          * because they are known to be properly supported in our code.
1929          * Also, usually, the low half of the MSRs (bits which must be 1) can
1930          * be set to 0, meaning that L1 may turn off any of these bits. The
1931          * reason is that if one of these bits is necessary, it will appear
1932          * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
1933          * fields of vmcs01 and vmcs02, will turn these bits off - and
1934          * nested_vmx_exit_handled() will not pass related exits to L1.
1935          * These rules have exceptions below.
1936          */
1937
1938         /* pin-based controls */
1939         /*
1940          * According to the Intel spec, if bit 55 of VMX_BASIC is off (as it is
1941          * in our case), bits 1, 2 and 4 (i.e., 0x16) must be 1 in this MSR.
1942          */
1943         nested_vmx_pinbased_ctls_low = 0x16 ;
1944         nested_vmx_pinbased_ctls_high = 0x16 |
1945                 PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING |
1946                 PIN_BASED_VIRTUAL_NMIS;
1947
1948         /* exit controls */
1949         nested_vmx_exit_ctls_low = 0;
1950         /* Note that guest use of VM_EXIT_ACK_INTR_ON_EXIT is not supported. */
1951 #ifdef CONFIG_X86_64
1952         nested_vmx_exit_ctls_high = VM_EXIT_HOST_ADDR_SPACE_SIZE;
1953 #else
1954         nested_vmx_exit_ctls_high = 0;
1955 #endif
1956
1957         /* entry controls */
1958         rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
1959                 nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high);
1960         nested_vmx_entry_ctls_low = 0;
1961         nested_vmx_entry_ctls_high &=
1962                 VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_IA32E_MODE;
1963
1964         /* cpu-based controls */
1965         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
1966                 nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high);
1967         nested_vmx_procbased_ctls_low = 0;
1968         nested_vmx_procbased_ctls_high &=
1969                 CPU_BASED_VIRTUAL_INTR_PENDING | CPU_BASED_USE_TSC_OFFSETING |
1970                 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
1971                 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
1972                 CPU_BASED_CR3_STORE_EXITING |
1973 #ifdef CONFIG_X86_64
1974                 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
1975 #endif
1976                 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
1977                 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_EXITING |
1978                 CPU_BASED_RDPMC_EXITING |
1979                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1980         /*
1981          * We can allow some features even when not supported by the
1982          * hardware. For example, L1 can specify an MSR bitmap - and we
1983          * can use it to avoid exits to L1 - even when L0 runs L2
1984          * without MSR bitmaps.
1985          */
1986         nested_vmx_procbased_ctls_high |= CPU_BASED_USE_MSR_BITMAPS;
1987
1988         /* secondary cpu-based controls */
1989         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
1990                 nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high);
1991         nested_vmx_secondary_ctls_low = 0;
1992         nested_vmx_secondary_ctls_high &=
1993                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1994 }
1995
1996 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
1997 {
1998         /*
1999          * Bits 0 in high must be 0, and bits 1 in low must be 1.
2000          */
2001         return ((control & high) | low) == control;
2002 }
2003
2004 static inline u64 vmx_control_msr(u32 low, u32 high)
2005 {
2006         return low | ((u64)high << 32);
2007 }
2008
2009 /*
2010  * If we allow our guest to use VMX instructions (i.e., nested VMX), we should
2011  * also let it use VMX-specific MSRs.
2012  * vmx_get_vmx_msr() and vmx_set_vmx_msr() return 1 when we handled a
2013  * VMX-specific MSR, or 0 when we haven't (and the caller should handle it
2014  * like all other MSRs).
2015  */
2016 static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
2017 {
2018         if (!nested_vmx_allowed(vcpu) && msr_index >= MSR_IA32_VMX_BASIC &&
2019                      msr_index <= MSR_IA32_VMX_TRUE_ENTRY_CTLS) {
2020                 /*
2021                  * According to the spec, processors which do not support VMX
2022                  * should throw a #GP(0) when VMX capability MSRs are read.
2023                  */
2024                 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
2025                 return 1;
2026         }
2027
2028         switch (msr_index) {
2029         case MSR_IA32_FEATURE_CONTROL:
2030                 *pdata = 0;
2031                 break;
2032         case MSR_IA32_VMX_BASIC:
2033                 /*
2034                  * This MSR reports some information about VMX support. We
2035                  * should return information about the VMX we emulate for the
2036                  * guest, and the VMCS structure we give it - not about the
2037                  * VMX support of the underlying hardware.
2038                  */
2039                 *pdata = VMCS12_REVISION |
2040                            ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
2041                            (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
2042                 break;
2043         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2044         case MSR_IA32_VMX_PINBASED_CTLS:
2045                 *pdata = vmx_control_msr(nested_vmx_pinbased_ctls_low,
2046                                         nested_vmx_pinbased_ctls_high);
2047                 break;
2048         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
2049         case MSR_IA32_VMX_PROCBASED_CTLS:
2050                 *pdata = vmx_control_msr(nested_vmx_procbased_ctls_low,
2051                                         nested_vmx_procbased_ctls_high);
2052                 break;
2053         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
2054         case MSR_IA32_VMX_EXIT_CTLS:
2055                 *pdata = vmx_control_msr(nested_vmx_exit_ctls_low,
2056                                         nested_vmx_exit_ctls_high);
2057                 break;
2058         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
2059         case MSR_IA32_VMX_ENTRY_CTLS:
2060                 *pdata = vmx_control_msr(nested_vmx_entry_ctls_low,
2061                                         nested_vmx_entry_ctls_high);
2062                 break;
2063         case MSR_IA32_VMX_MISC:
2064                 *pdata = 0;
2065                 break;
2066         /*
2067          * These MSRs specify bits which the guest must keep fixed (on or off)
2068          * while L1 is in VMXON mode (in L1's root mode, or running an L2).
2069          * We picked the standard core2 setting.
2070          */
2071 #define VMXON_CR0_ALWAYSON      (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
2072 #define VMXON_CR4_ALWAYSON      X86_CR4_VMXE
2073         case MSR_IA32_VMX_CR0_FIXED0:
2074                 *pdata = VMXON_CR0_ALWAYSON;
2075                 break;
2076         case MSR_IA32_VMX_CR0_FIXED1:
2077                 *pdata = -1ULL;
2078                 break;
2079         case MSR_IA32_VMX_CR4_FIXED0:
2080                 *pdata = VMXON_CR4_ALWAYSON;
2081                 break;
2082         case MSR_IA32_VMX_CR4_FIXED1:
2083                 *pdata = -1ULL;
2084                 break;
2085         case MSR_IA32_VMX_VMCS_ENUM:
2086                 *pdata = 0x1f;
2087                 break;
2088         case MSR_IA32_VMX_PROCBASED_CTLS2:
2089                 *pdata = vmx_control_msr(nested_vmx_secondary_ctls_low,
2090                                         nested_vmx_secondary_ctls_high);
2091                 break;
2092         case MSR_IA32_VMX_EPT_VPID_CAP:
2093                 /* Currently, no nested ept or nested vpid */
2094                 *pdata = 0;
2095                 break;
2096         default:
2097                 return 0;
2098         }
2099
2100         return 1;
2101 }
2102
2103 static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
2104 {
2105         if (!nested_vmx_allowed(vcpu))
2106                 return 0;
2107
2108         if (msr_index == MSR_IA32_FEATURE_CONTROL)
2109                 /* TODO: the right thing. */
2110                 return 1;
2111         /*
2112          * No need to treat VMX capability MSRs specially: If we don't handle
2113          * them, handle_wrmsr will #GP(0), which is correct (they are readonly)
2114          */
2115         return 0;
2116 }
2117
2118 /*
2119  * Reads an msr value (of 'msr_index') into 'pdata'.
2120  * Returns 0 on success, non-0 otherwise.
2121  * Assumes vcpu_load() was already called.
2122  */
2123 static int vmx_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
2124 {
2125         u64 data;
2126         struct shared_msr_entry *msr;
2127
2128         if (!pdata) {
2129                 printk(KERN_ERR "BUG: get_msr called with NULL pdata\n");
2130                 return -EINVAL;
2131         }
2132
2133         switch (msr_index) {
2134 #ifdef CONFIG_X86_64
2135         case MSR_FS_BASE:
2136                 data = vmcs_readl(GUEST_FS_BASE);
2137                 break;
2138         case MSR_GS_BASE:
2139                 data = vmcs_readl(GUEST_GS_BASE);
2140                 break;
2141         case MSR_KERNEL_GS_BASE:
2142                 vmx_load_host_state(to_vmx(vcpu));
2143                 data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
2144                 break;
2145 #endif
2146         case MSR_EFER:
2147                 return kvm_get_msr_common(vcpu, msr_index, pdata);
2148         case MSR_IA32_TSC:
2149                 data = guest_read_tsc();
2150                 break;
2151         case MSR_IA32_SYSENTER_CS:
2152                 data = vmcs_read32(GUEST_SYSENTER_CS);
2153                 break;
2154         case MSR_IA32_SYSENTER_EIP:
2155                 data = vmcs_readl(GUEST_SYSENTER_EIP);
2156                 break;
2157         case MSR_IA32_SYSENTER_ESP:
2158                 data = vmcs_readl(GUEST_SYSENTER_ESP);
2159                 break;
2160         case MSR_TSC_AUX:
2161                 if (!to_vmx(vcpu)->rdtscp_enabled)
2162                         return 1;
2163                 /* Otherwise falls through */
2164         default:
2165                 if (vmx_get_vmx_msr(vcpu, msr_index, pdata))
2166                         return 0;
2167                 msr = find_msr_entry(to_vmx(vcpu), msr_index);
2168                 if (msr) {
2169                         data = msr->data;
2170                         break;
2171                 }
2172                 return kvm_get_msr_common(vcpu, msr_index, pdata);
2173         }
2174
2175         *pdata = data;
2176         return 0;
2177 }
2178
2179 /*
2180  * Writes msr value into into the appropriate "register".
2181  * Returns 0 on success, non-0 otherwise.
2182  * Assumes vcpu_load() was already called.
2183  */
2184 static int vmx_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
2185 {
2186         struct vcpu_vmx *vmx = to_vmx(vcpu);
2187         struct shared_msr_entry *msr;
2188         int ret = 0;
2189
2190         switch (msr_index) {
2191         case MSR_EFER:
2192                 ret = kvm_set_msr_common(vcpu, msr_index, data);
2193                 break;
2194 #ifdef CONFIG_X86_64
2195         case MSR_FS_BASE:
2196                 vmx_segment_cache_clear(vmx);
2197                 vmcs_writel(GUEST_FS_BASE, data);
2198                 break;
2199         case MSR_GS_BASE:
2200                 vmx_segment_cache_clear(vmx);
2201                 vmcs_writel(GUEST_GS_BASE, data);
2202                 break;
2203         case MSR_KERNEL_GS_BASE:
2204                 vmx_load_host_state(vmx);
2205                 vmx->msr_guest_kernel_gs_base = data;
2206                 break;
2207 #endif
2208         case MSR_IA32_SYSENTER_CS:
2209                 vmcs_write32(GUEST_SYSENTER_CS, data);
2210                 break;
2211         case MSR_IA32_SYSENTER_EIP:
2212                 vmcs_writel(GUEST_SYSENTER_EIP, data);
2213                 break;
2214         case MSR_IA32_SYSENTER_ESP:
2215                 vmcs_writel(GUEST_SYSENTER_ESP, data);
2216                 break;
2217         case MSR_IA32_TSC:
2218                 kvm_write_tsc(vcpu, data);
2219                 break;
2220         case MSR_IA32_CR_PAT:
2221                 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2222                         vmcs_write64(GUEST_IA32_PAT, data);
2223                         vcpu->arch.pat = data;
2224                         break;
2225                 }
2226                 ret = kvm_set_msr_common(vcpu, msr_index, data);
2227                 break;
2228         case MSR_TSC_AUX:
2229                 if (!vmx->rdtscp_enabled)
2230                         return 1;
2231                 /* Check reserved bit, higher 32 bits should be zero */
2232                 if ((data >> 32) != 0)
2233                         return 1;
2234                 /* Otherwise falls through */
2235         default:
2236                 if (vmx_set_vmx_msr(vcpu, msr_index, data))
2237                         break;
2238                 msr = find_msr_entry(vmx, msr_index);
2239                 if (msr) {
2240                         msr->data = data;
2241                         if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
2242                                 preempt_disable();
2243                                 kvm_set_shared_msr(msr->index, msr->data,
2244                                                    msr->mask);
2245                                 preempt_enable();
2246                         }
2247                         break;
2248                 }
2249                 ret = kvm_set_msr_common(vcpu, msr_index, data);
2250         }
2251
2252         return ret;
2253 }
2254
2255 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2256 {
2257         __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
2258         switch (reg) {
2259         case VCPU_REGS_RSP:
2260                 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2261                 break;
2262         case VCPU_REGS_RIP:
2263                 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2264                 break;
2265         case VCPU_EXREG_PDPTR:
2266                 if (enable_ept)
2267                         ept_save_pdptrs(vcpu);
2268                 break;
2269         default:
2270                 break;
2271         }
2272 }
2273
2274 static void set_guest_debug(struct kvm_vcpu *vcpu, struct kvm_guest_debug *dbg)
2275 {
2276         if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
2277                 vmcs_writel(GUEST_DR7, dbg->arch.debugreg[7]);
2278         else
2279                 vmcs_writel(GUEST_DR7, vcpu->arch.dr7);
2280
2281         update_exception_bitmap(vcpu);
2282 }
2283
2284 static __init int cpu_has_kvm_support(void)
2285 {
2286         return cpu_has_vmx();
2287 }
2288
2289 static __init int vmx_disabled_by_bios(void)
2290 {
2291         u64 msr;
2292
2293         rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
2294         if (msr & FEATURE_CONTROL_LOCKED) {
2295                 /* launched w/ TXT and VMX disabled */
2296                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2297                         && tboot_enabled())
2298                         return 1;
2299                 /* launched w/o TXT and VMX only enabled w/ TXT */
2300                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2301                         && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2302                         && !tboot_enabled()) {
2303                         printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
2304                                 "activate TXT before enabling KVM\n");
2305                         return 1;
2306                 }
2307                 /* launched w/o TXT and VMX disabled */
2308                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2309                         && !tboot_enabled())
2310                         return 1;
2311         }
2312
2313         return 0;
2314 }
2315
2316 static void kvm_cpu_vmxon(u64 addr)
2317 {
2318         asm volatile (ASM_VMX_VMXON_RAX
2319                         : : "a"(&addr), "m"(addr)
2320                         : "memory", "cc");
2321 }
2322
2323 static int hardware_enable(void *garbage)
2324 {
2325         int cpu = raw_smp_processor_id();
2326         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2327         u64 old, test_bits;
2328
2329         if (read_cr4() & X86_CR4_VMXE)
2330                 return -EBUSY;
2331
2332         INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
2333         rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
2334
2335         test_bits = FEATURE_CONTROL_LOCKED;
2336         test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
2337         if (tboot_enabled())
2338                 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
2339
2340         if ((old & test_bits) != test_bits) {
2341                 /* enable and lock */
2342                 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
2343         }
2344         write_cr4(read_cr4() | X86_CR4_VMXE); /* FIXME: not cpu hotplug safe */
2345
2346         if (vmm_exclusive) {
2347                 kvm_cpu_vmxon(phys_addr);
2348                 ept_sync_global();
2349         }
2350
2351         store_gdt(&__get_cpu_var(host_gdt));
2352
2353         return 0;
2354 }
2355
2356 static void vmclear_local_loaded_vmcss(void)
2357 {
2358         int cpu = raw_smp_processor_id();
2359         struct loaded_vmcs *v, *n;
2360
2361         list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2362                                  loaded_vmcss_on_cpu_link)
2363                 __loaded_vmcs_clear(v);
2364 }
2365
2366
2367 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
2368  * tricks.
2369  */
2370 static void kvm_cpu_vmxoff(void)
2371 {
2372         asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
2373 }
2374
2375 static void hardware_disable(void *garbage)
2376 {
2377         if (vmm_exclusive) {
2378                 vmclear_local_loaded_vmcss();
2379                 kvm_cpu_vmxoff();
2380         }
2381         write_cr4(read_cr4() & ~X86_CR4_VMXE);
2382 }
2383
2384 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2385                                       u32 msr, u32 *result)
2386 {
2387         u32 vmx_msr_low, vmx_msr_high;
2388         u32 ctl = ctl_min | ctl_opt;
2389
2390         rdmsr(msr, vmx_msr_low, vmx_msr_high);
2391
2392         ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2393         ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
2394
2395         /* Ensure minimum (required) set of control bits are supported. */
2396         if (ctl_min & ~ctl)
2397                 return -EIO;
2398
2399         *result = ctl;
2400         return 0;
2401 }
2402
2403 static __init bool allow_1_setting(u32 msr, u32 ctl)
2404 {
2405         u32 vmx_msr_low, vmx_msr_high;
2406
2407         rdmsr(msr, vmx_msr_low, vmx_msr_high);
2408         return vmx_msr_high & ctl;
2409 }
2410
2411 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
2412 {
2413         u32 vmx_msr_low, vmx_msr_high;
2414         u32 min, opt, min2, opt2;
2415         u32 _pin_based_exec_control = 0;
2416         u32 _cpu_based_exec_control = 0;
2417         u32 _cpu_based_2nd_exec_control = 0;
2418         u32 _vmexit_control = 0;
2419         u32 _vmentry_control = 0;
2420
2421         min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2422         opt = PIN_BASED_VIRTUAL_NMIS;
2423         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2424                                 &_pin_based_exec_control) < 0)
2425                 return -EIO;
2426
2427         min = CPU_BASED_HLT_EXITING |
2428 #ifdef CONFIG_X86_64
2429               CPU_BASED_CR8_LOAD_EXITING |
2430               CPU_BASED_CR8_STORE_EXITING |
2431 #endif
2432               CPU_BASED_CR3_LOAD_EXITING |
2433               CPU_BASED_CR3_STORE_EXITING |
2434               CPU_BASED_USE_IO_BITMAPS |
2435               CPU_BASED_MOV_DR_EXITING |
2436               CPU_BASED_USE_TSC_OFFSETING |
2437               CPU_BASED_MWAIT_EXITING |
2438               CPU_BASED_MONITOR_EXITING |
2439               CPU_BASED_INVLPG_EXITING |
2440               CPU_BASED_RDPMC_EXITING;
2441
2442         opt = CPU_BASED_TPR_SHADOW |
2443               CPU_BASED_USE_MSR_BITMAPS |
2444               CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2445         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2446                                 &_cpu_based_exec_control) < 0)
2447                 return -EIO;
2448 #ifdef CONFIG_X86_64
2449         if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2450                 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2451                                            ~CPU_BASED_CR8_STORE_EXITING;
2452 #endif
2453         if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2454                 min2 = 0;
2455                 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2456                         SECONDARY_EXEC_WBINVD_EXITING |
2457                         SECONDARY_EXEC_ENABLE_VPID |
2458                         SECONDARY_EXEC_ENABLE_EPT |
2459                         SECONDARY_EXEC_UNRESTRICTED_GUEST |
2460                         SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2461                         SECONDARY_EXEC_RDTSCP;
2462                 if (adjust_vmx_controls(min2, opt2,
2463                                         MSR_IA32_VMX_PROCBASED_CTLS2,
2464                                         &_cpu_based_2nd_exec_control) < 0)
2465                         return -EIO;
2466         }
2467 #ifndef CONFIG_X86_64
2468         if (!(_cpu_based_2nd_exec_control &
2469                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2470                 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2471 #endif
2472         if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2473                 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2474                    enabled */
2475                 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2476                                              CPU_BASED_CR3_STORE_EXITING |
2477                                              CPU_BASED_INVLPG_EXITING);
2478                 rdmsr(MSR_IA32_VMX_EPT_VPID_CAP,
2479                       vmx_capability.ept, vmx_capability.vpid);
2480         }
2481
2482         min = 0;
2483 #ifdef CONFIG_X86_64
2484         min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2485 #endif
2486         opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT;
2487         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2488                                 &_vmexit_control) < 0)
2489                 return -EIO;
2490
2491         min = 0;
2492         opt = VM_ENTRY_LOAD_IA32_PAT;
2493         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2494                                 &_vmentry_control) < 0)
2495                 return -EIO;
2496
2497         rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2498
2499         /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2500         if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2501                 return -EIO;
2502
2503 #ifdef CONFIG_X86_64
2504         /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2505         if (vmx_msr_high & (1u<<16))
2506                 return -EIO;
2507 #endif
2508
2509         /* Require Write-Back (WB) memory type for VMCS accesses. */
2510         if (((vmx_msr_high >> 18) & 15) != 6)
2511                 return -EIO;
2512
2513         vmcs_conf->size = vmx_msr_high & 0x1fff;
2514         vmcs_conf->order = get_order(vmcs_config.size);
2515         vmcs_conf->revision_id = vmx_msr_low;
2516
2517         vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2518         vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2519         vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2520         vmcs_conf->vmexit_ctrl         = _vmexit_control;
2521         vmcs_conf->vmentry_ctrl        = _vmentry_control;
2522
2523         cpu_has_load_ia32_efer =
2524                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
2525                                 VM_ENTRY_LOAD_IA32_EFER)
2526                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
2527                                    VM_EXIT_LOAD_IA32_EFER);
2528
2529         cpu_has_load_perf_global_ctrl =
2530                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
2531                                 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
2532                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
2533                                    VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
2534
2535         /*
2536          * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
2537          * but due to arrata below it can't be used. Workaround is to use
2538          * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2539          *
2540          * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
2541          *
2542          * AAK155             (model 26)
2543          * AAP115             (model 30)
2544          * AAT100             (model 37)
2545          * BC86,AAY89,BD102   (model 44)
2546          * BA97               (model 46)
2547          *
2548          */
2549         if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
2550                 switch (boot_cpu_data.x86_model) {
2551                 case 26:
2552                 case 30:
2553                 case 37:
2554                 case 44:
2555                 case 46:
2556                         cpu_has_load_perf_global_ctrl = false;
2557                         printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2558                                         "does not work properly. Using workaround\n");
2559                         break;
2560                 default:
2561                         break;
2562                 }
2563         }
2564
2565         return 0;
2566 }
2567
2568 static struct vmcs *alloc_vmcs_cpu(int cpu)
2569 {
2570         int node = cpu_to_node(cpu);
2571         struct page *pages;
2572         struct vmcs *vmcs;
2573
2574         pages = alloc_pages_exact_node(node, GFP_KERNEL, vmcs_config.order);
2575         if (!pages)
2576                 return NULL;
2577         vmcs = page_address(pages);
2578         memset(vmcs, 0, vmcs_config.size);
2579         vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
2580         return vmcs;
2581 }
2582
2583 static struct vmcs *alloc_vmcs(void)
2584 {
2585         return alloc_vmcs_cpu(raw_smp_processor_id());
2586 }
2587
2588 static void free_vmcs(struct vmcs *vmcs)
2589 {
2590         free_pages((unsigned long)vmcs, vmcs_config.order);
2591 }
2592
2593 /*
2594  * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2595  */
2596 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2597 {
2598         if (!loaded_vmcs->vmcs)
2599                 return;
2600         loaded_vmcs_clear(loaded_vmcs);
2601         free_vmcs(loaded_vmcs->vmcs);
2602         loaded_vmcs->vmcs = NULL;
2603 }
2604
2605 static void free_kvm_area(void)
2606 {
2607         int cpu;
2608
2609         for_each_possible_cpu(cpu) {
2610                 free_vmcs(per_cpu(vmxarea, cpu));
2611                 per_cpu(vmxarea, cpu) = NULL;
2612         }
2613 }
2614
2615 static __init int alloc_kvm_area(void)
2616 {
2617         int cpu;
2618
2619         for_each_possible_cpu(cpu) {
2620                 struct vmcs *vmcs;
2621
2622                 vmcs = alloc_vmcs_cpu(cpu);
2623                 if (!vmcs) {
2624                         free_kvm_area();
2625                         return -ENOMEM;
2626                 }
2627
2628                 per_cpu(vmxarea, cpu) = vmcs;
2629         }
2630         return 0;
2631 }
2632
2633 static __init int hardware_setup(void)
2634 {
2635         if (setup_vmcs_config(&vmcs_config) < 0)
2636                 return -EIO;
2637
2638         if (boot_cpu_has(X86_FEATURE_NX))
2639                 kvm_enable_efer_bits(EFER_NX);
2640
2641         if (!cpu_has_vmx_vpid())
2642                 enable_vpid = 0;
2643
2644         if (!cpu_has_vmx_ept() ||
2645             !cpu_has_vmx_ept_4levels()) {
2646                 enable_ept = 0;
2647                 enable_unrestricted_guest = 0;
2648         }
2649
2650         if (!cpu_has_vmx_unrestricted_guest())
2651                 enable_unrestricted_guest = 0;
2652
2653         if (!cpu_has_vmx_flexpriority())
2654                 flexpriority_enabled = 0;
2655
2656         if (!cpu_has_vmx_tpr_shadow())
2657                 kvm_x86_ops->update_cr8_intercept = NULL;
2658
2659         if (enable_ept && !cpu_has_vmx_ept_2m_page())
2660                 kvm_disable_largepages();
2661
2662         if (!cpu_has_vmx_ple())
2663                 ple_gap = 0;
2664
2665         if (nested)
2666                 nested_vmx_setup_ctls_msrs();
2667
2668         return alloc_kvm_area();
2669 }
2670
2671 static __exit void hardware_unsetup(void)
2672 {
2673         free_kvm_area();
2674 }
2675
2676 static void fix_pmode_dataseg(int seg, struct kvm_save_segment *save)
2677 {
2678         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2679
2680         if (vmcs_readl(sf->base) == save->base && (save->base & AR_S_MASK)) {
2681                 vmcs_write16(sf->selector, save->selector);
2682                 vmcs_writel(sf->base, save->base);
2683                 vmcs_write32(sf->limit, save->limit);
2684                 vmcs_write32(sf->ar_bytes, save->ar);
2685         } else {
2686                 u32 dpl = (vmcs_read16(sf->selector) & SELECTOR_RPL_MASK)
2687                         << AR_DPL_SHIFT;
2688                 vmcs_write32(sf->ar_bytes, 0x93 | dpl);
2689         }
2690 }
2691
2692 static void enter_pmode(struct kvm_vcpu *vcpu)
2693 {
2694         unsigned long flags;
2695         struct vcpu_vmx *vmx = to_vmx(vcpu);
2696
2697         vmx->emulation_required = 1;
2698         vmx->rmode.vm86_active = 0;
2699
2700         vmx_segment_cache_clear(vmx);
2701
2702         vmcs_write16(GUEST_TR_SELECTOR, vmx->rmode.tr.selector);
2703         vmcs_writel(GUEST_TR_BASE, vmx->rmode.tr.base);
2704         vmcs_write32(GUEST_TR_LIMIT, vmx->rmode.tr.limit);
2705         vmcs_write32(GUEST_TR_AR_BYTES, vmx->rmode.tr.ar);
2706
2707         flags = vmcs_readl(GUEST_RFLAGS);
2708         flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2709         flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2710         vmcs_writel(GUEST_RFLAGS, flags);
2711
2712         vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2713                         (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2714
2715         update_exception_bitmap(vcpu);
2716
2717         if (emulate_invalid_guest_state)
2718                 return;
2719
2720         fix_pmode_dataseg(VCPU_SREG_ES, &vmx->rmode.es);
2721         fix_pmode_dataseg(VCPU_SREG_DS, &vmx->rmode.ds);
2722         fix_pmode_dataseg(VCPU_SREG_GS, &vmx->rmode.gs);
2723         fix_pmode_dataseg(VCPU_SREG_FS, &vmx->rmode.fs);
2724
2725         vmx_segment_cache_clear(vmx);
2726
2727         vmcs_write16(GUEST_SS_SELECTOR, 0);
2728         vmcs_write32(GUEST_SS_AR_BYTES, 0x93);
2729
2730         vmcs_write16(GUEST_CS_SELECTOR,
2731                      vmcs_read16(GUEST_CS_SELECTOR) & ~SELECTOR_RPL_MASK);
2732         vmcs_write32(GUEST_CS_AR_BYTES, 0x9b);
2733 }
2734
2735 static gva_t rmode_tss_base(struct kvm *kvm)
2736 {
2737         if (!kvm->arch.tss_addr) {
2738                 struct kvm_memslots *slots;
2739                 struct kvm_memory_slot *slot;
2740                 gfn_t base_gfn;
2741
2742                 slots = kvm_memslots(kvm);
2743                 slot = id_to_memslot(slots, 0);
2744                 base_gfn = slot->base_gfn + slot->npages - 3;
2745
2746                 return base_gfn << PAGE_SHIFT;
2747         }
2748         return kvm->arch.tss_addr;
2749 }
2750
2751 static void fix_rmode_seg(int seg, struct kvm_save_segment *save)
2752 {
2753         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2754
2755         save->selector = vmcs_read16(sf->selector);
2756         save->base = vmcs_readl(sf->base);
2757         save->limit = vmcs_read32(sf->limit);
2758         save->ar = vmcs_read32(sf->ar_bytes);
2759         vmcs_write16(sf->selector, save->base >> 4);
2760         vmcs_write32(sf->base, save->base & 0xffff0);
2761         vmcs_write32(sf->limit, 0xffff);
2762         vmcs_write32(sf->ar_bytes, 0xf3);
2763         if (save->base & 0xf)
2764                 printk_once(KERN_WARNING "kvm: segment base is not paragraph"
2765                             " aligned when entering protected mode (seg=%d)",
2766                             seg);
2767 }
2768
2769 static void enter_rmode(struct kvm_vcpu *vcpu)
2770 {
2771         unsigned long flags;
2772         struct vcpu_vmx *vmx = to_vmx(vcpu);
2773
2774         if (enable_unrestricted_guest)
2775                 return;
2776
2777         vmx->emulation_required = 1;
2778         vmx->rmode.vm86_active = 1;
2779
2780         /*
2781          * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2782          * vcpu. Call it here with phys address pointing 16M below 4G.
2783          */
2784         if (!vcpu->kvm->arch.tss_addr) {
2785                 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2786                              "called before entering vcpu\n");
2787                 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
2788                 vmx_set_tss_addr(vcpu->kvm, 0xfeffd000);
2789                 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
2790         }
2791
2792         vmx_segment_cache_clear(vmx);
2793
2794         vmx->rmode.tr.selector = vmcs_read16(GUEST_TR_SELECTOR);
2795         vmx->rmode.tr.base = vmcs_readl(GUEST_TR_BASE);
2796         vmcs_writel(GUEST_TR_BASE, rmode_tss_base(vcpu->kvm));
2797
2798         vmx->rmode.tr.limit = vmcs_read32(GUEST_TR_LIMIT);
2799         vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2800
2801         vmx->rmode.tr.ar = vmcs_read32(GUEST_TR_AR_BYTES);
2802         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2803
2804         flags = vmcs_readl(GUEST_RFLAGS);
2805         vmx->rmode.save_rflags = flags;
2806
2807         flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2808
2809         vmcs_writel(GUEST_RFLAGS, flags);
2810         vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2811         update_exception_bitmap(vcpu);
2812
2813         if (emulate_invalid_guest_state)
2814                 goto continue_rmode;
2815
2816         vmcs_write16(GUEST_SS_SELECTOR, vmcs_readl(GUEST_SS_BASE) >> 4);
2817         vmcs_write32(GUEST_SS_LIMIT, 0xffff);
2818         vmcs_write32(GUEST_SS_AR_BYTES, 0xf3);
2819
2820         vmcs_write32(GUEST_CS_AR_BYTES, 0xf3);
2821         vmcs_write32(GUEST_CS_LIMIT, 0xffff);
2822         if (vmcs_readl(GUEST_CS_BASE) == 0xffff0000)
2823                 vmcs_writel(GUEST_CS_BASE, 0xf0000);
2824         vmcs_write16(GUEST_CS_SELECTOR, vmcs_readl(GUEST_CS_BASE) >> 4);
2825
2826         fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.es);
2827         fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.ds);
2828         fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.gs);
2829         fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.fs);
2830
2831 continue_rmode:
2832         kvm_mmu_reset_context(vcpu);
2833 }
2834
2835 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2836 {
2837         struct vcpu_vmx *vmx = to_vmx(vcpu);
2838         struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
2839
2840         if (!msr)
2841                 return;
2842
2843         /*
2844          * Force kernel_gs_base reloading before EFER changes, as control
2845          * of this msr depends on is_long_mode().
2846          */
2847         vmx_load_host_state(to_vmx(vcpu));
2848         vcpu->arch.efer = efer;
2849         if (efer & EFER_LMA) {
2850                 vmcs_write32(VM_ENTRY_CONTROLS,
2851                              vmcs_read32(VM_ENTRY_CONTROLS) |
2852                              VM_ENTRY_IA32E_MODE);
2853                 msr->data = efer;
2854         } else {
2855                 vmcs_write32(VM_ENTRY_CONTROLS,
2856                              vmcs_read32(VM_ENTRY_CONTROLS) &
2857                              ~VM_ENTRY_IA32E_MODE);
2858
2859                 msr->data = efer & ~EFER_LME;
2860         }
2861         setup_msrs(vmx);
2862 }
2863
2864 #ifdef CONFIG_X86_64
2865
2866 static void enter_lmode(struct kvm_vcpu *vcpu)
2867 {
2868         u32 guest_tr_ar;
2869
2870         vmx_segment_cache_clear(to_vmx(vcpu));
2871
2872         guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2873         if ((guest_tr_ar & AR_TYPE_MASK) != AR_TYPE_BUSY_64_TSS) {
2874                 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2875                                      __func__);
2876                 vmcs_write32(GUEST_TR_AR_BYTES,
2877                              (guest_tr_ar & ~AR_TYPE_MASK)
2878                              | AR_TYPE_BUSY_64_TSS);
2879         }
2880         vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
2881 }
2882
2883 static void exit_lmode(struct kvm_vcpu *vcpu)
2884 {
2885         vmcs_write32(VM_ENTRY_CONTROLS,
2886                      vmcs_read32(VM_ENTRY_CONTROLS)
2887                      & ~VM_ENTRY_IA32E_MODE);
2888         vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
2889 }
2890
2891 #endif
2892
2893 static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
2894 {
2895         vpid_sync_context(to_vmx(vcpu));
2896         if (enable_ept) {
2897                 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
2898                         return;
2899                 ept_sync_context(construct_eptp(vcpu->arch.mmu.root_hpa));
2900         }
2901 }
2902
2903 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2904 {
2905         ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2906
2907         vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
2908         vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
2909 }
2910
2911 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
2912 {
2913         if (enable_ept && is_paging(vcpu))
2914                 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2915         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
2916 }
2917
2918 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2919 {
2920         ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2921
2922         vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
2923         vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
2924 }
2925
2926 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
2927 {
2928         if (!test_bit(VCPU_EXREG_PDPTR,
2929                       (unsigned long *)&vcpu->arch.regs_dirty))
2930                 return;
2931
2932         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
2933                 vmcs_write64(GUEST_PDPTR0, vcpu->arch.mmu.pdptrs[0]);
2934                 vmcs_write64(GUEST_PDPTR1, vcpu->arch.mmu.pdptrs[1]);
2935                 vmcs_write64(GUEST_PDPTR2, vcpu->arch.mmu.pdptrs[2]);
2936                 vmcs_write64(GUEST_PDPTR3, vcpu->arch.mmu.pdptrs[3]);
2937         }
2938 }
2939
2940 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
2941 {
2942         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
2943                 vcpu->arch.mmu.pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
2944                 vcpu->arch.mmu.pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
2945                 vcpu->arch.mmu.pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
2946                 vcpu->arch.mmu.pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
2947         }
2948
2949         __set_bit(VCPU_EXREG_PDPTR,
2950                   (unsigned long *)&vcpu->arch.regs_avail);
2951         __set_bit(VCPU_EXREG_PDPTR,
2952                   (unsigned long *)&vcpu->arch.regs_dirty);
2953 }
2954
2955 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
2956
2957 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
2958                                         unsigned long cr0,
2959                                         struct kvm_vcpu *vcpu)
2960 {
2961         if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
2962                 vmx_decache_cr3(vcpu);
2963         if (!(cr0 & X86_CR0_PG)) {
2964                 /* From paging/starting to nonpaging */
2965                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
2966                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
2967                              (CPU_BASED_CR3_LOAD_EXITING |
2968                               CPU_BASED_CR3_STORE_EXITING));
2969                 vcpu->arch.cr0 = cr0;
2970                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2971         } else if (!is_paging(vcpu)) {
2972                 /* From nonpaging to paging */
2973                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
2974                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
2975                              ~(CPU_BASED_CR3_LOAD_EXITING |
2976                                CPU_BASED_CR3_STORE_EXITING));
2977                 vcpu->arch.cr0 = cr0;
2978                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2979         }
2980
2981         if (!(cr0 & X86_CR0_WP))
2982                 *hw_cr0 &= ~X86_CR0_WP;
2983 }
2984
2985 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2986 {
2987         struct vcpu_vmx *vmx = to_vmx(vcpu);
2988         unsigned long hw_cr0;
2989
2990         if (enable_unrestricted_guest)
2991                 hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK_UNRESTRICTED_GUEST)
2992                         | KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
2993         else
2994                 hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK) | KVM_VM_CR0_ALWAYS_ON;
2995
2996         if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
2997                 enter_pmode(vcpu);
2998
2999         if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3000                 enter_rmode(vcpu);
3001
3002 #ifdef CONFIG_X86_64
3003         if (vcpu->arch.efer & EFER_LME) {
3004                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
3005                         enter_lmode(vcpu);
3006                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
3007                         exit_lmode(vcpu);
3008         }
3009 #endif
3010
3011         if (enable_ept)
3012                 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
3013
3014         if (!vcpu->fpu_active)
3015                 hw_cr0 |= X86_CR0_TS | X86_CR0_MP;
3016
3017         vmcs_writel(CR0_READ_SHADOW, cr0);
3018         vmcs_writel(GUEST_CR0, hw_cr0);
3019         vcpu->arch.cr0 = cr0;
3020         __clear_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
3021 }
3022
3023 static u64 construct_eptp(unsigned long root_hpa)
3024 {
3025         u64 eptp;
3026
3027         /* TODO write the value reading from MSR */
3028         eptp = VMX_EPT_DEFAULT_MT |
3029                 VMX_EPT_DEFAULT_GAW << VMX_EPT_GAW_EPTP_SHIFT;
3030         eptp |= (root_hpa & PAGE_MASK);
3031
3032         return eptp;
3033 }
3034
3035 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
3036 {
3037         unsigned long guest_cr3;
3038         u64 eptp;
3039
3040         guest_cr3 = cr3;
3041         if (enable_ept) {
3042                 eptp = construct_eptp(cr3);
3043                 vmcs_write64(EPT_POINTER, eptp);
3044                 guest_cr3 = is_paging(vcpu) ? kvm_read_cr3(vcpu) :
3045                         vcpu->kvm->arch.ept_identity_map_addr;
3046                 ept_load_pdptrs(vcpu);
3047         }
3048
3049         vmx_flush_tlb(vcpu);
3050         vmcs_writel(GUEST_CR3, guest_cr3);
3051 }
3052
3053 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3054 {
3055         unsigned long hw_cr4 = cr4 | (to_vmx(vcpu)->rmode.vm86_active ?
3056                     KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
3057
3058         if (cr4 & X86_CR4_VMXE) {
3059                 /*
3060                  * To use VMXON (and later other VMX instructions), a guest
3061                  * must first be able to turn on cr4.VMXE (see handle_vmon()).
3062                  * So basically the check on whether to allow nested VMX
3063                  * is here.
3064                  */
3065                 if (!nested_vmx_allowed(vcpu))
3066                         return 1;
3067         } else if (to_vmx(vcpu)->nested.vmxon)
3068                 return 1;
3069
3070         vcpu->arch.cr4 = cr4;
3071         if (enable_ept) {
3072                 if (!is_paging(vcpu)) {
3073                         hw_cr4 &= ~X86_CR4_PAE;
3074                         hw_cr4 |= X86_CR4_PSE;
3075                 } else if (!(cr4 & X86_CR4_PAE)) {
3076                         hw_cr4 &= ~X86_CR4_PAE;
3077                 }
3078         }
3079
3080         vmcs_writel(CR4_READ_SHADOW, cr4);
3081         vmcs_writel(GUEST_CR4, hw_cr4);
3082         return 0;
3083 }
3084
3085 static void vmx_get_segment(struct kvm_vcpu *vcpu,
3086                             struct kvm_segment *var, int seg)
3087 {
3088         struct vcpu_vmx *vmx = to_vmx(vcpu);
3089         struct kvm_save_segment *save;
3090         u32 ar;
3091
3092         if (vmx->rmode.vm86_active
3093             && (seg == VCPU_SREG_TR || seg == VCPU_SREG_ES
3094                 || seg == VCPU_SREG_DS || seg == VCPU_SREG_FS
3095                 || seg == VCPU_SREG_GS)
3096             && !emulate_invalid_guest_state) {
3097                 switch (seg) {
3098                 case VCPU_SREG_TR: save = &vmx->rmode.tr; break;
3099                 case VCPU_SREG_ES: save = &vmx->rmode.es; break;
3100                 case VCPU_SREG_DS: save = &vmx->rmode.ds; break;
3101                 case VCPU_SREG_FS: save = &vmx->rmode.fs; break;
3102                 case VCPU_SREG_GS: save = &vmx->rmode.gs; break;
3103                 default: BUG();
3104                 }
3105                 var->selector = save->selector;
3106                 var->base = save->base;
3107                 var->limit = save->limit;
3108                 ar = save->ar;
3109                 if (seg == VCPU_SREG_TR
3110                     || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3111                         goto use_saved_rmode_seg;
3112         }
3113         var->base = vmx_read_guest_seg_base(vmx, seg);
3114         var->limit = vmx_read_guest_seg_limit(vmx, seg);
3115         var->selector = vmx_read_guest_seg_selector(vmx, seg);
3116         ar = vmx_read_guest_seg_ar(vmx, seg);
3117 use_saved_rmode_seg:
3118         if ((ar & AR_UNUSABLE_MASK) && !emulate_invalid_guest_state)
3119                 ar = 0;
3120         var->type = ar & 15;
3121         var->s = (ar >> 4) & 1;
3122         var->dpl = (ar >> 5) & 3;
3123         var->present = (ar >> 7) & 1;
3124         var->avl = (ar >> 12) & 1;
3125         var->l = (ar >> 13) & 1;
3126         var->db = (ar >> 14) & 1;
3127         var->g = (ar >> 15) & 1;
3128         var->unusable = (ar >> 16) & 1;
3129 }
3130
3131 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3132 {
3133         struct kvm_segment s;
3134
3135         if (to_vmx(vcpu)->rmode.vm86_active) {
3136                 vmx_get_segment(vcpu, &s, seg);
3137                 return s.base;
3138         }
3139         return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3140 }
3141
3142 static int __vmx_get_cpl(struct kvm_vcpu *vcpu)
3143 {
3144         if (!is_protmode(vcpu))
3145                 return 0;
3146
3147         if (!is_long_mode(vcpu)
3148             && (kvm_get_rflags(vcpu) & X86_EFLAGS_VM)) /* if virtual 8086 */
3149                 return 3;
3150
3151         return vmx_read_guest_seg_selector(to_vmx(vcpu), VCPU_SREG_CS) & 3;
3152 }
3153
3154 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
3155 {
3156         if (!test_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail)) {
3157                 __set_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
3158                 to_vmx(vcpu)->cpl = __vmx_get_cpl(vcpu);
3159         }
3160         return to_vmx(vcpu)->cpl;
3161 }
3162
3163
3164 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3165 {
3166         u32 ar;
3167
3168         if (var->unusable)
3169                 ar = 1 << 16;
3170         else {
3171                 ar = var->type & 15;
3172                 ar |= (var->s & 1) << 4;
3173                 ar |= (var->dpl & 3) << 5;
3174                 ar |= (var->present & 1) << 7;
3175                 ar |= (var->avl & 1) << 12;
3176                 ar |= (var->l & 1) << 13;
3177                 ar |= (var->db & 1) << 14;
3178                 ar |= (var->g & 1) << 15;
3179         }
3180         if (ar == 0) /* a 0 value means unusable */
3181                 ar = AR_UNUSABLE_MASK;
3182
3183         return ar;
3184 }
3185
3186 static void vmx_set_segment(struct kvm_vcpu *vcpu,
3187                             struct kvm_segment *var, int seg)
3188 {
3189         struct vcpu_vmx *vmx = to_vmx(vcpu);
3190         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3191         u32 ar;
3192
3193         vmx_segment_cache_clear(vmx);
3194
3195         if (vmx->rmode.vm86_active && seg == VCPU_SREG_TR) {
3196                 vmcs_write16(sf->selector, var->selector);
3197                 vmx->rmode.tr.selector = var->selector;
3198                 vmx->rmode.tr.base = var->base;
3199                 vmx->rmode.tr.limit = var->limit;
3200                 vmx->rmode.tr.ar = vmx_segment_access_rights(var);
3201                 return;
3202         }
3203         vmcs_writel(sf->base, var->base);
3204         vmcs_write32(sf->limit, var->limit);
3205         vmcs_write16(sf->selector, var->selector);
3206         if (vmx->rmode.vm86_active && var->s) {
3207                 /*
3208                  * Hack real-mode segments into vm86 compatibility.
3209                  */
3210                 if (var->base == 0xffff0000 && var->selector == 0xf000)
3211                         vmcs_writel(sf->base, 0xf0000);
3212                 ar = 0xf3;
3213         } else
3214                 ar = vmx_segment_access_rights(var);
3215
3216         /*
3217          *   Fix the "Accessed" bit in AR field of segment registers for older
3218          * qemu binaries.
3219          *   IA32 arch specifies that at the time of processor reset the
3220          * "Accessed" bit in the AR field of segment registers is 1. And qemu
3221          * is setting it to 0 in the usedland code. This causes invalid guest
3222          * state vmexit when "unrestricted guest" mode is turned on.
3223          *    Fix for this setup issue in cpu_reset is being pushed in the qemu
3224          * tree. Newer qemu binaries with that qemu fix would not need this
3225          * kvm hack.
3226          */
3227         if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
3228                 ar |= 0x1; /* Accessed */
3229
3230         vmcs_write32(sf->ar_bytes, ar);
3231         __clear_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
3232 }
3233
3234 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3235 {
3236         u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3237
3238         *db = (ar >> 14) & 1;
3239         *l = (ar >> 13) & 1;
3240 }
3241
3242 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3243 {
3244         dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3245         dt->address = vmcs_readl(GUEST_IDTR_BASE);
3246 }
3247
3248 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3249 {
3250         vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3251         vmcs_writel(GUEST_IDTR_BASE, dt->address);
3252 }
3253
3254 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3255 {
3256         dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3257         dt->address = vmcs_readl(GUEST_GDTR_BASE);
3258 }
3259
3260 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3261 {
3262         vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3263         vmcs_writel(GUEST_GDTR_BASE, dt->address);
3264 }
3265
3266 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3267 {
3268         struct kvm_segment var;
3269         u32 ar;
3270
3271         vmx_get_segment(vcpu, &var, seg);
3272         ar = vmx_segment_access_rights(&var);
3273
3274         if (var.base != (var.selector << 4))
3275                 return false;
3276         if (var.limit != 0xffff)
3277                 return false;
3278         if (ar != 0xf3)
3279                 return false;
3280
3281         return true;
3282 }
3283
3284 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3285 {
3286         struct kvm_segment cs;
3287         unsigned int cs_rpl;
3288
3289         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3290         cs_rpl = cs.selector & SELECTOR_RPL_MASK;
3291
3292         if (cs.unusable)
3293                 return false;
3294         if (~cs.type & (AR_TYPE_CODE_MASK|AR_TYPE_ACCESSES_MASK))
3295                 return false;
3296         if (!cs.s)
3297                 return false;
3298         if (cs.type & AR_TYPE_WRITEABLE_MASK) {
3299                 if (cs.dpl > cs_rpl)
3300                         return false;
3301         } else {
3302                 if (cs.dpl != cs_rpl)
3303                         return false;
3304         }
3305         if (!cs.present)
3306                 return false;
3307
3308         /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3309         return true;
3310 }
3311
3312 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3313 {
3314         struct kvm_segment ss;
3315         unsigned int ss_rpl;
3316
3317         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3318         ss_rpl = ss.selector & SELECTOR_RPL_MASK;
3319
3320         if (ss.unusable)
3321                 return true;
3322         if (ss.type != 3 && ss.type != 7)
3323                 return false;
3324         if (!ss.s)
3325                 return false;
3326         if (ss.dpl != ss_rpl) /* DPL != RPL */
3327                 return false;
3328         if (!ss.present)
3329                 return false;
3330
3331         return true;
3332 }
3333
3334 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3335 {
3336         struct kvm_segment var;
3337         unsigned int rpl;
3338
3339         vmx_get_segment(vcpu, &var, seg);
3340         rpl = var.selector & SELECTOR_RPL_MASK;
3341
3342         if (var.unusable)
3343                 return true;
3344         if (!var.s)
3345                 return false;
3346         if (!var.present)
3347                 return false;
3348         if (~var.type & (AR_TYPE_CODE_MASK|AR_TYPE_WRITEABLE_MASK)) {
3349                 if (var.dpl < rpl) /* DPL < RPL */
3350                         return false;
3351         }
3352
3353         /* TODO: Add other members to kvm_segment_field to allow checking for other access
3354          * rights flags
3355          */
3356         return true;
3357 }
3358
3359 static bool tr_valid(struct kvm_vcpu *vcpu)
3360 {
3361         struct kvm_segment tr;
3362
3363         vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3364
3365         if (tr.unusable)
3366                 return false;
3367         if (tr.selector & SELECTOR_TI_MASK)     /* TI = 1 */
3368                 return false;
3369         if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3370                 return false;
3371         if (!tr.present)
3372                 return false;
3373
3374         return true;
3375 }
3376
3377 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3378 {
3379         struct kvm_segment ldtr;
3380
3381         vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3382
3383         if (ldtr.unusable)
3384                 return true;
3385         if (ldtr.selector & SELECTOR_TI_MASK)   /* TI = 1 */
3386                 return false;
3387         if (ldtr.type != 2)
3388                 return false;
3389         if (!ldtr.present)
3390                 return false;
3391
3392         return true;
3393 }
3394
3395 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3396 {
3397         struct kvm_segment cs, ss;
3398
3399         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3400         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3401
3402         return ((cs.selector & SELECTOR_RPL_MASK) ==
3403                  (ss.selector & SELECTOR_RPL_MASK));
3404 }
3405
3406 /*
3407  * Check if guest state is valid. Returns true if valid, false if
3408  * not.
3409  * We assume that registers are always usable
3410  */
3411 static bool guest_state_valid(struct kvm_vcpu *vcpu)
3412 {
3413         /* real mode guest state checks */
3414         if (!is_protmode(vcpu)) {
3415                 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3416                         return false;
3417                 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3418                         return false;
3419                 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3420                         return false;
3421                 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3422                         return false;
3423                 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3424                         return false;
3425                 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3426                         return false;
3427         } else {
3428         /* protected mode guest state checks */
3429                 if (!cs_ss_rpl_check(vcpu))
3430                         return false;
3431                 if (!code_segment_valid(vcpu))
3432                         return false;
3433                 if (!stack_segment_valid(vcpu))
3434                         return false;
3435                 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3436                         return false;
3437                 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3438                         return false;
3439                 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3440                         return false;
3441                 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3442                         return false;
3443                 if (!tr_valid(vcpu))
3444                         return false;
3445                 if (!ldtr_valid(vcpu))
3446                         return false;
3447         }
3448         /* TODO:
3449          * - Add checks on RIP
3450          * - Add checks on RFLAGS
3451          */
3452
3453         return true;
3454 }
3455
3456 static int init_rmode_tss(struct kvm *kvm)
3457 {
3458         gfn_t fn;
3459         u16 data = 0;
3460         int r, idx, ret = 0;
3461
3462         idx = srcu_read_lock(&kvm->srcu);
3463         fn = rmode_tss_base(kvm) >> PAGE_SHIFT;
3464         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3465         if (r < 0)
3466                 goto out;
3467         data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3468         r = kvm_write_guest_page(kvm, fn++, &data,
3469                         TSS_IOPB_BASE_OFFSET, sizeof(u16));
3470         if (r < 0)
3471                 goto out;
3472         r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
3473         if (r < 0)
3474                 goto out;
3475         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3476         if (r < 0)
3477                 goto out;
3478         data = ~0;
3479         r = kvm_write_guest_page(kvm, fn, &data,
3480                                  RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
3481                                  sizeof(u8));
3482         if (r < 0)
3483                 goto out;
3484
3485         ret = 1;
3486 out:
3487         srcu_read_unlock(&kvm->srcu, idx);
3488         return ret;
3489 }
3490
3491 static int init_rmode_identity_map(struct kvm *kvm)
3492 {
3493         int i, idx, r, ret;
3494         pfn_t identity_map_pfn;
3495         u32 tmp;
3496
3497         if (!enable_ept)
3498                 return 1;
3499         if (unlikely(!kvm->arch.ept_identity_pagetable)) {
3500                 printk(KERN_ERR "EPT: identity-mapping pagetable "
3501                         "haven't been allocated!\n");
3502                 return 0;
3503         }
3504         if (likely(kvm->arch.ept_identity_pagetable_done))
3505                 return 1;
3506         ret = 0;
3507         identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
3508         idx = srcu_read_lock(&kvm->srcu);
3509         r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
3510         if (r < 0)
3511                 goto out;
3512         /* Set up identity-mapping pagetable for EPT in real mode */
3513         for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3514                 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3515                         _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3516                 r = kvm_write_guest_page(kvm, identity_map_pfn,
3517                                 &tmp, i * sizeof(tmp), sizeof(tmp));
3518                 if (r < 0)
3519                         goto out;
3520         }
3521         kvm->arch.ept_identity_pagetable_done = true;
3522         ret = 1;
3523 out:
3524         srcu_read_unlock(&kvm->srcu, idx);
3525         return ret;
3526 }
3527
3528 static void seg_setup(int seg)
3529 {
3530         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3531         unsigned int ar;
3532
3533         vmcs_write16(sf->selector, 0);
3534         vmcs_writel(sf->base, 0);
3535         vmcs_write32(sf->limit, 0xffff);
3536         if (enable_unrestricted_guest) {
3537                 ar = 0x93;
3538                 if (seg == VCPU_SREG_CS)
3539                         ar |= 0x08; /* code segment */
3540         } else
3541                 ar = 0xf3;
3542
3543         vmcs_write32(sf->ar_bytes, ar);
3544 }
3545
3546 static int alloc_apic_access_page(struct kvm *kvm)
3547 {
3548         struct kvm_userspace_memory_region kvm_userspace_mem;
3549         int r = 0;
3550
3551         mutex_lock(&kvm->slots_lock);
3552         if (kvm->arch.apic_access_page)
3553                 goto out;
3554         kvm_userspace_mem.slot = APIC_ACCESS_PAGE_PRIVATE_MEMSLOT;
3555         kvm_userspace_mem.flags = 0;
3556         kvm_userspace_mem.guest_phys_addr = 0xfee00000ULL;
3557         kvm_userspace_mem.memory_size = PAGE_SIZE;
3558         r = __kvm_set_memory_region(kvm, &kvm_userspace_mem, 0);
3559         if (r)
3560                 goto out;
3561
3562         kvm->arch.apic_access_page = gfn_to_page(kvm, 0xfee00);
3563 out:
3564         mutex_unlock(&kvm->slots_lock);
3565         return r;
3566 }
3567
3568 static int alloc_identity_pagetable(struct kvm *kvm)
3569 {
3570         struct kvm_userspace_memory_region kvm_userspace_mem;
3571         int r = 0;
3572
3573         mutex_lock(&kvm->slots_lock);
3574         if (kvm->arch.ept_identity_pagetable)
3575                 goto out;
3576         kvm_userspace_mem.slot = IDENTITY_PAGETABLE_PRIVATE_MEMSLOT;
3577         kvm_userspace_mem.flags = 0;
3578         kvm_userspace_mem.guest_phys_addr =
3579                 kvm->arch.ept_identity_map_addr;
3580         kvm_userspace_mem.memory_size = PAGE_SIZE;
3581         r = __kvm_set_memory_region(kvm, &kvm_userspace_mem, 0);
3582         if (r)
3583                 goto out;
3584
3585         kvm->arch.ept_identity_pagetable = gfn_to_page(kvm,
3586                         kvm->arch.ept_identity_map_addr >> PAGE_SHIFT);
3587 out:
3588         mutex_unlock(&kvm->slots_lock);
3589         return r;
3590 }
3591
3592 static void allocate_vpid(struct vcpu_vmx *vmx)
3593 {
3594         int vpid;
3595
3596         vmx->vpid = 0;
3597         if (!enable_vpid)
3598                 return;
3599         spin_lock(&vmx_vpid_lock);
3600         vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3601         if (vpid < VMX_NR_VPIDS) {
3602                 vmx->vpid = vpid;
3603                 __set_bit(vpid, vmx_vpid_bitmap);
3604         }
3605         spin_unlock(&vmx_vpid_lock);
3606 }
3607
3608 static void free_vpid(struct vcpu_vmx *vmx)
3609 {
3610         if (!enable_vpid)
3611                 return;
3612         spin_lock(&vmx_vpid_lock);
3613         if (vmx->vpid != 0)
3614                 __clear_bit(vmx->vpid, vmx_vpid_bitmap);
3615         spin_unlock(&vmx_vpid_lock);
3616 }
3617
3618 static void __vmx_disable_intercept_for_msr(unsigned long *msr_bitmap, u32 msr)
3619 {
3620         int f = sizeof(unsigned long);
3621
3622         if (!cpu_has_vmx_msr_bitmap())
3623                 return;
3624
3625         /*
3626          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3627          * have the write-low and read-high bitmap offsets the wrong way round.
3628          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3629          */
3630         if (msr <= 0x1fff) {
3631                 __clear_bit(msr, msr_bitmap + 0x000 / f); /* read-low */
3632                 __clear_bit(msr, msr_bitmap + 0x800 / f); /* write-low */
3633         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3634                 msr &= 0x1fff;
3635                 __clear_bit(msr, msr_bitmap + 0x400 / f); /* read-high */
3636                 __clear_bit(msr, msr_bitmap + 0xc00 / f); /* write-high */
3637         }
3638 }
3639
3640 static void vmx_disable_intercept_for_msr(u32 msr, bool longmode_only)
3641 {
3642         if (!longmode_only)
3643                 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy, msr);
3644         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode, msr);
3645 }
3646
3647 /*
3648  * Set up the vmcs's constant host-state fields, i.e., host-state fields that
3649  * will not change in the lifetime of the guest.
3650  * Note that host-state that does change is set elsewhere. E.g., host-state
3651  * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
3652  */
3653 static void vmx_set_constant_host_state(void)
3654 {
3655         u32 low32, high32;
3656         unsigned long tmpl;
3657         struct desc_ptr dt;
3658
3659         vmcs_writel(HOST_CR0, read_cr0() | X86_CR0_TS);  /* 22.2.3 */
3660         vmcs_writel(HOST_CR4, read_cr4());  /* 22.2.3, 22.2.5 */
3661         vmcs_writel(HOST_CR3, read_cr3());  /* 22.2.3  FIXME: shadow tables */
3662
3663         vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
3664 #ifdef CONFIG_X86_64
3665         /*
3666          * Load null selectors, so we can avoid reloading them in
3667          * __vmx_load_host_state(), in case userspace uses the null selectors
3668          * too (the expected case).
3669          */
3670         vmcs_write16(HOST_DS_SELECTOR, 0);
3671         vmcs_write16(HOST_ES_SELECTOR, 0);
3672 #else
3673         vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
3674         vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
3675 #endif
3676         vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
3677         vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
3678
3679         native_store_idt(&dt);
3680         vmcs_writel(HOST_IDTR_BASE, dt.address);   /* 22.2.4 */
3681
3682         asm("mov $.Lkvm_vmx_return, %0" : "=r"(tmpl));
3683         vmcs_writel(HOST_RIP, tmpl); /* 22.2.5 */
3684
3685         rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
3686         vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
3687         rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
3688         vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl);   /* 22.2.3 */
3689
3690         if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
3691                 rdmsr(MSR_IA32_CR_PAT, low32, high32);
3692                 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
3693         }
3694 }
3695
3696 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
3697 {
3698         vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
3699         if (enable_ept)
3700                 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
3701         if (is_guest_mode(&vmx->vcpu))
3702                 vmx->vcpu.arch.cr4_guest_owned_bits &=
3703                         ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
3704         vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
3705 }
3706
3707 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
3708 {
3709         u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
3710         if (!vm_need_tpr_shadow(vmx->vcpu.kvm)) {
3711                 exec_control &= ~CPU_BASED_TPR_SHADOW;
3712 #ifdef CONFIG_X86_64
3713                 exec_control |= CPU_BASED_CR8_STORE_EXITING |
3714                                 CPU_BASED_CR8_LOAD_EXITING;
3715 #endif
3716         }
3717         if (!enable_ept)
3718                 exec_control |= CPU_BASED_CR3_STORE_EXITING |
3719                                 CPU_BASED_CR3_LOAD_EXITING  |
3720                                 CPU_BASED_INVLPG_EXITING;
3721         return exec_control;
3722 }
3723
3724 static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
3725 {
3726         u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
3727         if (!vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
3728                 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
3729         if (vmx->vpid == 0)
3730                 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
3731         if (!enable_ept) {
3732                 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
3733                 enable_unrestricted_guest = 0;
3734         }
3735         if (!enable_unrestricted_guest)
3736                 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
3737         if (!ple_gap)
3738                 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
3739         return exec_control;
3740 }
3741
3742 static void ept_set_mmio_spte_mask(void)
3743 {
3744         /*
3745          * EPT Misconfigurations can be generated if the value of bits 2:0
3746          * of an EPT paging-structure entry is 110b (write/execute).
3747          * Also, magic bits (0xffull << 49) is set to quickly identify mmio
3748          * spte.
3749          */
3750         kvm_mmu_set_mmio_spte_mask(0xffull << 49 | 0x6ull);
3751 }
3752
3753 /*
3754  * Sets up the vmcs for emulated real mode.
3755  */
3756 static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
3757 {
3758 #ifdef CONFIG_X86_64
3759         unsigned long a;
3760 #endif
3761         int i;
3762
3763         /* I/O */
3764         vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
3765         vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));
3766
3767         if (cpu_has_vmx_msr_bitmap())
3768                 vmcs_write64(MSR_BITMAP, __pa(vmx_msr_bitmap_legacy));
3769
3770         vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
3771
3772         /* Control */
3773         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL,
3774                 vmcs_config.pin_based_exec_ctrl);
3775
3776         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
3777
3778         if (cpu_has_secondary_exec_ctrls()) {
3779                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
3780                                 vmx_secondary_exec_control(vmx));
3781         }
3782
3783         if (ple_gap) {
3784                 vmcs_write32(PLE_GAP, ple_gap);
3785                 vmcs_write32(PLE_WINDOW, ple_window);
3786         }
3787
3788         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
3789         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
3790         vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
3791
3792         vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
3793         vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
3794         vmx_set_constant_host_state();
3795 #ifdef CONFIG_X86_64
3796         rdmsrl(MSR_FS_BASE, a);
3797         vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
3798         rdmsrl(MSR_GS_BASE, a);
3799         vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
3800 #else
3801         vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
3802         vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
3803 #endif
3804
3805         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
3806         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
3807         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
3808         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
3809         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
3810
3811         if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
3812                 u32 msr_low, msr_high;
3813                 u64 host_pat;
3814                 rdmsr(MSR_IA32_CR_PAT, msr_low, msr_high);
3815                 host_pat = msr_low | ((u64) msr_high << 32);
3816                 /* Write the default value follow host pat */
3817                 vmcs_write64(GUEST_IA32_PAT, host_pat);
3818                 /* Keep arch.pat sync with GUEST_IA32_PAT */
3819                 vmx->vcpu.arch.pat = host_pat;
3820         }
3821
3822         for (i = 0; i < NR_VMX_MSR; ++i) {
3823                 u32 index = vmx_msr_index[i];
3824                 u32 data_low, data_high;
3825                 int j = vmx->nmsrs;
3826
3827                 if (rdmsr_safe(index, &data_low, &data_high) < 0)
3828                         continue;
3829                 if (wrmsr_safe(index, data_low, data_high) < 0)
3830                         continue;
3831                 vmx->guest_msrs[j].index = i;
3832                 vmx->guest_msrs[j].data = 0;
3833                 vmx->guest_msrs[j].mask = -1ull;
3834                 ++vmx->nmsrs;
3835         }
3836
3837         vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
3838
3839         /* 22.2.1, 20.8.1 */
3840         vmcs_write32(VM_ENTRY_CONTROLS, vmcs_config.vmentry_ctrl);
3841
3842         vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL);
3843         set_cr4_guest_host_mask(vmx);
3844
3845         kvm_write_tsc(&vmx->vcpu, 0);
3846
3847         return 0;
3848 }
3849
3850 static int vmx_vcpu_reset(struct kvm_vcpu *vcpu)
3851 {
3852         struct vcpu_vmx *vmx = to_vmx(vcpu);
3853         u64 msr;
3854         int ret;
3855
3856         vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP));
3857
3858         vmx->rmode.vm86_active = 0;
3859
3860         vmx->soft_vnmi_blocked = 0;
3861
3862         vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
3863         kvm_set_cr8(&vmx->vcpu, 0);
3864         msr = 0xfee00000 | MSR_IA32_APICBASE_ENABLE;
3865         if (kvm_vcpu_is_bsp(&vmx->vcpu))
3866                 msr |= MSR_IA32_APICBASE_BSP;
3867         kvm_set_apic_base(&vmx->vcpu, msr);
3868
3869         ret = fx_init(&vmx->vcpu);
3870         if (ret != 0)
3871                 goto out;
3872
3873         vmx_segment_cache_clear(vmx);
3874
3875         seg_setup(VCPU_SREG_CS);
3876         /*
3877          * GUEST_CS_BASE should really be 0xffff0000, but VT vm86 mode
3878          * insists on having GUEST_CS_BASE == GUEST_CS_SELECTOR << 4.  Sigh.
3879          */
3880         if (kvm_vcpu_is_bsp(&vmx->vcpu)) {
3881                 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
3882                 vmcs_writel(GUEST_CS_BASE, 0x000f0000);
3883         } else {
3884                 vmcs_write16(GUEST_CS_SELECTOR, vmx->vcpu.arch.sipi_vector << 8);
3885                 vmcs_writel(GUEST_CS_BASE, vmx->vcpu.arch.sipi_vector << 12);
3886         }
3887
3888         seg_setup(VCPU_SREG_DS);
3889         seg_setup(VCPU_SREG_ES);
3890         seg_setup(VCPU_SREG_FS);
3891         seg_setup(VCPU_SREG_GS);
3892         seg_setup(VCPU_SREG_SS);
3893
3894         vmcs_write16(GUEST_TR_SELECTOR, 0);
3895         vmcs_writel(GUEST_TR_BASE, 0);
3896         vmcs_write32(GUEST_TR_LIMIT, 0xffff);
3897         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
3898
3899         vmcs_write16(GUEST_LDTR_SELECTOR, 0);
3900         vmcs_writel(GUEST_LDTR_BASE, 0);
3901         vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
3902         vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
3903
3904         vmcs_write32(GUEST_SYSENTER_CS, 0);
3905         vmcs_writel(GUEST_SYSENTER_ESP, 0);
3906         vmcs_writel(GUEST_SYSENTER_EIP, 0);
3907
3908         vmcs_writel(GUEST_RFLAGS, 0x02);
3909         if (kvm_vcpu_is_bsp(&vmx->vcpu))
3910                 kvm_rip_write(vcpu, 0xfff0);
3911         else
3912                 kvm_rip_write(vcpu, 0);
3913         kvm_register_write(vcpu, VCPU_REGS_RSP, 0);
3914
3915         vmcs_writel(GUEST_DR7, 0x400);
3916
3917         vmcs_writel(GUEST_GDTR_BASE, 0);
3918         vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
3919
3920         vmcs_writel(GUEST_IDTR_BASE, 0);
3921         vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
3922
3923         vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
3924         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
3925         vmcs_write32(GUEST_PENDING_DBG_EXCEPTIONS, 0);
3926
3927         /* Special registers */
3928         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
3929
3930         setup_msrs(vmx);
3931
3932         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
3933
3934         if (cpu_has_vmx_tpr_shadow()) {
3935                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
3936                 if (vm_need_tpr_shadow(vmx->vcpu.kvm))
3937                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
3938                                      __pa(vmx->vcpu.arch.apic->regs));
3939                 vmcs_write32(TPR_THRESHOLD, 0);
3940         }
3941
3942         if (vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
3943                 vmcs_write64(APIC_ACCESS_ADDR,
3944                              page_to_phys(vmx->vcpu.kvm->arch.apic_access_page));
3945
3946         if (vmx->vpid != 0)
3947                 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
3948
3949         vmx->vcpu.arch.cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
3950         vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
3951         vmx_set_cr0(&vmx->vcpu, kvm_read_cr0(vcpu)); /* enter rmode */
3952         srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
3953         vmx_set_cr4(&vmx->vcpu, 0);
3954         vmx_set_efer(&vmx->vcpu, 0);
3955         vmx_fpu_activate(&vmx->vcpu);
3956         update_exception_bitmap(&vmx->vcpu);
3957
3958         vpid_sync_context(vmx);
3959
3960         ret = 0;
3961
3962         /* HACK: Don't enable emulation on guest boot/reset */
3963         vmx->emulation_required = 0;
3964
3965 out:
3966         return ret;
3967 }
3968
3969 /*
3970  * In nested virtualization, check if L1 asked to exit on external interrupts.
3971  * For most existing hypervisors, this will always return true.
3972  */
3973 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
3974 {
3975         return get_vmcs12(vcpu)->pin_based_vm_exec_control &
3976                 PIN_BASED_EXT_INTR_MASK;
3977 }
3978
3979 static void enable_irq_window(struct kvm_vcpu *vcpu)
3980 {
3981         u32 cpu_based_vm_exec_control;
3982         if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu)) {
3983                 /*
3984                  * We get here if vmx_interrupt_allowed() said we can't
3985                  * inject to L1 now because L2 must run. Ask L2 to exit
3986                  * right after entry, so we can inject to L1 more promptly.
3987                  */
3988                 kvm_make_request(KVM_REQ_IMMEDIATE_EXIT, vcpu);
3989                 return;
3990         }
3991
3992         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
3993         cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING;
3994         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
3995 }
3996
3997 static void enable_nmi_window(struct kvm_vcpu *vcpu)
3998 {
3999         u32 cpu_based_vm_exec_control;
4000
4001         if (!cpu_has_virtual_nmis()) {
4002                 enable_irq_window(vcpu);
4003                 return;
4004         }
4005
4006         if (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4007                 enable_irq_window(vcpu);
4008                 return;
4009         }
4010         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
4011         cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_NMI_PENDING;
4012         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
4013 }
4014
4015 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4016 {
4017         struct vcpu_vmx *vmx = to_vmx(vcpu);
4018         uint32_t intr;
4019         int irq = vcpu->arch.interrupt.nr;
4020
4021         trace_kvm_inj_virq(irq);
4022
4023         ++vcpu->stat.irq_injections;
4024         if (vmx->rmode.vm86_active) {
4025                 int inc_eip = 0;
4026                 if (vcpu->arch.interrupt.soft)
4027                         inc_eip = vcpu->arch.event_exit_inst_len;
4028                 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
4029                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4030                 return;
4031         }
4032         intr = irq | INTR_INFO_VALID_MASK;
4033         if (vcpu->arch.interrupt.soft) {
4034                 intr |= INTR_TYPE_SOFT_INTR;
4035                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4036                              vmx->vcpu.arch.event_exit_inst_len);
4037         } else
4038                 intr |= INTR_TYPE_EXT_INTR;
4039         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4040 }
4041
4042 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4043 {
4044         struct vcpu_vmx *vmx = to_vmx(vcpu);
4045
4046         if (is_guest_mode(vcpu))
4047                 return;
4048
4049         if (!cpu_has_virtual_nmis()) {
4050                 /*
4051                  * Tracking the NMI-blocked state in software is built upon
4052                  * finding the next open IRQ window. This, in turn, depends on
4053                  * well-behaving guests: They have to keep IRQs disabled at
4054                  * least as long as the NMI handler runs. Otherwise we may
4055                  * cause NMI nesting, maybe breaking the guest. But as this is
4056                  * highly unlikely, we can live with the residual risk.
4057                  */
4058                 vmx->soft_vnmi_blocked = 1;
4059                 vmx->vnmi_blocked_time = 0;
4060         }
4061
4062         ++vcpu->stat.nmi_injections;
4063         vmx->nmi_known_unmasked = false;
4064         if (vmx->rmode.vm86_active) {
4065                 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
4066                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4067                 return;
4068         }
4069         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4070                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4071 }
4072
4073 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
4074 {
4075         if (!cpu_has_virtual_nmis() && to_vmx(vcpu)->soft_vnmi_blocked)
4076                 return 0;
4077
4078         return  !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4079                   (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
4080                    | GUEST_INTR_STATE_NMI));
4081 }
4082
4083 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4084 {
4085         if (!cpu_has_virtual_nmis())
4086                 return to_vmx(vcpu)->soft_vnmi_blocked;
4087         if (to_vmx(vcpu)->nmi_known_unmasked)
4088                 return false;
4089         return vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4090 }
4091
4092 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4093 {
4094         struct vcpu_vmx *vmx = to_vmx(vcpu);
4095
4096         if (!cpu_has_virtual_nmis()) {
4097                 if (vmx->soft_vnmi_blocked != masked) {
4098                         vmx->soft_vnmi_blocked = masked;
4099                         vmx->vnmi_blocked_time = 0;
4100                 }
4101         } else {
4102                 vmx->nmi_known_unmasked = !masked;
4103                 if (masked)
4104                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4105                                       GUEST_INTR_STATE_NMI);
4106                 else
4107                         vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4108                                         GUEST_INTR_STATE_NMI);
4109         }
4110 }
4111
4112 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
4113 {
4114         if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu)) {
4115                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4116                 if (to_vmx(vcpu)->nested.nested_run_pending ||
4117                     (vmcs12->idt_vectoring_info_field &
4118                      VECTORING_INFO_VALID_MASK))
4119                         return 0;
4120                 nested_vmx_vmexit(vcpu);
4121                 vmcs12->vm_exit_reason = EXIT_REASON_EXTERNAL_INTERRUPT;
4122                 vmcs12->vm_exit_intr_info = 0;
4123                 /* fall through to normal code, but now in L1, not L2 */
4124         }
4125
4126         return (vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
4127                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4128                         (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4129 }
4130
4131 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4132 {
4133         int ret;
4134         struct kvm_userspace_memory_region tss_mem = {
4135                 .slot = TSS_PRIVATE_MEMSLOT,
4136                 .guest_phys_addr = addr,
4137                 .memory_size = PAGE_SIZE * 3,
4138                 .flags = 0,
4139         };
4140
4141         ret = kvm_set_memory_region(kvm, &tss_mem, 0);
4142         if (ret)
4143                 return ret;
4144         kvm->arch.tss_addr = addr;
4145         if (!init_rmode_tss(kvm))
4146                 return  -ENOMEM;
4147
4148         return 0;
4149 }
4150
4151 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4152                                   int vec, u32 err_code)
4153 {
4154         /*
4155          * Instruction with address size override prefix opcode 0x67
4156          * Cause the #SS fault with 0 error code in VM86 mode.
4157          */
4158         if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0)
4159                 if (emulate_instruction(vcpu, 0) == EMULATE_DONE)
4160                         return 1;
4161         /*
4162          * Forward all other exceptions that are valid in real mode.
4163          * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4164          *        the required debugging infrastructure rework.
4165          */
4166         switch (vec) {
4167         case DB_VECTOR:
4168                 if (vcpu->guest_debug &
4169                     (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
4170                         return 0;
4171                 kvm_queue_exception(vcpu, vec);
4172                 return 1;
4173         case BP_VECTOR:
4174                 /*
4175                  * Update instruction length as we may reinject the exception
4176                  * from user space while in guest debugging mode.
4177                  */
4178                 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4179                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4180                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4181                         return 0;
4182                 /* fall through */
4183         case DE_VECTOR:
4184         case OF_VECTOR:
4185         case BR_VECTOR:
4186         case UD_VECTOR:
4187         case DF_VECTOR:
4188         case SS_VECTOR:
4189         case GP_VECTOR:
4190         case MF_VECTOR:
4191                 kvm_queue_exception(vcpu, vec);
4192                 return 1;
4193         }
4194         return 0;
4195 }
4196
4197 /*
4198  * Trigger machine check on the host. We assume all the MSRs are already set up
4199  * by the CPU and that we still run on the same CPU as the MCE occurred on.
4200  * We pass a fake environment to the machine check handler because we want
4201  * the guest to be always treated like user space, no matter what context
4202  * it used internally.
4203  */
4204 static void kvm_machine_check(void)
4205 {
4206 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
4207         struct pt_regs regs = {
4208                 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
4209                 .flags = X86_EFLAGS_IF,
4210         };
4211
4212         do_machine_check(&regs, 0);
4213 #endif
4214 }
4215
4216 static int handle_machine_check(struct kvm_vcpu *vcpu)
4217 {
4218         /* already handled by vcpu_run */
4219         return 1;
4220 }
4221
4222 static int handle_exception(struct kvm_vcpu *vcpu)
4223 {
4224         struct vcpu_vmx *vmx = to_vmx(vcpu);
4225         struct kvm_run *kvm_run = vcpu->run;
4226         u32 intr_info, ex_no, error_code;
4227         unsigned long cr2, rip, dr6;
4228         u32 vect_info;
4229         enum emulation_result er;
4230
4231         vect_info = vmx->idt_vectoring_info;
4232         intr_info = vmx->exit_intr_info;
4233
4234         if (is_machine_check(intr_info))
4235                 return handle_machine_check(vcpu);
4236
4237         if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4238             !is_page_fault(intr_info)) {
4239                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4240                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4241                 vcpu->run->internal.ndata = 2;
4242                 vcpu->run->internal.data[0] = vect_info;
4243                 vcpu->run->internal.data[1] = intr_info;
4244                 return 0;
4245         }
4246
4247         if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR)
4248                 return 1;  /* already handled by vmx_vcpu_run() */
4249
4250         if (is_no_device(intr_info)) {
4251                 vmx_fpu_activate(vcpu);
4252                 return 1;
4253         }
4254
4255         if (is_invalid_opcode(intr_info)) {
4256                 er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
4257                 if (er != EMULATE_DONE)
4258                         kvm_queue_exception(vcpu, UD_VECTOR);
4259                 return 1;
4260         }
4261
4262         error_code = 0;
4263         if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4264                 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4265         if (is_page_fault(intr_info)) {
4266                 /* EPT won't cause page fault directly */
4267                 BUG_ON(enable_ept);
4268                 cr2 = vmcs_readl(EXIT_QUALIFICATION);
4269                 trace_kvm_page_fault(cr2, error_code);
4270
4271                 if (kvm_event_needs_reinjection(vcpu))
4272                         kvm_mmu_unprotect_page_virt(vcpu, cr2);
4273                 return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
4274         }
4275
4276         if (vmx->rmode.vm86_active &&
4277             handle_rmode_exception(vcpu, intr_info & INTR_INFO_VECTOR_MASK,
4278                                                                 error_code)) {
4279                 if (vcpu->arch.halt_request) {
4280                         vcpu->arch.halt_request = 0;
4281                         return kvm_emulate_halt(vcpu);
4282                 }
4283                 return 1;
4284         }
4285
4286         ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4287         switch (ex_no) {
4288         case DB_VECTOR:
4289                 dr6 = vmcs_readl(EXIT_QUALIFICATION);
4290                 if (!(vcpu->guest_debug &
4291                       (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4292                         vcpu->arch.dr6 = dr6 | DR6_FIXED_1;
4293                         kvm_queue_exception(vcpu, DB_VECTOR);
4294                         return 1;
4295                 }
4296                 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
4297                 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4298                 /* fall through */
4299         case BP_VECTOR:
4300                 /*
4301                  * Update instruction length as we may reinject #BP from
4302                  * user space while in guest debugging mode. Reading it for
4303                  * #DB as well causes no harm, it is not used in that case.
4304                  */
4305                 vmx->vcpu.arch.event_exit_inst_len =
4306                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4307                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4308                 rip = kvm_rip_read(vcpu);
4309                 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4310                 kvm_run->debug.arch.exception = ex_no;
4311                 break;
4312         default:
4313                 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4314                 kvm_run->ex.exception = ex_no;
4315                 kvm_run->ex.error_code = error_code;
4316                 break;
4317         }
4318         return 0;
4319 }
4320
4321 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
4322 {
4323         ++vcpu->stat.irq_exits;
4324         return 1;
4325 }
4326
4327 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4328 {
4329         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4330         return 0;
4331 }
4332
4333 static int handle_io(struct kvm_vcpu *vcpu)
4334 {
4335         unsigned long exit_qualification;
4336         int size, in, string;
4337         unsigned port;
4338
4339         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4340         string = (exit_qualification & 16) != 0;
4341         in = (exit_qualification & 8) != 0;
4342
4343         ++vcpu->stat.io_exits;
4344
4345         if (string || in)
4346                 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
4347
4348         port = exit_qualification >> 16;
4349         size = (exit_qualification & 7) + 1;
4350         skip_emulated_instruction(vcpu);
4351
4352         return kvm_fast_pio_out(vcpu, size, port);
4353 }
4354
4355 static void
4356 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4357 {
4358         /*
4359          * Patch in the VMCALL instruction:
4360          */
4361         hypercall[0] = 0x0f;
4362         hypercall[1] = 0x01;
4363         hypercall[2] = 0xc1;
4364 }
4365
4366 /* called to set cr0 as approriate for a mov-to-cr0 exit. */
4367 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4368 {
4369         if (to_vmx(vcpu)->nested.vmxon &&
4370             ((val & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON))
4371                 return 1;
4372
4373         if (is_guest_mode(vcpu)) {
4374                 /*
4375                  * We get here when L2 changed cr0 in a way that did not change
4376                  * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4377                  * but did change L0 shadowed bits. This can currently happen
4378                  * with the TS bit: L0 may want to leave TS on (for lazy fpu
4379                  * loading) while pretending to allow the guest to change it.
4380                  */
4381                 if (kvm_set_cr0(vcpu, (val & vcpu->arch.cr0_guest_owned_bits) |
4382                          (vcpu->arch.cr0 & ~vcpu->arch.cr0_guest_owned_bits)))
4383                         return 1;
4384                 vmcs_writel(CR0_READ_SHADOW, val);
4385                 return 0;
4386         } else
4387                 return kvm_set_cr0(vcpu, val);
4388 }
4389
4390 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
4391 {
4392         if (is_guest_mode(vcpu)) {
4393                 if (kvm_set_cr4(vcpu, (val & vcpu->arch.cr4_guest_owned_bits) |
4394                          (vcpu->arch.cr4 & ~vcpu->arch.cr4_guest_owned_bits)))
4395                         return 1;
4396                 vmcs_writel(CR4_READ_SHADOW, val);
4397                 return 0;
4398         } else
4399                 return kvm_set_cr4(vcpu, val);
4400 }
4401
4402 /* called to set cr0 as approriate for clts instruction exit. */
4403 static void handle_clts(struct kvm_vcpu *vcpu)
4404 {
4405         if (is_guest_mode(vcpu)) {
4406                 /*
4407                  * We get here when L2 did CLTS, and L1 didn't shadow CR0.TS
4408                  * but we did (!fpu_active). We need to keep GUEST_CR0.TS on,
4409                  * just pretend it's off (also in arch.cr0 for fpu_activate).
4410                  */
4411                 vmcs_writel(CR0_READ_SHADOW,
4412                         vmcs_readl(CR0_READ_SHADOW) & ~X86_CR0_TS);
4413                 vcpu->arch.cr0 &= ~X86_CR0_TS;
4414         } else
4415                 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
4416 }
4417
4418 static int handle_cr(struct kvm_vcpu *vcpu)
4419 {
4420         unsigned long exit_qualification, val;
4421         int cr;
4422         int reg;
4423         int err;
4424
4425         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4426         cr = exit_qualification & 15;
4427         reg = (exit_qualification >> 8) & 15;
4428         switch ((exit_qualification >> 4) & 3) {
4429         case 0: /* mov to cr */
4430                 val = kvm_register_read(vcpu, reg);
4431                 trace_kvm_cr_write(cr, val);
4432                 switch (cr) {
4433                 case 0:
4434                         err = handle_set_cr0(vcpu, val);
4435                         kvm_complete_insn_gp(vcpu, err);
4436                         return 1;
4437                 case 3:
4438                         err = kvm_set_cr3(vcpu, val);
4439                         kvm_complete_insn_gp(vcpu, err);
4440                         return 1;
4441                 case 4:
4442                         err = handle_set_cr4(vcpu, val);
4443                         kvm_complete_insn_gp(vcpu, err);
4444                         return 1;
4445                 case 8: {
4446                                 u8 cr8_prev = kvm_get_cr8(vcpu);
4447                                 u8 cr8 = kvm_register_read(vcpu, reg);
4448                                 err = kvm_set_cr8(vcpu, cr8);
4449                                 kvm_complete_insn_gp(vcpu, err);
4450                                 if (irqchip_in_kernel(vcpu->kvm))
4451                                         return 1;
4452                                 if (cr8_prev <= cr8)
4453                                         return 1;
4454                                 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
4455                                 return 0;
4456                         }
4457                 };
4458                 break;
4459         case 2: /* clts */
4460                 handle_clts(vcpu);
4461                 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
4462                 skip_emulated_instruction(vcpu);
4463                 vmx_fpu_activate(vcpu);
4464                 return 1;
4465         case 1: /*mov from cr*/
4466                 switch (cr) {
4467                 case 3:
4468                         val = kvm_read_cr3(vcpu);
4469                         kvm_register_write(vcpu, reg, val);
4470                         trace_kvm_cr_read(cr, val);
4471                         skip_emulated_instruction(vcpu);
4472                         return 1;
4473                 case 8:
4474                         val = kvm_get_cr8(vcpu);
4475                         kvm_register_write(vcpu, reg, val);
4476                         trace_kvm_cr_read(cr, val);
4477                         skip_emulated_instruction(vcpu);
4478                         return 1;
4479                 }
4480                 break;
4481         case 3: /* lmsw */
4482                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
4483                 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
4484                 kvm_lmsw(vcpu, val);
4485
4486                 skip_emulated_instruction(vcpu);
4487                 return 1;
4488         default:
4489                 break;
4490         }
4491         vcpu->run->exit_reason = 0;
4492         pr_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
4493                (int)(exit_qualification >> 4) & 3, cr);
4494         return 0;
4495 }
4496
4497 static int handle_dr(struct kvm_vcpu *vcpu)
4498 {
4499         unsigned long exit_qualification;
4500         int dr, reg;
4501
4502         /* Do not handle if the CPL > 0, will trigger GP on re-entry */
4503         if (!kvm_require_cpl(vcpu, 0))
4504                 return 1;
4505         dr = vmcs_readl(GUEST_DR7);
4506         if (dr & DR7_GD) {
4507                 /*
4508                  * As the vm-exit takes precedence over the debug trap, we
4509                  * need to emulate the latter, either for the host or the
4510                  * guest debugging itself.
4511                  */
4512                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
4513                         vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
4514                         vcpu->run->debug.arch.dr7 = dr;
4515                         vcpu->run->debug.arch.pc =
4516                                 vmcs_readl(GUEST_CS_BASE) +
4517                                 vmcs_readl(GUEST_RIP);
4518                         vcpu->run->debug.arch.exception = DB_VECTOR;
4519                         vcpu->run->exit_reason = KVM_EXIT_DEBUG;
4520                         return 0;
4521                 } else {
4522                         vcpu->arch.dr7 &= ~DR7_GD;
4523                         vcpu->arch.dr6 |= DR6_BD;
4524                         vmcs_writel(GUEST_DR7, vcpu->arch.dr7);
4525                         kvm_queue_exception(vcpu, DB_VECTOR);
4526                         return 1;
4527                 }
4528         }
4529
4530         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4531         dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
4532         reg = DEBUG_REG_ACCESS_REG(exit_qualification);
4533         if (exit_qualification & TYPE_MOV_FROM_DR) {
4534                 unsigned long val;
4535                 if (!kvm_get_dr(vcpu, dr, &val))
4536                         kvm_register_write(vcpu, reg, val);
4537         } else
4538                 kvm_set_dr(vcpu, dr, vcpu->arch.regs[reg]);
4539         skip_emulated_instruction(vcpu);
4540         return 1;
4541 }
4542
4543 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
4544 {
4545         vmcs_writel(GUEST_DR7, val);
4546 }
4547
4548 static int handle_cpuid(struct kvm_vcpu *vcpu)
4549 {
4550         kvm_emulate_cpuid(vcpu);
4551         return 1;
4552 }
4553
4554 static int handle_rdmsr(struct kvm_vcpu *vcpu)
4555 {
4556         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
4557         u64 data;
4558
4559         if (vmx_get_msr(vcpu, ecx, &data)) {
4560                 trace_kvm_msr_read_ex(ecx);
4561                 kvm_inject_gp(vcpu, 0);
4562                 return 1;
4563         }
4564
4565         trace_kvm_msr_read(ecx, data);
4566
4567         /* FIXME: handling of bits 32:63 of rax, rdx */
4568         vcpu->arch.regs[VCPU_REGS_RAX] = data & -1u;
4569         vcpu->arch.regs[VCPU_REGS_RDX] = (data >> 32) & -1u;
4570         skip_emulated_instruction(vcpu);
4571         return 1;
4572 }
4573
4574 static int handle_wrmsr(struct kvm_vcpu *vcpu)
4575 {
4576         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
4577         u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
4578                 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
4579
4580         if (vmx_set_msr(vcpu, ecx, data) != 0) {
4581                 trace_kvm_msr_write_ex(ecx, data);
4582                 kvm_inject_gp(vcpu, 0);
4583                 return 1;
4584         }
4585
4586         trace_kvm_msr_write(ecx, data);
4587         skip_emulated_instruction(vcpu);
4588         return 1;
4589 }
4590
4591 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
4592 {
4593         kvm_make_request(KVM_REQ_EVENT, vcpu);
4594         return 1;
4595 }
4596
4597 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
4598 {
4599         u32 cpu_based_vm_exec_control;
4600
4601         /* clear pending irq */
4602         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
4603         cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
4604         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
4605
4606         kvm_make_request(KVM_REQ_EVENT, vcpu);
4607
4608         ++vcpu->stat.irq_window_exits;
4609
4610         /*
4611          * If the user space waits to inject interrupts, exit as soon as
4612          * possible
4613          */
4614         if (!irqchip_in_kernel(vcpu->kvm) &&
4615             vcpu->run->request_interrupt_window &&
4616             !kvm_cpu_has_interrupt(vcpu)) {
4617                 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
4618                 return 0;
4619         }
4620         return 1;
4621 }
4622
4623 static int handle_halt(struct kvm_vcpu *vcpu)
4624 {
4625         skip_emulated_instruction(vcpu);
4626         return kvm_emulate_halt(vcpu);
4627 }
4628
4629 static int handle_vmcall(struct kvm_vcpu *vcpu)
4630 {
4631         skip_emulated_instruction(vcpu);
4632         kvm_emulate_hypercall(vcpu);
4633         return 1;
4634 }
4635
4636 static int handle_invd(struct kvm_vcpu *vcpu)
4637 {
4638         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
4639 }
4640
4641 static int handle_invlpg(struct kvm_vcpu *vcpu)
4642 {
4643         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4644
4645         kvm_mmu_invlpg(vcpu, exit_qualification);
4646         skip_emulated_instruction(vcpu);
4647         return 1;
4648 }
4649
4650 static int handle_rdpmc(struct kvm_vcpu *vcpu)
4651 {
4652         int err;
4653
4654         err = kvm_rdpmc(vcpu);
4655         kvm_complete_insn_gp(vcpu, err);
4656
4657         return 1;
4658 }
4659
4660 static int handle_wbinvd(struct kvm_vcpu *vcpu)
4661 {
4662         skip_emulated_instruction(vcpu);
4663         kvm_emulate_wbinvd(vcpu);
4664         return 1;
4665 }
4666
4667 static int handle_xsetbv(struct kvm_vcpu *vcpu)
4668 {
4669         u64 new_bv = kvm_read_edx_eax(vcpu);
4670         u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
4671
4672         if (kvm_set_xcr(vcpu, index, new_bv) == 0)
4673                 skip_emulated_instruction(vcpu);
4674         return 1;
4675 }
4676
4677 static int handle_apic_access(struct kvm_vcpu *vcpu)
4678 {
4679         if (likely(fasteoi)) {
4680                 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4681                 int access_type, offset;
4682
4683                 access_type = exit_qualification & APIC_ACCESS_TYPE;
4684                 offset = exit_qualification & APIC_ACCESS_OFFSET;
4685                 /*
4686                  * Sane guest uses MOV to write EOI, with written value
4687                  * not cared. So make a short-circuit here by avoiding
4688                  * heavy instruction emulation.
4689                  */
4690                 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
4691                     (offset == APIC_EOI)) {
4692                         kvm_lapic_set_eoi(vcpu);
4693                         skip_emulated_instruction(vcpu);
4694                         return 1;
4695                 }
4696         }
4697         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
4698 }
4699
4700 static int handle_task_switch(struct kvm_vcpu *vcpu)
4701 {
4702         struct vcpu_vmx *vmx = to_vmx(vcpu);
4703         unsigned long exit_qualification;
4704         bool has_error_code = false;
4705         u32 error_code = 0;
4706         u16 tss_selector;
4707         int reason, type, idt_v, idt_index;
4708
4709         idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
4710         idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
4711         type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
4712
4713         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4714
4715         reason = (u32)exit_qualification >> 30;
4716         if (reason == TASK_SWITCH_GATE && idt_v) {
4717                 switch (type) {
4718                 case INTR_TYPE_NMI_INTR:
4719                         vcpu->arch.nmi_injected = false;
4720                         vmx_set_nmi_mask(vcpu, true);
4721                         break;
4722                 case INTR_TYPE_EXT_INTR:
4723                 case INTR_TYPE_SOFT_INTR:
4724                         kvm_clear_interrupt_queue(vcpu);
4725                         break;
4726                 case INTR_TYPE_HARD_EXCEPTION:
4727                         if (vmx->idt_vectoring_info &
4728                             VECTORING_INFO_DELIVER_CODE_MASK) {
4729                                 has_error_code = true;
4730                                 error_code =
4731                                         vmcs_read32(IDT_VECTORING_ERROR_CODE);
4732                         }
4733                         /* fall through */
4734                 case INTR_TYPE_SOFT_EXCEPTION:
4735                         kvm_clear_exception_queue(vcpu);
4736                         break;
4737                 default:
4738                         break;
4739                 }
4740         }
4741         tss_selector = exit_qualification;
4742
4743         if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
4744                        type != INTR_TYPE_EXT_INTR &&
4745                        type != INTR_TYPE_NMI_INTR))
4746                 skip_emulated_instruction(vcpu);
4747
4748         if (kvm_task_switch(vcpu, tss_selector,
4749                             type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
4750                             has_error_code, error_code) == EMULATE_FAIL) {
4751                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4752                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
4753                 vcpu->run->internal.ndata = 0;
4754                 return 0;
4755         }
4756
4757         /* clear all local breakpoint enable flags */
4758         vmcs_writel(GUEST_DR7, vmcs_readl(GUEST_DR7) & ~55);
4759
4760         /*
4761          * TODO: What about debug traps on tss switch?
4762          *       Are we supposed to inject them and update dr6?
4763          */
4764
4765         return 1;
4766 }
4767
4768 static int handle_ept_violation(struct kvm_vcpu *vcpu)
4769 {
4770         unsigned long exit_qualification;
4771         gpa_t gpa;
4772         int gla_validity;
4773
4774         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4775
4776         if (exit_qualification & (1 << 6)) {
4777                 printk(KERN_ERR "EPT: GPA exceeds GAW!\n");
4778                 return -EINVAL;
4779         }
4780
4781         gla_validity = (exit_qualification >> 7) & 0x3;
4782         if (gla_validity != 0x3 && gla_validity != 0x1 && gla_validity != 0) {
4783                 printk(KERN_ERR "EPT: Handling EPT violation failed!\n");
4784                 printk(KERN_ERR "EPT: GPA: 0x%lx, GVA: 0x%lx\n",
4785                         (long unsigned int)vmcs_read64(GUEST_PHYSICAL_ADDRESS),
4786                         vmcs_readl(GUEST_LINEAR_ADDRESS));
4787                 printk(KERN_ERR "EPT: Exit qualification is 0x%lx\n",
4788                         (long unsigned int)exit_qualification);
4789                 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
4790                 vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_VIOLATION;
4791                 return 0;
4792         }
4793
4794         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
4795         trace_kvm_page_fault(gpa, exit_qualification);
4796         return kvm_mmu_page_fault(vcpu, gpa, exit_qualification & 0x3, NULL, 0);
4797 }
4798
4799 static u64 ept_rsvd_mask(u64 spte, int level)
4800 {
4801         int i;
4802         u64 mask = 0;
4803
4804         for (i = 51; i > boot_cpu_data.x86_phys_bits; i--)
4805                 mask |= (1ULL << i);
4806
4807         if (level > 2)
4808                 /* bits 7:3 reserved */
4809                 mask |= 0xf8;
4810         else if (level == 2) {
4811                 if (spte & (1ULL << 7))
4812                         /* 2MB ref, bits 20:12 reserved */
4813                         mask |= 0x1ff000;
4814                 else
4815                         /* bits 6:3 reserved */
4816                         mask |= 0x78;
4817         }
4818
4819         return mask;
4820 }
4821
4822 static void ept_misconfig_inspect_spte(struct kvm_vcpu *vcpu, u64 spte,
4823                                        int level)
4824 {
4825         printk(KERN_ERR "%s: spte 0x%llx level %d\n", __func__, spte, level);
4826
4827         /* 010b (write-only) */
4828         WARN_ON((spte & 0x7) == 0x2);
4829
4830         /* 110b (write/execute) */
4831         WARN_ON((spte & 0x7) == 0x6);
4832
4833         /* 100b (execute-only) and value not supported by logical processor */
4834         if (!cpu_has_vmx_ept_execute_only())
4835                 WARN_ON((spte & 0x7) == 0x4);
4836
4837         /* not 000b */
4838         if ((spte & 0x7)) {
4839                 u64 rsvd_bits = spte & ept_rsvd_mask(spte, level);
4840
4841                 if (rsvd_bits != 0) {
4842                         printk(KERN_ERR "%s: rsvd_bits = 0x%llx\n",
4843                                          __func__, rsvd_bits);
4844                         WARN_ON(1);
4845                 }
4846
4847                 if (level == 1 || (level == 2 && (spte & (1ULL << 7)))) {
4848                         u64 ept_mem_type = (spte & 0x38) >> 3;
4849
4850                         if (ept_mem_type == 2 || ept_mem_type == 3 ||
4851                             ept_mem_type == 7) {
4852                                 printk(KERN_ERR "%s: ept_mem_type=0x%llx\n",
4853                                                 __func__, ept_mem_type);
4854                                 WARN_ON(1);
4855                         }
4856                 }
4857         }
4858 }
4859
4860 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
4861 {
4862         u64 sptes[4];
4863         int nr_sptes, i, ret;
4864         gpa_t gpa;
4865
4866         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
4867
4868         ret = handle_mmio_page_fault_common(vcpu, gpa, true);
4869         if (likely(ret == 1))
4870                 return x86_emulate_instruction(vcpu, gpa, 0, NULL, 0) ==
4871                                               EMULATE_DONE;
4872         if (unlikely(!ret))
4873                 return 1;
4874
4875         /* It is the real ept misconfig */
4876         printk(KERN_ERR "EPT: Misconfiguration.\n");
4877         printk(KERN_ERR "EPT: GPA: 0x%llx\n", gpa);
4878
4879         nr_sptes = kvm_mmu_get_spte_hierarchy(vcpu, gpa, sptes);
4880
4881         for (i = PT64_ROOT_LEVEL; i > PT64_ROOT_LEVEL - nr_sptes; --i)
4882                 ept_misconfig_inspect_spte(vcpu, sptes[i-1], i);
4883
4884         vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
4885         vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
4886
4887         return 0;
4888 }
4889
4890 static int handle_nmi_window(struct kvm_vcpu *vcpu)
4891 {
4892         u32 cpu_based_vm_exec_control;
4893
4894         /* clear pending NMI */
4895         cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
4896         cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
4897         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
4898         ++vcpu->stat.nmi_window_exits;
4899         kvm_make_request(KVM_REQ_EVENT, vcpu);
4900
4901         return 1;
4902 }
4903
4904 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
4905 {
4906         struct vcpu_vmx *vmx = to_vmx(vcpu);
4907         enum emulation_result err = EMULATE_DONE;
4908         int ret = 1;
4909         u32 cpu_exec_ctrl;
4910         bool intr_window_requested;
4911
4912         cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
4913         intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
4914
4915         while (!guest_state_valid(vcpu)) {
4916                 if (intr_window_requested
4917                     && (kvm_get_rflags(&vmx->vcpu) & X86_EFLAGS_IF))
4918                         return handle_interrupt_window(&vmx->vcpu);
4919
4920                 err = emulate_instruction(vcpu, 0);
4921
4922                 if (err == EMULATE_DO_MMIO) {
4923                         ret = 0;
4924                         goto out;
4925                 }
4926
4927                 if (err != EMULATE_DONE)
4928                         return 0;
4929
4930                 if (signal_pending(current))
4931                         goto out;
4932                 if (need_resched())
4933                         schedule();
4934         }
4935
4936         vmx->emulation_required = 0;
4937 out:
4938         return ret;
4939 }
4940
4941 /*
4942  * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
4943  * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
4944  */
4945 static int handle_pause(struct kvm_vcpu *vcpu)
4946 {
4947         skip_emulated_instruction(vcpu);
4948         kvm_vcpu_on_spin(vcpu);
4949
4950         return 1;
4951 }
4952
4953 static int handle_invalid_op(struct kvm_vcpu *vcpu)
4954 {
4955         kvm_queue_exception(vcpu, UD_VECTOR);
4956         return 1;
4957 }
4958
4959 /*
4960  * To run an L2 guest, we need a vmcs02 based on the L1-specified vmcs12.
4961  * We could reuse a single VMCS for all the L2 guests, but we also want the
4962  * option to allocate a separate vmcs02 for each separate loaded vmcs12 - this
4963  * allows keeping them loaded on the processor, and in the future will allow
4964  * optimizations where prepare_vmcs02 doesn't need to set all the fields on
4965  * every entry if they never change.
4966  * So we keep, in vmx->nested.vmcs02_pool, a cache of size VMCS02_POOL_SIZE
4967  * (>=0) with a vmcs02 for each recently loaded vmcs12s, most recent first.
4968  *
4969  * The following functions allocate and free a vmcs02 in this pool.
4970  */
4971
4972 /* Get a VMCS from the pool to use as vmcs02 for the current vmcs12. */
4973 static struct loaded_vmcs *nested_get_current_vmcs02(struct vcpu_vmx *vmx)
4974 {
4975         struct vmcs02_list *item;
4976         list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
4977                 if (item->vmptr == vmx->nested.current_vmptr) {
4978                         list_move(&item->list, &vmx->nested.vmcs02_pool);
4979                         return &item->vmcs02;
4980                 }
4981
4982         if (vmx->nested.vmcs02_num >= max(VMCS02_POOL_SIZE, 1)) {
4983                 /* Recycle the least recently used VMCS. */
4984                 item = list_entry(vmx->nested.vmcs02_pool.prev,
4985                         struct vmcs02_list, list);
4986                 item->vmptr = vmx->nested.current_vmptr;
4987                 list_move(&item->list, &vmx->nested.vmcs02_pool);
4988                 return &item->vmcs02;
4989         }
4990
4991         /* Create a new VMCS */
4992         item = (struct vmcs02_list *)
4993                 kmalloc(sizeof(struct vmcs02_list), GFP_KERNEL);
4994         if (!item)
4995                 return NULL;
4996         item->vmcs02.vmcs = alloc_vmcs();
4997         if (!item->vmcs02.vmcs) {
4998                 kfree(item);
4999                 return NULL;
5000         }
5001         loaded_vmcs_init(&item->vmcs02);
5002         item->vmptr = vmx->nested.current_vmptr;
5003         list_add(&(item->list), &(vmx->nested.vmcs02_pool));
5004         vmx->nested.vmcs02_num++;
5005         return &item->vmcs02;
5006 }
5007
5008 /* Free and remove from pool a vmcs02 saved for a vmcs12 (if there is one) */
5009 static void nested_free_vmcs02(struct vcpu_vmx *vmx, gpa_t vmptr)
5010 {
5011         struct vmcs02_list *item;
5012         list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
5013                 if (item->vmptr == vmptr) {
5014                         free_loaded_vmcs(&item->vmcs02);
5015                         list_del(&item->list);
5016                         kfree(item);
5017                         vmx->nested.vmcs02_num--;
5018                         return;
5019                 }
5020 }
5021
5022 /*
5023  * Free all VMCSs saved for this vcpu, except the one pointed by
5024  * vmx->loaded_vmcs. These include the VMCSs in vmcs02_pool (except the one
5025  * currently used, if running L2), and vmcs01 when running L2.
5026  */
5027 static void nested_free_all_saved_vmcss(struct vcpu_vmx *vmx)
5028 {
5029         struct vmcs02_list *item, *n;
5030         list_for_each_entry_safe(item, n, &vmx->nested.vmcs02_pool, list) {
5031                 if (vmx->loaded_vmcs != &item->vmcs02)
5032                         free_loaded_vmcs(&item->vmcs02);
5033                 list_del(&item->list);
5034                 kfree(item);
5035         }
5036         vmx->nested.vmcs02_num = 0;
5037
5038         if (vmx->loaded_vmcs != &vmx->vmcs01)
5039                 free_loaded_vmcs(&vmx->vmcs01);
5040 }
5041
5042 /*
5043  * Emulate the VMXON instruction.
5044  * Currently, we just remember that VMX is active, and do not save or even
5045  * inspect the argument to VMXON (the so-called "VMXON pointer") because we
5046  * do not currently need to store anything in that guest-allocated memory
5047  * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
5048  * argument is different from the VMXON pointer (which the spec says they do).
5049  */
5050 static int handle_vmon(struct kvm_vcpu *vcpu)
5051 {
5052         struct kvm_segment cs;
5053         struct vcpu_vmx *vmx = to_vmx(vcpu);
5054
5055         /* The Intel VMX Instruction Reference lists a bunch of bits that
5056          * are prerequisite to running VMXON, most notably cr4.VMXE must be
5057          * set to 1 (see vmx_set_cr4() for when we allow the guest to set this).
5058          * Otherwise, we should fail with #UD. We test these now:
5059          */
5060         if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE) ||
5061             !kvm_read_cr0_bits(vcpu, X86_CR0_PE) ||
5062             (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
5063                 kvm_queue_exception(vcpu, UD_VECTOR);
5064                 return 1;
5065         }
5066
5067         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5068         if (is_long_mode(vcpu) && !cs.l) {
5069                 kvm_queue_exception(vcpu, UD_VECTOR);
5070                 return 1;
5071         }
5072
5073         if (vmx_get_cpl(vcpu)) {
5074                 kvm_inject_gp(vcpu, 0);
5075                 return 1;
5076         }
5077
5078         INIT_LIST_HEAD(&(vmx->nested.vmcs02_pool));
5079         vmx->nested.vmcs02_num = 0;
5080
5081         vmx->nested.vmxon = true;
5082
5083         skip_emulated_instruction(vcpu);
5084         return 1;
5085 }
5086
5087 /*
5088  * Intel's VMX Instruction Reference specifies a common set of prerequisites
5089  * for running VMX instructions (except VMXON, whose prerequisites are
5090  * slightly different). It also specifies what exception to inject otherwise.
5091  */
5092 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
5093 {
5094         struct kvm_segment cs;
5095         struct vcpu_vmx *vmx = to_vmx(vcpu);
5096
5097         if (!vmx->nested.vmxon) {
5098                 kvm_queue_exception(vcpu, UD_VECTOR);
5099                 return 0;
5100         }
5101
5102         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5103         if ((vmx_get_rflags(vcpu) & X86_EFLAGS_VM) ||
5104             (is_long_mode(vcpu) && !cs.l)) {
5105                 kvm_queue_exception(vcpu, UD_VECTOR);
5106                 return 0;
5107         }
5108
5109         if (vmx_get_cpl(vcpu)) {
5110                 kvm_inject_gp(vcpu, 0);
5111                 return 0;
5112         }
5113
5114         return 1;
5115 }
5116
5117 /*
5118  * Free whatever needs to be freed from vmx->nested when L1 goes down, or
5119  * just stops using VMX.
5120  */
5121 static void free_nested(struct vcpu_vmx *vmx)
5122 {
5123         if (!vmx->nested.vmxon)
5124                 return;
5125         vmx->nested.vmxon = false;
5126         if (vmx->nested.current_vmptr != -1ull) {
5127                 kunmap(vmx->nested.current_vmcs12_page);
5128                 nested_release_page(vmx->nested.current_vmcs12_page);
5129                 vmx->nested.current_vmptr = -1ull;
5130                 vmx->nested.current_vmcs12 = NULL;
5131         }
5132         /* Unpin physical memory we referred to in current vmcs02 */
5133         if (vmx->nested.apic_access_page) {
5134                 nested_release_page(vmx->nested.apic_access_page);
5135                 vmx->nested.apic_access_page = 0;
5136         }
5137
5138         nested_free_all_saved_vmcss(vmx);
5139 }
5140
5141 /* Emulate the VMXOFF instruction */
5142 static int handle_vmoff(struct kvm_vcpu *vcpu)
5143 {
5144         if (!nested_vmx_check_permission(vcpu))
5145                 return 1;
5146         free_nested(to_vmx(vcpu));
5147         skip_emulated_instruction(vcpu);
5148         return 1;
5149 }
5150
5151 /*
5152  * Decode the memory-address operand of a vmx instruction, as recorded on an
5153  * exit caused by such an instruction (run by a guest hypervisor).
5154  * On success, returns 0. When the operand is invalid, returns 1 and throws
5155  * #UD or #GP.
5156  */
5157 static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
5158                                  unsigned long exit_qualification,
5159                                  u32 vmx_instruction_info, gva_t *ret)
5160 {
5161         /*
5162          * According to Vol. 3B, "Information for VM Exits Due to Instruction
5163          * Execution", on an exit, vmx_instruction_info holds most of the
5164          * addressing components of the operand. Only the displacement part
5165          * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
5166          * For how an actual address is calculated from all these components,
5167          * refer to Vol. 1, "Operand Addressing".
5168          */
5169         int  scaling = vmx_instruction_info & 3;
5170         int  addr_size = (vmx_instruction_info >> 7) & 7;
5171         bool is_reg = vmx_instruction_info & (1u << 10);
5172         int  seg_reg = (vmx_instruction_info >> 15) & 7;
5173         int  index_reg = (vmx_instruction_info >> 18) & 0xf;
5174         bool index_is_valid = !(vmx_instruction_info & (1u << 22));
5175         int  base_reg       = (vmx_instruction_info >> 23) & 0xf;
5176         bool base_is_valid  = !(vmx_instruction_info & (1u << 27));
5177
5178         if (is_reg) {
5179                 kvm_queue_exception(vcpu, UD_VECTOR);
5180                 return 1;
5181         }
5182
5183         /* Addr = segment_base + offset */
5184         /* offset = base + [index * scale] + displacement */
5185         *ret = vmx_get_segment_base(vcpu, seg_reg);
5186         if (base_is_valid)
5187                 *ret += kvm_register_read(vcpu, base_reg);
5188         if (index_is_valid)
5189                 *ret += kvm_register_read(vcpu, index_reg)<<scaling;
5190         *ret += exit_qualification; /* holds the displacement */
5191
5192         if (addr_size == 1) /* 32 bit */
5193                 *ret &= 0xffffffff;
5194
5195         /*
5196          * TODO: throw #GP (and return 1) in various cases that the VM*
5197          * instructions require it - e.g., offset beyond segment limit,
5198          * unusable or unreadable/unwritable segment, non-canonical 64-bit
5199          * address, and so on. Currently these are not checked.
5200          */
5201         return 0;
5202 }
5203
5204 /*
5205  * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
5206  * set the success or error code of an emulated VMX instruction, as specified
5207  * by Vol 2B, VMX Instruction Reference, "Conventions".
5208  */
5209 static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
5210 {
5211         vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
5212                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
5213                             X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
5214 }
5215
5216 static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
5217 {
5218         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
5219                         & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
5220                             X86_EFLAGS_SF | X86_EFLAGS_OF))
5221                         | X86_EFLAGS_CF);
5222 }
5223
5224 static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
5225                                         u32 vm_instruction_error)
5226 {
5227         if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
5228                 /*
5229                  * failValid writes the error number to the current VMCS, which
5230                  * can't be done there isn't a current VMCS.
5231                  */
5232                 nested_vmx_failInvalid(vcpu);
5233                 return;
5234         }
5235         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
5236                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
5237                             X86_EFLAGS_SF | X86_EFLAGS_OF))
5238                         | X86_EFLAGS_ZF);
5239         get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
5240 }
5241
5242 /* Emulate the VMCLEAR instruction */
5243 static int handle_vmclear(struct kvm_vcpu *vcpu)
5244 {
5245         struct vcpu_vmx *vmx = to_vmx(vcpu);
5246         gva_t gva;
5247         gpa_t vmptr;
5248         struct vmcs12 *vmcs12;
5249         struct page *page;
5250         struct x86_exception e;
5251
5252         if (!nested_vmx_check_permission(vcpu))
5253                 return 1;
5254
5255         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
5256                         vmcs_read32(VMX_INSTRUCTION_INFO), &gva))
5257                 return 1;
5258
5259         if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vmptr,
5260                                 sizeof(vmptr), &e)) {
5261                 kvm_inject_page_fault(vcpu, &e);
5262                 return 1;
5263         }
5264
5265         if (!IS_ALIGNED(vmptr, PAGE_SIZE)) {
5266                 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS);
5267                 skip_emulated_instruction(vcpu);
5268                 return 1;
5269         }
5270
5271         if (vmptr == vmx->nested.current_vmptr) {
5272                 kunmap(vmx->nested.current_vmcs12_page);
5273                 nested_release_page(vmx->nested.current_vmcs12_page);
5274                 vmx->nested.current_vmptr = -1ull;
5275                 vmx->nested.current_vmcs12 = NULL;
5276         }
5277
5278         page = nested_get_page(vcpu, vmptr);
5279         if (page == NULL) {
5280                 /*
5281                  * For accurate processor emulation, VMCLEAR beyond available
5282                  * physical memory should do nothing at all. However, it is
5283                  * possible that a nested vmx bug, not a guest hypervisor bug,
5284                  * resulted in this case, so let's shut down before doing any
5285                  * more damage:
5286                  */
5287                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5288                 return 1;
5289         }
5290         vmcs12 = kmap(page);
5291         vmcs12->launch_state = 0;
5292         kunmap(page);
5293         nested_release_page(page);
5294
5295         nested_free_vmcs02(vmx, vmptr);
5296
5297         skip_emulated_instruction(vcpu);
5298         nested_vmx_succeed(vcpu);
5299         return 1;
5300 }
5301
5302 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
5303
5304 /* Emulate the VMLAUNCH instruction */
5305 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
5306 {
5307         return nested_vmx_run(vcpu, true);
5308 }
5309
5310 /* Emulate the VMRESUME instruction */
5311 static int handle_vmresume(struct kvm_vcpu *vcpu)
5312 {
5313
5314         return nested_vmx_run(vcpu, false);
5315 }
5316
5317 enum vmcs_field_type {
5318         VMCS_FIELD_TYPE_U16 = 0,
5319         VMCS_FIELD_TYPE_U64 = 1,
5320         VMCS_FIELD_TYPE_U32 = 2,
5321         VMCS_FIELD_TYPE_NATURAL_WIDTH = 3
5322 };
5323
5324 static inline int vmcs_field_type(unsigned long field)
5325 {
5326         if (0x1 & field)        /* the *_HIGH fields are all 32 bit */
5327                 return VMCS_FIELD_TYPE_U32;
5328         return (field >> 13) & 0x3 ;
5329 }
5330
5331 static inline int vmcs_field_readonly(unsigned long field)
5332 {
5333         return (((field >> 10) & 0x3) == 1);
5334 }
5335
5336 /*
5337  * Read a vmcs12 field. Since these can have varying lengths and we return
5338  * one type, we chose the biggest type (u64) and zero-extend the return value
5339  * to that size. Note that the caller, handle_vmread, might need to use only
5340  * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
5341  * 64-bit fields are to be returned).
5342  */
5343 static inline bool vmcs12_read_any(struct kvm_vcpu *vcpu,
5344                                         unsigned long field, u64 *ret)
5345 {
5346         short offset = vmcs_field_to_offset(field);
5347         char *p;
5348
5349         if (offset < 0)
5350                 return 0;
5351
5352         p = ((char *)(get_vmcs12(vcpu))) + offset;
5353
5354         switch (vmcs_field_type(field)) {
5355         case VMCS_FIELD_TYPE_NATURAL_WIDTH:
5356                 *ret = *((natural_width *)p);
5357                 return 1;
5358         case VMCS_FIELD_TYPE_U16:
5359                 *ret = *((u16 *)p);
5360                 return 1;
5361         case VMCS_FIELD_TYPE_U32:
5362                 *ret = *((u32 *)p);
5363                 return 1;
5364         case VMCS_FIELD_TYPE_U64:
5365                 *ret = *((u64 *)p);
5366                 return 1;
5367         default:
5368                 return 0; /* can never happen. */
5369         }
5370 }
5371
5372 /*
5373  * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
5374  * used before) all generate the same failure when it is missing.
5375  */
5376 static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
5377 {
5378         struct vcpu_vmx *vmx = to_vmx(vcpu);
5379         if (vmx->nested.current_vmptr == -1ull) {
5380                 nested_vmx_failInvalid(vcpu);
5381                 skip_emulated_instruction(vcpu);
5382                 return 0;
5383         }
5384         return 1;
5385 }
5386
5387 static int handle_vmread(struct kvm_vcpu *vcpu)
5388 {
5389         unsigned long field;
5390         u64 field_value;
5391         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5392         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5393         gva_t gva = 0;
5394
5395         if (!nested_vmx_check_permission(vcpu) ||
5396             !nested_vmx_check_vmcs12(vcpu))
5397                 return 1;
5398
5399         /* Decode instruction info and find the field to read */
5400         field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
5401         /* Read the field, zero-extended to a u64 field_value */
5402         if (!vmcs12_read_any(vcpu, field, &field_value)) {
5403                 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
5404                 skip_emulated_instruction(vcpu);
5405                 return 1;
5406         }
5407         /*
5408          * Now copy part of this value to register or memory, as requested.
5409          * Note that the number of bits actually copied is 32 or 64 depending
5410          * on the guest's mode (32 or 64 bit), not on the given field's length.
5411          */
5412         if (vmx_instruction_info & (1u << 10)) {
5413                 kvm_register_write(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
5414                         field_value);
5415         } else {
5416                 if (get_vmx_mem_address(vcpu, exit_qualification,
5417                                 vmx_instruction_info, &gva))
5418                         return 1;
5419                 /* _system ok, as nested_vmx_check_permission verified cpl=0 */
5420                 kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,
5421                              &field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);
5422         }
5423
5424         nested_vmx_succeed(vcpu);
5425         skip_emulated_instruction(vcpu);
5426         return 1;
5427 }
5428
5429
5430 static int handle_vmwrite(struct kvm_vcpu *vcpu)
5431 {
5432         unsigned long field;
5433         gva_t gva;
5434         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5435         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5436         char *p;
5437         short offset;
5438         /* The value to write might be 32 or 64 bits, depending on L1's long
5439          * mode, and eventually we need to write that into a field of several
5440          * possible lengths. The code below first zero-extends the value to 64
5441          * bit (field_value), and then copies only the approriate number of
5442          * bits into the vmcs12 field.
5443          */
5444         u64 field_value = 0;
5445         struct x86_exception e;
5446
5447         if (!nested_vmx_check_permission(vcpu) ||
5448             !nested_vmx_check_vmcs12(vcpu))
5449                 return 1;
5450
5451         if (vmx_instruction_info & (1u << 10))
5452                 field_value = kvm_register_read(vcpu,
5453                         (((vmx_instruction_info) >> 3) & 0xf));
5454         else {
5455                 if (get_vmx_mem_address(vcpu, exit_qualification,
5456                                 vmx_instruction_info, &gva))
5457                         return 1;
5458                 if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva,
5459                            &field_value, (is_long_mode(vcpu) ? 8 : 4), &e)) {
5460                         kvm_inject_page_fault(vcpu, &e);
5461                         return 1;
5462                 }
5463         }
5464
5465
5466         field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
5467         if (vmcs_field_readonly(field)) {
5468                 nested_vmx_failValid(vcpu,
5469                         VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
5470                 skip_emulated_instruction(vcpu);
5471                 return 1;
5472         }
5473
5474         offset = vmcs_field_to_offset(field);
5475         if (offset < 0) {
5476                 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
5477                 skip_emulated_instruction(vcpu);
5478                 return 1;
5479         }
5480         p = ((char *) get_vmcs12(vcpu)) + offset;
5481
5482         switch (vmcs_field_type(field)) {
5483         case VMCS_FIELD_TYPE_U16:
5484                 *(u16 *)p = field_value;
5485                 break;
5486         case VMCS_FIELD_TYPE_U32:
5487                 *(u32 *)p = field_value;
5488                 break;
5489         case VMCS_FIELD_TYPE_U64:
5490                 *(u64 *)p = field_value;
5491                 break;
5492         case VMCS_FIELD_TYPE_NATURAL_WIDTH:
5493                 *(natural_width *)p = field_value;
5494                 break;
5495         default:
5496                 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
5497                 skip_emulated_instruction(vcpu);
5498                 return 1;
5499         }
5500
5501         nested_vmx_succeed(vcpu);
5502         skip_emulated_instruction(vcpu);
5503         return 1;
5504 }
5505
5506 /* Emulate the VMPTRLD instruction */
5507 static int handle_vmptrld(struct kvm_vcpu *vcpu)
5508 {
5509         struct vcpu_vmx *vmx = to_vmx(vcpu);
5510         gva_t gva;
5511         gpa_t vmptr;
5512         struct x86_exception e;
5513
5514         if (!nested_vmx_check_permission(vcpu))
5515                 return 1;
5516
5517         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
5518                         vmcs_read32(VMX_INSTRUCTION_INFO), &gva))
5519                 return 1;
5520
5521         if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vmptr,
5522                                 sizeof(vmptr), &e)) {
5523                 kvm_inject_page_fault(vcpu, &e);
5524                 return 1;
5525         }
5526
5527         if (!IS_ALIGNED(vmptr, PAGE_SIZE)) {
5528                 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS);
5529                 skip_emulated_instruction(vcpu);
5530                 return 1;
5531         }
5532
5533         if (vmx->nested.current_vmptr != vmptr) {
5534                 struct vmcs12 *new_vmcs12;
5535                 struct page *page;
5536                 page = nested_get_page(vcpu, vmptr);
5537                 if (page == NULL) {
5538                         nested_vmx_failInvalid(vcpu);
5539                         skip_emulated_instruction(vcpu);
5540                         return 1;
5541                 }
5542                 new_vmcs12 = kmap(page);
5543                 if (new_vmcs12->revision_id != VMCS12_REVISION) {
5544                         kunmap(page);
5545                         nested_release_page_clean(page);
5546                         nested_vmx_failValid(vcpu,
5547                                 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
5548                         skip_emulated_instruction(vcpu);
5549                         return 1;
5550                 }
5551                 if (vmx->nested.current_vmptr != -1ull) {
5552                         kunmap(vmx->nested.current_vmcs12_page);
5553                         nested_release_page(vmx->nested.current_vmcs12_page);
5554                 }
5555
5556                 vmx->nested.current_vmptr = vmptr;
5557                 vmx->nested.current_vmcs12 = new_vmcs12;
5558                 vmx->nested.current_vmcs12_page = page;
5559         }
5560
5561         nested_vmx_succeed(vcpu);
5562         skip_emulated_instruction(vcpu);
5563         return 1;
5564 }
5565
5566 /* Emulate the VMPTRST instruction */
5567 static int handle_vmptrst(struct kvm_vcpu *vcpu)
5568 {
5569         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5570         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5571         gva_t vmcs_gva;
5572         struct x86_exception e;
5573
5574         if (!nested_vmx_check_permission(vcpu))
5575                 return 1;
5576
5577         if (get_vmx_mem_address(vcpu, exit_qualification,
5578                         vmx_instruction_info, &vmcs_gva))
5579                 return 1;
5580         /* ok to use *_system, as nested_vmx_check_permission verified cpl=0 */
5581         if (kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, vmcs_gva,
5582                                  (void *)&to_vmx(vcpu)->nested.current_vmptr,
5583                                  sizeof(u64), &e)) {
5584                 kvm_inject_page_fault(vcpu, &e);
5585                 return 1;
5586         }
5587         nested_vmx_succeed(vcpu);
5588         skip_emulated_instruction(vcpu);
5589         return 1;
5590 }
5591
5592 /*
5593  * The exit handlers return 1 if the exit was handled fully and guest execution
5594  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
5595  * to be done to userspace and return 0.
5596  */
5597 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5598         [EXIT_REASON_EXCEPTION_NMI]           = handle_exception,
5599         [EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
5600         [EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
5601         [EXIT_REASON_NMI_WINDOW]              = handle_nmi_window,
5602         [EXIT_REASON_IO_INSTRUCTION]          = handle_io,
5603         [EXIT_REASON_CR_ACCESS]               = handle_cr,
5604         [EXIT_REASON_DR_ACCESS]               = handle_dr,
5605         [EXIT_REASON_CPUID]                   = handle_cpuid,
5606         [EXIT_REASON_MSR_READ]                = handle_rdmsr,
5607         [EXIT_REASON_MSR_WRITE]               = handle_wrmsr,
5608         [EXIT_REASON_PENDING_INTERRUPT]       = handle_interrupt_window,
5609         [EXIT_REASON_HLT]                     = handle_halt,
5610         [EXIT_REASON_INVD]                    = handle_invd,
5611         [EXIT_REASON_INVLPG]                  = handle_invlpg,
5612         [EXIT_REASON_RDPMC]                   = handle_rdpmc,
5613         [EXIT_REASON_VMCALL]                  = handle_vmcall,
5614         [EXIT_REASON_VMCLEAR]                 = handle_vmclear,
5615         [EXIT_REASON_VMLAUNCH]                = handle_vmlaunch,
5616         [EXIT_REASON_VMPTRLD]                 = handle_vmptrld,
5617         [EXIT_REASON_VMPTRST]                 = handle_vmptrst,
5618         [EXIT_REASON_VMREAD]                  = handle_vmread,
5619         [EXIT_REASON_VMRESUME]                = handle_vmresume,
5620         [EXIT_REASON_VMWRITE]                 = handle_vmwrite,
5621         [EXIT_REASON_VMOFF]                   = handle_vmoff,
5622         [EXIT_REASON_VMON]                    = handle_vmon,
5623         [EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
5624         [EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
5625         [EXIT_REASON_WBINVD]                  = handle_wbinvd,
5626         [EXIT_REASON_XSETBV]                  = handle_xsetbv,
5627         [EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
5628         [EXIT_REASON_MCE_DURING_VMENTRY]      = handle_machine_check,
5629         [EXIT_REASON_EPT_VIOLATION]           = handle_ept_violation,
5630         [EXIT_REASON_EPT_MISCONFIG]           = handle_ept_misconfig,
5631         [EXIT_REASON_PAUSE_INSTRUCTION]       = handle_pause,
5632         [EXIT_REASON_MWAIT_INSTRUCTION]       = handle_invalid_op,
5633         [EXIT_REASON_MONITOR_INSTRUCTION]     = handle_invalid_op,
5634 };
5635
5636 static const int kvm_vmx_max_exit_handlers =
5637         ARRAY_SIZE(kvm_vmx_exit_handlers);
5638
5639 /*
5640  * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
5641  * rather than handle it ourselves in L0. I.e., check whether L1 expressed
5642  * disinterest in the current event (read or write a specific MSR) by using an
5643  * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
5644  */
5645 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
5646         struct vmcs12 *vmcs12, u32 exit_reason)
5647 {
5648         u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
5649         gpa_t bitmap;
5650
5651         if (!nested_cpu_has(get_vmcs12(vcpu), CPU_BASED_USE_MSR_BITMAPS))
5652                 return 1;
5653
5654         /*
5655          * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
5656          * for the four combinations of read/write and low/high MSR numbers.
5657          * First we need to figure out which of the four to use:
5658          */
5659         bitmap = vmcs12->msr_bitmap;
5660         if (exit_reason == EXIT_REASON_MSR_WRITE)
5661                 bitmap += 2048;
5662         if (msr_index >= 0xc0000000) {
5663                 msr_index -= 0xc0000000;
5664                 bitmap += 1024;
5665         }
5666
5667         /* Then read the msr_index'th bit from this bitmap: */
5668         if (msr_index < 1024*8) {
5669                 unsigned char b;
5670                 kvm_read_guest(vcpu->kvm, bitmap + msr_index/8, &b, 1);
5671                 return 1 & (b >> (msr_index & 7));
5672         } else
5673                 return 1; /* let L1 handle the wrong parameter */
5674 }
5675
5676 /*
5677  * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
5678  * rather than handle it ourselves in L0. I.e., check if L1 wanted to
5679  * intercept (via guest_host_mask etc.) the current event.
5680  */
5681 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
5682         struct vmcs12 *vmcs12)
5683 {
5684         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5685         int cr = exit_qualification & 15;
5686         int reg = (exit_qualification >> 8) & 15;
5687         unsigned long val = kvm_register_read(vcpu, reg);
5688
5689         switch ((exit_qualification >> 4) & 3) {
5690         case 0: /* mov to cr */
5691                 switch (cr) {
5692                 case 0:
5693                         if (vmcs12->cr0_guest_host_mask &
5694                             (val ^ vmcs12->cr0_read_shadow))
5695                                 return 1;
5696                         break;
5697                 case 3:
5698                         if ((vmcs12->cr3_target_count >= 1 &&
5699                                         vmcs12->cr3_target_value0 == val) ||
5700                                 (vmcs12->cr3_target_count >= 2 &&
5701                                         vmcs12->cr3_target_value1 == val) ||
5702                                 (vmcs12->cr3_target_count >= 3 &&
5703                                         vmcs12->cr3_target_value2 == val) ||
5704                                 (vmcs12->cr3_target_count >= 4 &&
5705                                         vmcs12->cr3_target_value3 == val))
5706                                 return 0;
5707                         if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
5708                                 return 1;
5709                         break;
5710                 case 4:
5711                         if (vmcs12->cr4_guest_host_mask &
5712                             (vmcs12->cr4_read_shadow ^ val))
5713                                 return 1;
5714                         break;
5715                 case 8:
5716                         if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
5717                                 return 1;
5718                         break;
5719                 }
5720                 break;
5721         case 2: /* clts */
5722                 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
5723                     (vmcs12->cr0_read_shadow & X86_CR0_TS))
5724                         return 1;
5725                 break;
5726         case 1: /* mov from cr */
5727                 switch (cr) {
5728                 case 3:
5729                         if (vmcs12->cpu_based_vm_exec_control &
5730                             CPU_BASED_CR3_STORE_EXITING)
5731                                 return 1;
5732                         break;
5733                 case 8:
5734                         if (vmcs12->cpu_based_vm_exec_control &
5735                             CPU_BASED_CR8_STORE_EXITING)
5736                                 return 1;
5737                         break;
5738                 }
5739                 break;
5740         case 3: /* lmsw */
5741                 /*
5742                  * lmsw can change bits 1..3 of cr0, and only set bit 0 of
5743                  * cr0. Other attempted changes are ignored, with no exit.
5744                  */
5745                 if (vmcs12->cr0_guest_host_mask & 0xe &
5746                     (val ^ vmcs12->cr0_read_shadow))
5747                         return 1;
5748                 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
5749                     !(vmcs12->cr0_read_shadow & 0x1) &&
5750                     (val & 0x1))
5751                         return 1;
5752                 break;
5753         }
5754         return 0;
5755 }
5756
5757 /*
5758  * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
5759  * should handle it ourselves in L0 (and then continue L2). Only call this
5760  * when in is_guest_mode (L2).
5761  */
5762 static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu)
5763 {
5764         u32 exit_reason = vmcs_read32(VM_EXIT_REASON);
5765         u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
5766         struct vcpu_vmx *vmx = to_vmx(vcpu);
5767         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5768
5769         if (vmx->nested.nested_run_pending)
5770                 return 0;
5771
5772         if (unlikely(vmx->fail)) {
5773                 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
5774                                     vmcs_read32(VM_INSTRUCTION_ERROR));
5775                 return 1;
5776         }
5777
5778         switch (exit_reason) {
5779         case EXIT_REASON_EXCEPTION_NMI:
5780                 if (!is_exception(intr_info))
5781                         return 0;
5782                 else if (is_page_fault(intr_info))
5783                         return enable_ept;
5784                 return vmcs12->exception_bitmap &
5785                                 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
5786         case EXIT_REASON_EXTERNAL_INTERRUPT:
5787                 return 0;
5788         case EXIT_REASON_TRIPLE_FAULT:
5789                 return 1;
5790         case EXIT_REASON_PENDING_INTERRUPT:
5791         case EXIT_REASON_NMI_WINDOW:
5792                 /*
5793                  * prepare_vmcs02() set the CPU_BASED_VIRTUAL_INTR_PENDING bit
5794                  * (aka Interrupt Window Exiting) only when L1 turned it on,
5795                  * so if we got a PENDING_INTERRUPT exit, this must be for L1.
5796                  * Same for NMI Window Exiting.
5797                  */
5798                 return 1;
5799         case EXIT_REASON_TASK_SWITCH:
5800                 return 1;
5801         case EXIT_REASON_CPUID:
5802                 return 1;
5803         case EXIT_REASON_HLT:
5804                 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
5805         case EXIT_REASON_INVD:
5806                 return 1;
5807         case EXIT_REASON_INVLPG:
5808                 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
5809         case EXIT_REASON_RDPMC:
5810                 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
5811         case EXIT_REASON_RDTSC:
5812                 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
5813         case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
5814         case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
5815         case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
5816         case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
5817         case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
5818                 /*
5819                  * VMX instructions trap unconditionally. This allows L1 to
5820                  * emulate them for its L2 guest, i.e., allows 3-level nesting!
5821                  */
5822                 return 1;
5823         case EXIT_REASON_CR_ACCESS:
5824                 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
5825         case EXIT_REASON_DR_ACCESS:
5826                 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
5827         case EXIT_REASON_IO_INSTRUCTION:
5828                 /* TODO: support IO bitmaps */
5829                 return 1;
5830         case EXIT_REASON_MSR_READ:
5831         case EXIT_REASON_MSR_WRITE:
5832                 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
5833         case EXIT_REASON_INVALID_STATE:
5834                 return 1;
5835         case EXIT_REASON_MWAIT_INSTRUCTION:
5836                 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
5837         case EXIT_REASON_MONITOR_INSTRUCTION:
5838                 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
5839         case EXIT_REASON_PAUSE_INSTRUCTION:
5840                 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
5841                         nested_cpu_has2(vmcs12,
5842                                 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
5843         case EXIT_REASON_MCE_DURING_VMENTRY:
5844                 return 0;
5845         case EXIT_REASON_TPR_BELOW_THRESHOLD:
5846                 return 1;
5847         case EXIT_REASON_APIC_ACCESS:
5848                 return nested_cpu_has2(vmcs12,
5849                         SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
5850         case EXIT_REASON_EPT_VIOLATION:
5851         case EXIT_REASON_EPT_MISCONFIG:
5852                 return 0;
5853         case EXIT_REASON_WBINVD:
5854                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
5855         case EXIT_REASON_XSETBV:
5856                 return 1;
5857         default:
5858                 return 1;
5859         }
5860 }
5861
5862 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
5863 {
5864         *info1 = vmcs_readl(EXIT_QUALIFICATION);
5865         *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
5866 }
5867
5868 /*
5869  * The guest has exited.  See if we can fix it or if we need userspace
5870  * assistance.
5871  */
5872 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
5873 {
5874         struct vcpu_vmx *vmx = to_vmx(vcpu);
5875         u32 exit_reason = vmx->exit_reason;
5876         u32 vectoring_info = vmx->idt_vectoring_info;
5877
5878         /* If guest state is invalid, start emulating */
5879         if (vmx->emulation_required && emulate_invalid_guest_state)
5880                 return handle_invalid_guest_state(vcpu);
5881
5882         /*
5883          * the KVM_REQ_EVENT optimization bit is only on for one entry, and if
5884          * we did not inject a still-pending event to L1 now because of
5885          * nested_run_pending, we need to re-enable this bit.
5886          */
5887         if (vmx->nested.nested_run_pending)
5888                 kvm_make_request(KVM_REQ_EVENT, vcpu);
5889
5890         if (!is_guest_mode(vcpu) && (exit_reason == EXIT_REASON_VMLAUNCH ||
5891             exit_reason == EXIT_REASON_VMRESUME))
5892                 vmx->nested.nested_run_pending = 1;
5893         else
5894                 vmx->nested.nested_run_pending = 0;
5895
5896         if (is_guest_mode(vcpu) && nested_vmx_exit_handled(vcpu)) {
5897                 nested_vmx_vmexit(vcpu);
5898                 return 1;
5899         }
5900
5901         if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
5902                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5903                 vcpu->run->fail_entry.hardware_entry_failure_reason
5904                         = exit_reason;
5905                 return 0;
5906         }
5907
5908         if (unlikely(vmx->fail)) {
5909                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5910                 vcpu->run->fail_entry.hardware_entry_failure_reason
5911                         = vmcs_read32(VM_INSTRUCTION_ERROR);
5912                 return 0;
5913         }
5914
5915         if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
5916                         (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
5917                         exit_reason != EXIT_REASON_EPT_VIOLATION &&
5918                         exit_reason != EXIT_REASON_TASK_SWITCH))
5919                 printk(KERN_WARNING "%s: unexpected, valid vectoring info "
5920                        "(0x%x) and exit reason is 0x%x\n",
5921                        __func__, vectoring_info, exit_reason);
5922
5923         if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked &&
5924             !(is_guest_mode(vcpu) && nested_cpu_has_virtual_nmis(
5925                                         get_vmcs12(vcpu), vcpu)))) {
5926                 if (vmx_interrupt_allowed(vcpu)) {
5927                         vmx->soft_vnmi_blocked = 0;
5928                 } else if (vmx->vnmi_blocked_time > 1000000000LL &&
5929                            vcpu->arch.nmi_pending) {
5930                         /*
5931                          * This CPU don't support us in finding the end of an
5932                          * NMI-blocked window if the guest runs with IRQs
5933                          * disabled. So we pull the trigger after 1 s of
5934                          * futile waiting, but inform the user about this.
5935                          */
5936                         printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
5937                                "state on VCPU %d after 1 s timeout\n",
5938                                __func__, vcpu->vcpu_id);
5939                         vmx->soft_vnmi_blocked = 0;
5940                 }
5941         }
5942
5943         if (exit_reason < kvm_vmx_max_exit_handlers
5944             && kvm_vmx_exit_handlers[exit_reason])
5945                 return kvm_vmx_exit_handlers[exit_reason](vcpu);
5946         else {
5947                 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
5948                 vcpu->run->hw.hardware_exit_reason = exit_reason;
5949         }
5950         return 0;
5951 }
5952
5953 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
5954 {
5955         if (irr == -1 || tpr < irr) {
5956                 vmcs_write32(TPR_THRESHOLD, 0);
5957                 return;
5958         }
5959
5960         vmcs_write32(TPR_THRESHOLD, irr);
5961 }
5962
5963 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
5964 {
5965         u32 exit_intr_info;
5966
5967         if (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
5968               || vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI))
5969                 return;
5970
5971         vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
5972         exit_intr_info = vmx->exit_intr_info;
5973
5974         /* Handle machine checks before interrupts are enabled */
5975         if (is_machine_check(exit_intr_info))
5976                 kvm_machine_check();
5977
5978         /* We need to handle NMIs before interrupts are enabled */
5979         if ((exit_intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR &&
5980             (exit_intr_info & INTR_INFO_VALID_MASK)) {
5981                 kvm_before_handle_nmi(&vmx->vcpu);
5982                 asm("int $2");
5983                 kvm_after_handle_nmi(&vmx->vcpu);
5984         }
5985 }
5986
5987 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
5988 {
5989         u32 exit_intr_info;
5990         bool unblock_nmi;
5991         u8 vector;
5992         bool idtv_info_valid;
5993
5994         idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
5995
5996         if (cpu_has_virtual_nmis()) {
5997                 if (vmx->nmi_known_unmasked)
5998                         return;
5999                 /*
6000                  * Can't use vmx->exit_intr_info since we're not sure what
6001                  * the exit reason is.
6002                  */
6003                 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6004                 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6005                 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6006                 /*
6007                  * SDM 3: 27.7.1.2 (September 2008)
6008                  * Re-set bit "block by NMI" before VM entry if vmexit caused by
6009                  * a guest IRET fault.
6010                  * SDM 3: 23.2.2 (September 2008)
6011                  * Bit 12 is undefined in any of the following cases:
6012                  *  If the VM exit sets the valid bit in the IDT-vectoring
6013                  *   information field.
6014                  *  If the VM exit is due to a double fault.
6015                  */
6016                 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6017                     vector != DF_VECTOR && !idtv_info_valid)
6018                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6019                                       GUEST_INTR_STATE_NMI);
6020                 else
6021                         vmx->nmi_known_unmasked =
6022                                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6023                                   & GUEST_INTR_STATE_NMI);
6024         } else if (unlikely(vmx->soft_vnmi_blocked))
6025                 vmx->vnmi_blocked_time +=
6026                         ktime_to_ns(ktime_sub(ktime_get(), vmx->entry_time));
6027 }
6028
6029 static void __vmx_complete_interrupts(struct vcpu_vmx *vmx,
6030                                       u32 idt_vectoring_info,
6031                                       int instr_len_field,
6032                                       int error_code_field)
6033 {
6034         u8 vector;
6035         int type;
6036         bool idtv_info_valid;
6037
6038         idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6039
6040         vmx->vcpu.arch.nmi_injected = false;
6041         kvm_clear_exception_queue(&vmx->vcpu);
6042         kvm_clear_interrupt_queue(&vmx->vcpu);
6043
6044         if (!idtv_info_valid)
6045                 return;
6046
6047         kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
6048
6049         vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6050         type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6051
6052         switch (type) {
6053         case INTR_TYPE_NMI_INTR:
6054                 vmx->vcpu.arch.nmi_injected = true;
6055                 /*
6056                  * SDM 3: 27.7.1.2 (September 2008)
6057                  * Clear bit "block by NMI" before VM entry if a NMI
6058                  * delivery faulted.
6059                  */
6060                 vmx_set_nmi_mask(&vmx->vcpu, false);
6061                 break;
6062         case INTR_TYPE_SOFT_EXCEPTION:
6063                 vmx->vcpu.arch.event_exit_inst_len =
6064                         vmcs_read32(instr_len_field);
6065                 /* fall through */
6066         case INTR_TYPE_HARD_EXCEPTION:
6067                 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6068                         u32 err = vmcs_read32(error_code_field);
6069                         kvm_queue_exception_e(&vmx->vcpu, vector, err);
6070                 } else
6071                         kvm_queue_exception(&vmx->vcpu, vector);
6072                 break;
6073         case INTR_TYPE_SOFT_INTR:
6074                 vmx->vcpu.arch.event_exit_inst_len =
6075                         vmcs_read32(instr_len_field);
6076                 /* fall through */
6077         case INTR_TYPE_EXT_INTR:
6078                 kvm_queue_interrupt(&vmx->vcpu, vector,
6079                         type == INTR_TYPE_SOFT_INTR);
6080                 break;
6081         default:
6082                 break;
6083         }
6084 }
6085
6086 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6087 {
6088         if (is_guest_mode(&vmx->vcpu))
6089                 return;
6090         __vmx_complete_interrupts(vmx, vmx->idt_vectoring_info,
6091                                   VM_EXIT_INSTRUCTION_LEN,
6092                                   IDT_VECTORING_ERROR_CODE);
6093 }
6094
6095 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6096 {
6097         if (is_guest_mode(vcpu))
6098                 return;
6099         __vmx_complete_interrupts(to_vmx(vcpu),
6100                                   vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6101                                   VM_ENTRY_INSTRUCTION_LEN,
6102                                   VM_ENTRY_EXCEPTION_ERROR_CODE);
6103
6104         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6105 }
6106
6107 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6108 {
6109         int i, nr_msrs;
6110         struct perf_guest_switch_msr *msrs;
6111
6112         msrs = perf_guest_get_msrs(&nr_msrs);
6113
6114         if (!msrs)
6115                 return;
6116
6117         for (i = 0; i < nr_msrs; i++)
6118                 if (msrs[i].host == msrs[i].guest)
6119                         clear_atomic_switch_msr(vmx, msrs[i].msr);
6120                 else
6121                         add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6122                                         msrs[i].host);
6123 }
6124
6125 #ifdef CONFIG_X86_64
6126 #define R "r"
6127 #define Q "q"
6128 #else
6129 #define R "e"
6130 #define Q "l"
6131 #endif
6132
6133 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
6134 {
6135         struct vcpu_vmx *vmx = to_vmx(vcpu);
6136
6137         if (is_guest_mode(vcpu) && !vmx->nested.nested_run_pending) {
6138                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6139                 if (vmcs12->idt_vectoring_info_field &
6140                                 VECTORING_INFO_VALID_MASK) {
6141                         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
6142                                 vmcs12->idt_vectoring_info_field);
6143                         vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
6144                                 vmcs12->vm_exit_instruction_len);
6145                         if (vmcs12->idt_vectoring_info_field &
6146                                         VECTORING_INFO_DELIVER_CODE_MASK)
6147                                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
6148                                         vmcs12->idt_vectoring_error_code);
6149                 }
6150         }
6151
6152         /* Record the guest's net vcpu time for enforced NMI injections. */
6153         if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked))
6154                 vmx->entry_time = ktime_get();
6155
6156         /* Don't enter VMX if guest state is invalid, let the exit handler
6157            start emulation until we arrive back to a valid state */
6158         if (vmx->emulation_required && emulate_invalid_guest_state)
6159                 return;
6160
6161         if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
6162                 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6163         if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
6164                 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6165
6166         /* When single-stepping over STI and MOV SS, we must clear the
6167          * corresponding interruptibility bits in the guest state. Otherwise
6168          * vmentry fails as it then expects bit 14 (BS) in pending debug
6169          * exceptions being set, but that's not correct for the guest debugging
6170          * case. */
6171         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6172                 vmx_set_interrupt_shadow(vcpu, 0);
6173
6174         atomic_switch_perf_msrs(vmx);
6175
6176         vmx->__launched = vmx->loaded_vmcs->launched;
6177         asm(
6178                 /* Store host registers */
6179                 "push %%"R"dx; push %%"R"bp;"
6180                 "push %%"R"cx \n\t" /* placeholder for guest rcx */
6181                 "push %%"R"cx \n\t"
6182                 "cmp %%"R"sp, %c[host_rsp](%0) \n\t"
6183                 "je 1f \n\t"
6184                 "mov %%"R"sp, %c[host_rsp](%0) \n\t"
6185                 __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
6186                 "1: \n\t"
6187                 /* Reload cr2 if changed */
6188                 "mov %c[cr2](%0), %%"R"ax \n\t"
6189                 "mov %%cr2, %%"R"dx \n\t"
6190                 "cmp %%"R"ax, %%"R"dx \n\t"
6191                 "je 2f \n\t"
6192                 "mov %%"R"ax, %%cr2 \n\t"
6193                 "2: \n\t"
6194                 /* Check if vmlaunch of vmresume is needed */
6195                 "cmpl $0, %c[launched](%0) \n\t"
6196                 /* Load guest registers.  Don't clobber flags. */
6197                 "mov %c[rax](%0), %%"R"ax \n\t"
6198                 "mov %c[rbx](%0), %%"R"bx \n\t"
6199                 "mov %c[rdx](%0), %%"R"dx \n\t"
6200                 "mov %c[rsi](%0), %%"R"si \n\t"
6201                 "mov %c[rdi](%0), %%"R"di \n\t"
6202                 "mov %c[rbp](%0), %%"R"bp \n\t"
6203 #ifdef CONFIG_X86_64
6204                 "mov %c[r8](%0),  %%r8  \n\t"
6205                 "mov %c[r9](%0),  %%r9  \n\t"
6206                 "mov %c[r10](%0), %%r10 \n\t"
6207                 "mov %c[r11](%0), %%r11 \n\t"
6208                 "mov %c[r12](%0), %%r12 \n\t"
6209                 "mov %c[r13](%0), %%r13 \n\t"
6210                 "mov %c[r14](%0), %%r14 \n\t"
6211                 "mov %c[r15](%0), %%r15 \n\t"
6212 #endif
6213                 "mov %c[rcx](%0), %%"R"cx \n\t" /* kills %0 (ecx) */
6214
6215                 /* Enter guest mode */
6216                 "jne .Llaunched \n\t"
6217                 __ex(ASM_VMX_VMLAUNCH) "\n\t"
6218                 "jmp .Lkvm_vmx_return \n\t"
6219                 ".Llaunched: " __ex(ASM_VMX_VMRESUME) "\n\t"
6220                 ".Lkvm_vmx_return: "
6221                 /* Save guest registers, load host registers, keep flags */
6222                 "mov %0, %c[wordsize](%%"R"sp) \n\t"
6223                 "pop %0 \n\t"
6224                 "mov %%"R"ax, %c[rax](%0) \n\t"
6225                 "mov %%"R"bx, %c[rbx](%0) \n\t"
6226                 "pop"Q" %c[rcx](%0) \n\t"
6227                 "mov %%"R"dx, %c[rdx](%0) \n\t"
6228                 "mov %%"R"si, %c[rsi](%0) \n\t"
6229                 "mov %%"R"di, %c[rdi](%0) \n\t"
6230                 "mov %%"R"bp, %c[rbp](%0) \n\t"
6231 #ifdef CONFIG_X86_64
6232                 "mov %%r8,  %c[r8](%0) \n\t"
6233                 "mov %%r9,  %c[r9](%0) \n\t"
6234                 "mov %%r10, %c[r10](%0) \n\t"
6235                 "mov %%r11, %c[r11](%0) \n\t"
6236                 "mov %%r12, %c[r12](%0) \n\t"
6237                 "mov %%r13, %c[r13](%0) \n\t"
6238                 "mov %%r14, %c[r14](%0) \n\t"
6239                 "mov %%r15, %c[r15](%0) \n\t"
6240 #endif
6241                 "mov %%cr2, %%"R"ax   \n\t"
6242                 "mov %%"R"ax, %c[cr2](%0) \n\t"
6243
6244                 "pop  %%"R"bp; pop  %%"R"dx \n\t"
6245                 "setbe %c[fail](%0) \n\t"
6246               : : "c"(vmx), "d"((unsigned long)HOST_RSP),
6247                 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
6248                 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
6249                 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
6250                 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
6251                 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
6252                 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
6253                 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
6254                 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
6255                 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
6256                 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
6257 #ifdef CONFIG_X86_64
6258                 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
6259                 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
6260                 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
6261                 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
6262                 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
6263                 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
6264                 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
6265                 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
6266 #endif
6267                 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
6268                 [wordsize]"i"(sizeof(ulong))
6269               : "cc", "memory"
6270                 , R"ax", R"bx", R"di", R"si"
6271 #ifdef CONFIG_X86_64
6272                 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
6273 #endif
6274               );
6275
6276         vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
6277                                   | (1 << VCPU_EXREG_RFLAGS)
6278                                   | (1 << VCPU_EXREG_CPL)
6279                                   | (1 << VCPU_EXREG_PDPTR)
6280                                   | (1 << VCPU_EXREG_SEGMENTS)
6281                                   | (1 << VCPU_EXREG_CR3));
6282         vcpu->arch.regs_dirty = 0;
6283
6284         vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
6285
6286         if (is_guest_mode(vcpu)) {
6287                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6288                 vmcs12->idt_vectoring_info_field = vmx->idt_vectoring_info;
6289                 if (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK) {
6290                         vmcs12->idt_vectoring_error_code =
6291                                 vmcs_read32(IDT_VECTORING_ERROR_CODE);
6292                         vmcs12->vm_exit_instruction_len =
6293                                 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6294                 }
6295         }
6296
6297         vmx->loaded_vmcs->launched = 1;
6298
6299         vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
6300         trace_kvm_exit(vmx->exit_reason, vcpu, KVM_ISA_VMX);
6301
6302         vmx_complete_atomic_exit(vmx);
6303         vmx_recover_nmi_blocking(vmx);
6304         vmx_complete_interrupts(vmx);
6305 }
6306
6307 #undef R
6308 #undef Q
6309
6310 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
6311 {
6312         struct vcpu_vmx *vmx = to_vmx(vcpu);
6313
6314         free_vpid(vmx);
6315         free_nested(vmx);
6316         free_loaded_vmcs(vmx->loaded_vmcs);
6317         kfree(vmx->guest_msrs);
6318         kvm_vcpu_uninit(vcpu);
6319         kmem_cache_free(kvm_vcpu_cache, vmx);
6320 }
6321
6322 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
6323 {
6324         int err;
6325         struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
6326         int cpu;
6327
6328         if (!vmx)
6329                 return ERR_PTR(-ENOMEM);
6330
6331         allocate_vpid(vmx);
6332
6333         err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
6334         if (err)
6335                 goto free_vcpu;
6336
6337         vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
6338         err = -ENOMEM;
6339         if (!vmx->guest_msrs) {
6340                 goto uninit_vcpu;
6341         }
6342
6343         vmx->loaded_vmcs = &vmx->vmcs01;
6344         vmx->loaded_vmcs->vmcs = alloc_vmcs();
6345         if (!vmx->loaded_vmcs->vmcs)
6346                 goto free_msrs;
6347         if (!vmm_exclusive)
6348                 kvm_cpu_vmxon(__pa(per_cpu(vmxarea, raw_smp_processor_id())));
6349         loaded_vmcs_init(vmx->loaded_vmcs);
6350         if (!vmm_exclusive)
6351                 kvm_cpu_vmxoff();
6352
6353         cpu = get_cpu();
6354         vmx_vcpu_load(&vmx->vcpu, cpu);
6355         vmx->vcpu.cpu = cpu;
6356         err = vmx_vcpu_setup(vmx);
6357         vmx_vcpu_put(&vmx->vcpu);
6358         put_cpu();
6359         if (err)
6360                 goto free_vmcs;
6361         if (vm_need_virtualize_apic_accesses(kvm))
6362                 err = alloc_apic_access_page(kvm);
6363                 if (err)
6364                         goto free_vmcs;
6365
6366         if (enable_ept) {
6367                 if (!kvm->arch.ept_identity_map_addr)
6368                         kvm->arch.ept_identity_map_addr =
6369                                 VMX_EPT_IDENTITY_PAGETABLE_ADDR;
6370                 err = -ENOMEM;
6371                 if (alloc_identity_pagetable(kvm) != 0)
6372                         goto free_vmcs;
6373                 if (!init_rmode_identity_map(kvm))
6374                         goto free_vmcs;
6375         }
6376
6377         vmx->nested.current_vmptr = -1ull;
6378         vmx->nested.current_vmcs12 = NULL;
6379
6380         return &vmx->vcpu;
6381
6382 free_vmcs:
6383         free_loaded_vmcs(vmx->loaded_vmcs);
6384 free_msrs:
6385         kfree(vmx->guest_msrs);
6386 uninit_vcpu:
6387         kvm_vcpu_uninit(&vmx->vcpu);
6388 free_vcpu:
6389         free_vpid(vmx);
6390         kmem_cache_free(kvm_vcpu_cache, vmx);
6391         return ERR_PTR(err);
6392 }
6393
6394 static void __init vmx_check_processor_compat(void *rtn)
6395 {
6396         struct vmcs_config vmcs_conf;
6397
6398         *(int *)rtn = 0;
6399         if (setup_vmcs_config(&vmcs_conf) < 0)
6400                 *(int *)rtn = -EIO;
6401         if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
6402                 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
6403                                 smp_processor_id());
6404                 *(int *)rtn = -EIO;
6405         }
6406 }
6407
6408 static int get_ept_level(void)
6409 {
6410         return VMX_EPT_DEFAULT_GAW + 1;
6411 }
6412
6413 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
6414 {
6415         u64 ret;
6416
6417         /* For VT-d and EPT combination
6418          * 1. MMIO: always map as UC
6419          * 2. EPT with VT-d:
6420          *   a. VT-d without snooping control feature: can't guarantee the
6421          *      result, try to trust guest.
6422          *   b. VT-d with snooping control feature: snooping control feature of
6423          *      VT-d engine can guarantee the cache correctness. Just set it
6424          *      to WB to keep consistent with host. So the same as item 3.
6425          * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
6426          *    consistent with host MTRR
6427          */
6428         if (is_mmio)
6429                 ret = MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
6430         else if (vcpu->kvm->arch.iommu_domain &&
6431                 !(vcpu->kvm->arch.iommu_flags & KVM_IOMMU_CACHE_COHERENCY))
6432                 ret = kvm_get_guest_memory_type(vcpu, gfn) <<
6433                       VMX_EPT_MT_EPTE_SHIFT;
6434         else
6435                 ret = (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT)
6436                         | VMX_EPT_IPAT_BIT;
6437
6438         return ret;
6439 }
6440
6441 static int vmx_get_lpage_level(void)
6442 {
6443         if (enable_ept && !cpu_has_vmx_ept_1g_page())
6444                 return PT_DIRECTORY_LEVEL;
6445         else
6446                 /* For shadow and EPT supported 1GB page */
6447                 return PT_PDPE_LEVEL;
6448 }
6449
6450 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
6451 {
6452         struct kvm_cpuid_entry2 *best;
6453         struct vcpu_vmx *vmx = to_vmx(vcpu);
6454         u32 exec_control;
6455
6456         vmx->rdtscp_enabled = false;
6457         if (vmx_rdtscp_supported()) {
6458                 exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6459                 if (exec_control & SECONDARY_EXEC_RDTSCP) {
6460                         best = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
6461                         if (best && (best->edx & bit(X86_FEATURE_RDTSCP)))
6462                                 vmx->rdtscp_enabled = true;
6463                         else {
6464                                 exec_control &= ~SECONDARY_EXEC_RDTSCP;
6465                                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
6466                                                 exec_control);
6467                         }
6468                 }
6469         }
6470 }
6471
6472 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
6473 {
6474         if (func == 1 && nested)
6475                 entry->ecx |= bit(X86_FEATURE_VMX);
6476 }
6477
6478 /*
6479  * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
6480  * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
6481  * with L0's requirements for its guest (a.k.a. vmsc01), so we can run the L2
6482  * guest in a way that will both be appropriate to L1's requests, and our
6483  * needs. In addition to modifying the active vmcs (which is vmcs02), this
6484  * function also has additional necessary side-effects, like setting various
6485  * vcpu->arch fields.
6486  */
6487 static void prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
6488 {
6489         struct vcpu_vmx *vmx = to_vmx(vcpu);
6490         u32 exec_control;
6491
6492         vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
6493         vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
6494         vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
6495         vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
6496         vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
6497         vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
6498         vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
6499         vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
6500         vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
6501         vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
6502         vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
6503         vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
6504         vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
6505         vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
6506         vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
6507         vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
6508         vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
6509         vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
6510         vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
6511         vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
6512         vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
6513         vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
6514         vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
6515         vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
6516         vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
6517         vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
6518         vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
6519         vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
6520         vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
6521         vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
6522         vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
6523         vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
6524         vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
6525         vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
6526         vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
6527         vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
6528
6529         vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
6530         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
6531                 vmcs12->vm_entry_intr_info_field);
6532         vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
6533                 vmcs12->vm_entry_exception_error_code);
6534         vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
6535                 vmcs12->vm_entry_instruction_len);
6536         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
6537                 vmcs12->guest_interruptibility_info);
6538         vmcs_write32(GUEST_ACTIVITY_STATE, vmcs12->guest_activity_state);
6539         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
6540         vmcs_writel(GUEST_DR7, vmcs12->guest_dr7);
6541         vmcs_writel(GUEST_RFLAGS, vmcs12->guest_rflags);
6542         vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
6543                 vmcs12->guest_pending_dbg_exceptions);
6544         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
6545         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
6546
6547         vmcs_write64(VMCS_LINK_POINTER, -1ull);
6548
6549         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL,
6550                 (vmcs_config.pin_based_exec_ctrl |
6551                  vmcs12->pin_based_vm_exec_control));
6552
6553         /*
6554          * Whether page-faults are trapped is determined by a combination of
6555          * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
6556          * If enable_ept, L0 doesn't care about page faults and we should
6557          * set all of these to L1's desires. However, if !enable_ept, L0 does
6558          * care about (at least some) page faults, and because it is not easy
6559          * (if at all possible?) to merge L0 and L1's desires, we simply ask
6560          * to exit on each and every L2 page fault. This is done by setting
6561          * MASK=MATCH=0 and (see below) EB.PF=1.
6562          * Note that below we don't need special code to set EB.PF beyond the
6563          * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
6564          * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
6565          * !enable_ept, EB.PF is 1, so the "or" will always be 1.
6566          *
6567          * A problem with this approach (when !enable_ept) is that L1 may be
6568          * injected with more page faults than it asked for. This could have
6569          * caused problems, but in practice existing hypervisors don't care.
6570          * To fix this, we will need to emulate the PFEC checking (on the L1
6571          * page tables), using walk_addr(), when injecting PFs to L1.
6572          */
6573         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
6574                 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
6575         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
6576                 enable_ept ? vmcs12->page_fault_error_code_match : 0);
6577
6578         if (cpu_has_secondary_exec_ctrls()) {
6579                 u32 exec_control = vmx_secondary_exec_control(vmx);
6580                 if (!vmx->rdtscp_enabled)
6581                         exec_control &= ~SECONDARY_EXEC_RDTSCP;
6582                 /* Take the following fields only from vmcs12 */
6583                 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6584                 if (nested_cpu_has(vmcs12,
6585                                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS))
6586                         exec_control |= vmcs12->secondary_vm_exec_control;
6587
6588                 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) {
6589                         /*
6590                          * Translate L1 physical address to host physical
6591                          * address for vmcs02. Keep the page pinned, so this
6592                          * physical address remains valid. We keep a reference
6593                          * to it so we can release it later.
6594                          */
6595                         if (vmx->nested.apic_access_page) /* shouldn't happen */
6596                                 nested_release_page(vmx->nested.apic_access_page);
6597                         vmx->nested.apic_access_page =
6598                                 nested_get_page(vcpu, vmcs12->apic_access_addr);
6599                         /*
6600                          * If translation failed, no matter: This feature asks
6601                          * to exit when accessing the given address, and if it
6602                          * can never be accessed, this feature won't do
6603                          * anything anyway.
6604                          */
6605                         if (!vmx->nested.apic_access_page)
6606                                 exec_control &=
6607                                   ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6608                         else
6609                                 vmcs_write64(APIC_ACCESS_ADDR,
6610                                   page_to_phys(vmx->nested.apic_access_page));
6611                 }
6612
6613                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
6614         }
6615
6616
6617         /*
6618          * Set host-state according to L0's settings (vmcs12 is irrelevant here)
6619          * Some constant fields are set here by vmx_set_constant_host_state().
6620          * Other fields are different per CPU, and will be set later when
6621          * vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
6622          */
6623         vmx_set_constant_host_state();
6624
6625         /*
6626          * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
6627          * entry, but only if the current (host) sp changed from the value
6628          * we wrote last (vmx->host_rsp). This cache is no longer relevant
6629          * if we switch vmcs, and rather than hold a separate cache per vmcs,
6630          * here we just force the write to happen on entry.
6631          */
6632         vmx->host_rsp = 0;
6633
6634         exec_control = vmx_exec_control(vmx); /* L0's desires */
6635         exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
6636         exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
6637         exec_control &= ~CPU_BASED_TPR_SHADOW;
6638         exec_control |= vmcs12->cpu_based_vm_exec_control;
6639         /*
6640          * Merging of IO and MSR bitmaps not currently supported.
6641          * Rather, exit every time.
6642          */
6643         exec_control &= ~CPU_BASED_USE_MSR_BITMAPS;
6644         exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
6645         exec_control |= CPU_BASED_UNCOND_IO_EXITING;
6646
6647         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
6648
6649         /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
6650          * bitwise-or of what L1 wants to trap for L2, and what we want to
6651          * trap. Note that CR0.TS also needs updating - we do this later.
6652          */
6653         update_exception_bitmap(vcpu);
6654         vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
6655         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
6656
6657         /* Note: IA32_MODE, LOAD_IA32_EFER are modified by vmx_set_efer below */
6658         vmcs_write32(VM_EXIT_CONTROLS,
6659                 vmcs12->vm_exit_controls | vmcs_config.vmexit_ctrl);
6660         vmcs_write32(VM_ENTRY_CONTROLS, vmcs12->vm_entry_controls |
6661                 (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
6662
6663         if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)
6664                 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
6665         else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
6666                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
6667
6668
6669         set_cr4_guest_host_mask(vmx);
6670
6671         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
6672                 vmcs_write64(TSC_OFFSET,
6673                         vmx->nested.vmcs01_tsc_offset + vmcs12->tsc_offset);
6674         else
6675                 vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset);
6676
6677         if (enable_vpid) {
6678                 /*
6679                  * Trivially support vpid by letting L2s share their parent
6680                  * L1's vpid. TODO: move to a more elaborate solution, giving
6681                  * each L2 its own vpid and exposing the vpid feature to L1.
6682                  */
6683                 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
6684                 vmx_flush_tlb(vcpu);
6685         }
6686
6687         if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)
6688                 vcpu->arch.efer = vmcs12->guest_ia32_efer;
6689         if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
6690                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
6691         else
6692                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
6693         /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
6694         vmx_set_efer(vcpu, vcpu->arch.efer);
6695
6696         /*
6697          * This sets GUEST_CR0 to vmcs12->guest_cr0, with possibly a modified
6698          * TS bit (for lazy fpu) and bits which we consider mandatory enabled.
6699          * The CR0_READ_SHADOW is what L2 should have expected to read given
6700          * the specifications by L1; It's not enough to take
6701          * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
6702          * have more bits than L1 expected.
6703          */
6704         vmx_set_cr0(vcpu, vmcs12->guest_cr0);
6705         vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
6706
6707         vmx_set_cr4(vcpu, vmcs12->guest_cr4);
6708         vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
6709
6710         /* shadow page tables on either EPT or shadow page tables */
6711         kvm_set_cr3(vcpu, vmcs12->guest_cr3);
6712         kvm_mmu_reset_context(vcpu);
6713
6714         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
6715         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
6716 }
6717
6718 /*
6719  * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
6720  * for running an L2 nested guest.
6721  */
6722 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
6723 {
6724         struct vmcs12 *vmcs12;
6725         struct vcpu_vmx *vmx = to_vmx(vcpu);
6726         int cpu;
6727         struct loaded_vmcs *vmcs02;
6728
6729         if (!nested_vmx_check_permission(vcpu) ||
6730             !nested_vmx_check_vmcs12(vcpu))
6731                 return 1;
6732
6733         skip_emulated_instruction(vcpu);
6734         vmcs12 = get_vmcs12(vcpu);
6735
6736         /*
6737          * The nested entry process starts with enforcing various prerequisites
6738          * on vmcs12 as required by the Intel SDM, and act appropriately when
6739          * they fail: As the SDM explains, some conditions should cause the
6740          * instruction to fail, while others will cause the instruction to seem
6741          * to succeed, but return an EXIT_REASON_INVALID_STATE.
6742          * To speed up the normal (success) code path, we should avoid checking
6743          * for misconfigurations which will anyway be caught by the processor
6744          * when using the merged vmcs02.
6745          */
6746         if (vmcs12->launch_state == launch) {
6747                 nested_vmx_failValid(vcpu,
6748                         launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
6749                                : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
6750                 return 1;
6751         }
6752
6753         if ((vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_MSR_BITMAPS) &&
6754                         !IS_ALIGNED(vmcs12->msr_bitmap, PAGE_SIZE)) {
6755                 /*TODO: Also verify bits beyond physical address width are 0*/
6756                 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
6757                 return 1;
6758         }
6759
6760         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
6761                         !IS_ALIGNED(vmcs12->apic_access_addr, PAGE_SIZE)) {
6762                 /*TODO: Also verify bits beyond physical address width are 0*/
6763                 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
6764                 return 1;
6765         }
6766
6767         if (vmcs12->vm_entry_msr_load_count > 0 ||
6768             vmcs12->vm_exit_msr_load_count > 0 ||
6769             vmcs12->vm_exit_msr_store_count > 0) {
6770                 pr_warn_ratelimited("%s: VMCS MSR_{LOAD,STORE} unsupported\n",
6771                                     __func__);
6772                 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
6773                 return 1;
6774         }
6775
6776         if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
6777               nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high) ||
6778             !vmx_control_verify(vmcs12->secondary_vm_exec_control,
6779               nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high) ||
6780             !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
6781               nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high) ||
6782             !vmx_control_verify(vmcs12->vm_exit_controls,
6783               nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high) ||
6784             !vmx_control_verify(vmcs12->vm_entry_controls,
6785               nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high))
6786         {
6787                 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
6788                 return 1;
6789         }
6790
6791         if (((vmcs12->host_cr0 & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON) ||
6792             ((vmcs12->host_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
6793                 nested_vmx_failValid(vcpu,
6794                         VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
6795                 return 1;
6796         }
6797
6798         if (((vmcs12->guest_cr0 & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON) ||
6799             ((vmcs12->guest_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
6800                 nested_vmx_entry_failure(vcpu, vmcs12,
6801                         EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
6802                 return 1;
6803         }
6804         if (vmcs12->vmcs_link_pointer != -1ull) {
6805                 nested_vmx_entry_failure(vcpu, vmcs12,
6806                         EXIT_REASON_INVALID_STATE, ENTRY_FAIL_VMCS_LINK_PTR);
6807                 return 1;
6808         }
6809
6810         /*
6811          * We're finally done with prerequisite checking, and can start with
6812          * the nested entry.
6813          */
6814
6815         vmcs02 = nested_get_current_vmcs02(vmx);
6816         if (!vmcs02)
6817                 return -ENOMEM;
6818
6819         enter_guest_mode(vcpu);
6820
6821         vmx->nested.vmcs01_tsc_offset = vmcs_read64(TSC_OFFSET);
6822
6823         cpu = get_cpu();
6824         vmx->loaded_vmcs = vmcs02;
6825         vmx_vcpu_put(vcpu);
6826         vmx_vcpu_load(vcpu, cpu);
6827         vcpu->cpu = cpu;
6828         put_cpu();
6829
6830         vmcs12->launch_state = 1;
6831
6832         prepare_vmcs02(vcpu, vmcs12);
6833
6834         /*
6835          * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
6836          * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
6837          * returned as far as L1 is concerned. It will only return (and set
6838          * the success flag) when L2 exits (see nested_vmx_vmexit()).
6839          */
6840         return 1;
6841 }
6842
6843 /*
6844  * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
6845  * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
6846  * This function returns the new value we should put in vmcs12.guest_cr0.
6847  * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
6848  *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
6849  *     available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
6850  *     didn't trap the bit, because if L1 did, so would L0).
6851  *  2. Bits that L1 asked to trap (and therefore L0 also did) could not have
6852  *     been modified by L2, and L1 knows it. So just leave the old value of
6853  *     the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
6854  *     isn't relevant, because if L0 traps this bit it can set it to anything.
6855  *  3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
6856  *     changed these bits, and therefore they need to be updated, but L0
6857  *     didn't necessarily allow them to be changed in GUEST_CR0 - and rather
6858  *     put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
6859  */
6860 static inline unsigned long
6861 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
6862 {
6863         return
6864         /*1*/   (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
6865         /*2*/   (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
6866         /*3*/   (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
6867                         vcpu->arch.cr0_guest_owned_bits));
6868 }
6869
6870 static inline unsigned long
6871 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
6872 {
6873         return
6874         /*1*/   (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
6875         /*2*/   (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
6876         /*3*/   (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
6877                         vcpu->arch.cr4_guest_owned_bits));
6878 }
6879
6880 /*
6881  * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
6882  * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
6883  * and this function updates it to reflect the changes to the guest state while
6884  * L2 was running (and perhaps made some exits which were handled directly by L0
6885  * without going back to L1), and to reflect the exit reason.
6886  * Note that we do not have to copy here all VMCS fields, just those that
6887  * could have changed by the L2 guest or the exit - i.e., the guest-state and
6888  * exit-information fields only. Other fields are modified by L1 with VMWRITE,
6889  * which already writes to vmcs12 directly.
6890  */
6891 void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
6892 {
6893         /* update guest state fields: */
6894         vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
6895         vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
6896
6897         kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
6898         vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
6899         vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
6900         vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
6901
6902         vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
6903         vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
6904         vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
6905         vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
6906         vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
6907         vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
6908         vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
6909         vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
6910         vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
6911         vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
6912         vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
6913         vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
6914         vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
6915         vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
6916         vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
6917         vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
6918         vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
6919         vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
6920         vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
6921         vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
6922         vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
6923         vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
6924         vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
6925         vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
6926         vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
6927         vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
6928         vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
6929         vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
6930         vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
6931         vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
6932         vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
6933         vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
6934         vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
6935         vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
6936         vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
6937         vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
6938
6939         vmcs12->guest_activity_state = vmcs_read32(GUEST_ACTIVITY_STATE);
6940         vmcs12->guest_interruptibility_info =
6941                 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
6942         vmcs12->guest_pending_dbg_exceptions =
6943                 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
6944
6945         /* TODO: These cannot have changed unless we have MSR bitmaps and
6946          * the relevant bit asks not to trap the change */
6947         vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
6948         if (vmcs12->vm_entry_controls & VM_EXIT_SAVE_IA32_PAT)
6949                 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
6950         vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
6951         vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
6952         vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
6953
6954         /* update exit information fields: */
6955
6956         vmcs12->vm_exit_reason  = vmcs_read32(VM_EXIT_REASON);
6957         vmcs12->exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6958
6959         vmcs12->vm_exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6960         vmcs12->vm_exit_intr_error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
6961         vmcs12->idt_vectoring_info_field =
6962                 vmcs_read32(IDT_VECTORING_INFO_FIELD);
6963         vmcs12->idt_vectoring_error_code =
6964                 vmcs_read32(IDT_VECTORING_ERROR_CODE);
6965         vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6966         vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
6967
6968         /* clear vm-entry fields which are to be cleared on exit */
6969         if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
6970                 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
6971 }
6972
6973 /*
6974  * A part of what we need to when the nested L2 guest exits and we want to
6975  * run its L1 parent, is to reset L1's guest state to the host state specified
6976  * in vmcs12.
6977  * This function is to be called not only on normal nested exit, but also on
6978  * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
6979  * Failures During or After Loading Guest State").
6980  * This function should be called when the active VMCS is L1's (vmcs01).
6981  */
6982 void load_vmcs12_host_state(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
6983 {
6984         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
6985                 vcpu->arch.efer = vmcs12->host_ia32_efer;
6986         if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
6987                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
6988         else
6989                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
6990         vmx_set_efer(vcpu, vcpu->arch.efer);
6991
6992         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
6993         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
6994         /*
6995          * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
6996          * actually changed, because it depends on the current state of
6997          * fpu_active (which may have changed).
6998          * Note that vmx_set_cr0 refers to efer set above.
6999          */
7000         kvm_set_cr0(vcpu, vmcs12->host_cr0);
7001         /*
7002          * If we did fpu_activate()/fpu_deactivate() during L2's run, we need
7003          * to apply the same changes to L1's vmcs. We just set cr0 correctly,
7004          * but we also need to update cr0_guest_host_mask and exception_bitmap.
7005          */
7006         update_exception_bitmap(vcpu);
7007         vcpu->arch.cr0_guest_owned_bits = (vcpu->fpu_active ? X86_CR0_TS : 0);
7008         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
7009
7010         /*
7011          * Note that CR4_GUEST_HOST_MASK is already set in the original vmcs01
7012          * (KVM doesn't change it)- no reason to call set_cr4_guest_host_mask();
7013          */
7014         vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
7015         kvm_set_cr4(vcpu, vmcs12->host_cr4);
7016
7017         /* shadow page tables on either EPT or shadow page tables */
7018         kvm_set_cr3(vcpu, vmcs12->host_cr3);
7019         kvm_mmu_reset_context(vcpu);
7020
7021         if (enable_vpid) {
7022                 /*
7023                  * Trivially support vpid by letting L2s share their parent
7024                  * L1's vpid. TODO: move to a more elaborate solution, giving
7025                  * each L2 its own vpid and exposing the vpid feature to L1.
7026                  */
7027                 vmx_flush_tlb(vcpu);
7028         }
7029
7030
7031         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
7032         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
7033         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
7034         vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
7035         vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
7036         vmcs_writel(GUEST_TR_BASE, vmcs12->host_tr_base);
7037         vmcs_writel(GUEST_GS_BASE, vmcs12->host_gs_base);
7038         vmcs_writel(GUEST_FS_BASE, vmcs12->host_fs_base);
7039         vmcs_write16(GUEST_ES_SELECTOR, vmcs12->host_es_selector);
7040         vmcs_write16(GUEST_CS_SELECTOR, vmcs12->host_cs_selector);
7041         vmcs_write16(GUEST_SS_SELECTOR, vmcs12->host_ss_selector);
7042         vmcs_write16(GUEST_DS_SELECTOR, vmcs12->host_ds_selector);
7043         vmcs_write16(GUEST_FS_SELECTOR, vmcs12->host_fs_selector);
7044         vmcs_write16(GUEST_GS_SELECTOR, vmcs12->host_gs_selector);
7045         vmcs_write16(GUEST_TR_SELECTOR, vmcs12->host_tr_selector);
7046
7047         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT)
7048                 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
7049         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
7050                 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
7051                         vmcs12->host_ia32_perf_global_ctrl);
7052 }
7053
7054 /*
7055  * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
7056  * and modify vmcs12 to make it see what it would expect to see there if
7057  * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
7058  */
7059 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu)
7060 {
7061         struct vcpu_vmx *vmx = to_vmx(vcpu);
7062         int cpu;
7063         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7064
7065         leave_guest_mode(vcpu);
7066         prepare_vmcs12(vcpu, vmcs12);
7067
7068         cpu = get_cpu();
7069         vmx->loaded_vmcs = &vmx->vmcs01;
7070         vmx_vcpu_put(vcpu);
7071         vmx_vcpu_load(vcpu, cpu);
7072         vcpu->cpu = cpu;
7073         put_cpu();
7074
7075         /* if no vmcs02 cache requested, remove the one we used */
7076         if (VMCS02_POOL_SIZE == 0)
7077                 nested_free_vmcs02(vmx, vmx->nested.current_vmptr);
7078
7079         load_vmcs12_host_state(vcpu, vmcs12);
7080
7081         /* Update TSC_OFFSET if TSC was changed while L2 ran */
7082         vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset);
7083
7084         /* This is needed for same reason as it was needed in prepare_vmcs02 */
7085         vmx->host_rsp = 0;
7086
7087         /* Unpin physical memory we referred to in vmcs02 */
7088         if (vmx->nested.apic_access_page) {
7089                 nested_release_page(vmx->nested.apic_access_page);
7090                 vmx->nested.apic_access_page = 0;
7091         }
7092
7093         /*
7094          * Exiting from L2 to L1, we're now back to L1 which thinks it just
7095          * finished a VMLAUNCH or VMRESUME instruction, so we need to set the
7096          * success or failure flag accordingly.
7097          */
7098         if (unlikely(vmx->fail)) {
7099                 vmx->fail = 0;
7100                 nested_vmx_failValid(vcpu, vmcs_read32(VM_INSTRUCTION_ERROR));
7101         } else
7102                 nested_vmx_succeed(vcpu);
7103 }
7104
7105 /*
7106  * L1's failure to enter L2 is a subset of a normal exit, as explained in
7107  * 23.7 "VM-entry failures during or after loading guest state" (this also
7108  * lists the acceptable exit-reason and exit-qualification parameters).
7109  * It should only be called before L2 actually succeeded to run, and when
7110  * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
7111  */
7112 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
7113                         struct vmcs12 *vmcs12,
7114                         u32 reason, unsigned long qualification)
7115 {
7116         load_vmcs12_host_state(vcpu, vmcs12);
7117         vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
7118         vmcs12->exit_qualification = qualification;
7119         nested_vmx_succeed(vcpu);
7120 }
7121
7122 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7123                                struct x86_instruction_info *info,
7124                                enum x86_intercept_stage stage)
7125 {
7126         return X86EMUL_CONTINUE;
7127 }
7128
7129 static struct kvm_x86_ops vmx_x86_ops = {
7130         .cpu_has_kvm_support = cpu_has_kvm_support,
7131         .disabled_by_bios = vmx_disabled_by_bios,
7132         .hardware_setup = hardware_setup,
7133         .hardware_unsetup = hardware_unsetup,
7134         .check_processor_compatibility = vmx_check_processor_compat,
7135         .hardware_enable = hardware_enable,
7136         .hardware_disable = hardware_disable,
7137         .cpu_has_accelerated_tpr = report_flexpriority,
7138
7139         .vcpu_create = vmx_create_vcpu,
7140         .vcpu_free = vmx_free_vcpu,
7141         .vcpu_reset = vmx_vcpu_reset,
7142
7143         .prepare_guest_switch = vmx_save_host_state,
7144         .vcpu_load = vmx_vcpu_load,
7145         .vcpu_put = vmx_vcpu_put,
7146
7147         .set_guest_debug = set_guest_debug,
7148         .get_msr = vmx_get_msr,
7149         .set_msr = vmx_set_msr,
7150         .get_segment_base = vmx_get_segment_base,
7151         .get_segment = vmx_get_segment,
7152         .set_segment = vmx_set_segment,
7153         .get_cpl = vmx_get_cpl,
7154         .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7155         .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
7156         .decache_cr3 = vmx_decache_cr3,
7157         .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
7158         .set_cr0 = vmx_set_cr0,
7159         .set_cr3 = vmx_set_cr3,
7160         .set_cr4 = vmx_set_cr4,
7161         .set_efer = vmx_set_efer,
7162         .get_idt = vmx_get_idt,
7163         .set_idt = vmx_set_idt,
7164         .get_gdt = vmx_get_gdt,
7165         .set_gdt = vmx_set_gdt,
7166         .set_dr7 = vmx_set_dr7,
7167         .cache_reg = vmx_cache_reg,
7168         .get_rflags = vmx_get_rflags,
7169         .set_rflags = vmx_set_rflags,
7170         .fpu_activate = vmx_fpu_activate,
7171         .fpu_deactivate = vmx_fpu_deactivate,
7172
7173         .tlb_flush = vmx_flush_tlb,
7174
7175         .run = vmx_vcpu_run,
7176         .handle_exit = vmx_handle_exit,
7177         .skip_emulated_instruction = skip_emulated_instruction,
7178         .set_interrupt_shadow = vmx_set_interrupt_shadow,
7179         .get_interrupt_shadow = vmx_get_interrupt_shadow,
7180         .patch_hypercall = vmx_patch_hypercall,
7181         .set_irq = vmx_inject_irq,
7182         .set_nmi = vmx_inject_nmi,
7183         .queue_exception = vmx_queue_exception,
7184         .cancel_injection = vmx_cancel_injection,
7185         .interrupt_allowed = vmx_interrupt_allowed,
7186         .nmi_allowed = vmx_nmi_allowed,
7187         .get_nmi_mask = vmx_get_nmi_mask,
7188         .set_nmi_mask = vmx_set_nmi_mask,
7189         .enable_nmi_window = enable_nmi_window,
7190         .enable_irq_window = enable_irq_window,
7191         .update_cr8_intercept = update_cr8_intercept,
7192
7193         .set_tss_addr = vmx_set_tss_addr,
7194         .get_tdp_level = get_ept_level,
7195         .get_mt_mask = vmx_get_mt_mask,
7196
7197         .get_exit_info = vmx_get_exit_info,
7198
7199         .get_lpage_level = vmx_get_lpage_level,
7200
7201         .cpuid_update = vmx_cpuid_update,
7202
7203         .rdtscp_supported = vmx_rdtscp_supported,
7204
7205         .set_supported_cpuid = vmx_set_supported_cpuid,
7206
7207         .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7208
7209         .set_tsc_khz = vmx_set_tsc_khz,
7210         .write_tsc_offset = vmx_write_tsc_offset,
7211         .adjust_tsc_offset = vmx_adjust_tsc_offset,
7212         .compute_tsc_offset = vmx_compute_tsc_offset,
7213         .read_l1_tsc = vmx_read_l1_tsc,
7214
7215         .set_tdp_cr3 = vmx_set_cr3,
7216
7217         .check_intercept = vmx_check_intercept,
7218 };
7219
7220 static int __init vmx_init(void)
7221 {
7222         int r, i;
7223
7224         rdmsrl_safe(MSR_EFER, &host_efer);
7225
7226         for (i = 0; i < NR_VMX_MSR; ++i)
7227                 kvm_define_shared_msr(i, vmx_msr_index[i]);
7228
7229         vmx_io_bitmap_a = (unsigned long *)__get_free_page(GFP_KERNEL);
7230         if (!vmx_io_bitmap_a)
7231                 return -ENOMEM;
7232
7233         vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL);
7234         if (!vmx_io_bitmap_b) {
7235                 r = -ENOMEM;
7236                 goto out;
7237         }
7238
7239         vmx_msr_bitmap_legacy = (unsigned long *)__get_free_page(GFP_KERNEL);
7240         if (!vmx_msr_bitmap_legacy) {
7241                 r = -ENOMEM;
7242                 goto out1;
7243         }
7244
7245         vmx_msr_bitmap_longmode = (unsigned long *)__get_free_page(GFP_KERNEL);
7246         if (!vmx_msr_bitmap_longmode) {
7247                 r = -ENOMEM;
7248                 goto out2;
7249         }
7250
7251         /*
7252          * Allow direct access to the PC debug port (it is often used for I/O
7253          * delays, but the vmexits simply slow things down).
7254          */
7255         memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE);
7256         clear_bit(0x80, vmx_io_bitmap_a);
7257
7258         memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE);
7259
7260         memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE);
7261         memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE);
7262
7263         set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7264
7265         r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
7266                      __alignof__(struct vcpu_vmx), THIS_MODULE);
7267         if (r)
7268                 goto out3;
7269
7270         vmx_disable_intercept_for_msr(MSR_FS_BASE, false);
7271         vmx_disable_intercept_for_msr(MSR_GS_BASE, false);
7272         vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true);
7273         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false);
7274         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false);
7275         vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false);
7276
7277         if (enable_ept) {
7278                 kvm_mmu_set_mask_ptes(0ull, 0ull, 0ull, 0ull,
7279                                 VMX_EPT_EXECUTABLE_MASK);
7280                 ept_set_mmio_spte_mask();
7281                 kvm_enable_tdp();
7282         } else
7283                 kvm_disable_tdp();
7284
7285         return 0;
7286
7287 out3:
7288         free_page((unsigned long)vmx_msr_bitmap_longmode);
7289 out2:
7290         free_page((unsigned long)vmx_msr_bitmap_legacy);
7291 out1:
7292         free_page((unsigned long)vmx_io_bitmap_b);
7293 out:
7294         free_page((unsigned long)vmx_io_bitmap_a);
7295         return r;
7296 }
7297
7298 static void __exit vmx_exit(void)
7299 {
7300         free_page((unsigned long)vmx_msr_bitmap_legacy);
7301         free_page((unsigned long)vmx_msr_bitmap_longmode);
7302         free_page((unsigned long)vmx_io_bitmap_b);
7303         free_page((unsigned long)vmx_io_bitmap_a);
7304
7305         kvm_exit();
7306 }
7307
7308 module_init(vmx_init)
7309 module_exit(vmx_exit)