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