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