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