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