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