bd0ed47989e4f8af4ce6345aaf1ba7c1399828ae
[pandora-kernel.git] / arch / x86 / kvm / vmx.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
9  *
10  * Authors:
11  *   Avi Kivity   <avi@qumranet.com>
12  *   Yaniv Kamay  <yaniv@qumranet.com>
13  *
14  * This work is licensed under the terms of the GNU GPL, version 2.  See
15  * the COPYING file in the top-level directory.
16  *
17  */
18
19 #include "irq.h"
20 #include "mmu.h"
21
22 #include <linux/kvm_host.h>
23 #include <linux/module.h>
24 #include <linux/kernel.h>
25 #include <linux/mm.h>
26 #include <linux/highmem.h>
27 #include <linux/sched.h>
28 #include <linux/moduleparam.h>
29 #include <linux/ftrace_event.h>
30 #include <linux/slab.h>
31 #include <linux/tboot.h>
32 #include "kvm_cache_regs.h"
33 #include "x86.h"
34
35 #include <asm/io.h>
36 #include <asm/desc.h>
37 #include <asm/vmx.h>
38 #include <asm/virtext.h>
39 #include <asm/mce.h>
40 #include <asm/i387.h>
41 #include <asm/xcr.h>
42 #include <asm/perf_event.h>
43
44 #include "trace.h"
45
46 #define __ex(x) __kvm_handle_fault_on_reboot(x)
47 #define __ex_clear(x, reg) \
48         ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
49
50 MODULE_AUTHOR("Qumranet");
51 MODULE_LICENSE("GPL");
52
53 static int __read_mostly enable_vpid = 1;
54 module_param_named(vpid, enable_vpid, bool, 0444);
55
56 static int __read_mostly flexpriority_enabled = 1;
57 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
58
59 static int __read_mostly enable_ept = 1;
60 module_param_named(ept, enable_ept, bool, S_IRUGO);
61
62 static int __read_mostly enable_unrestricted_guest = 1;
63 module_param_named(unrestricted_guest,
64                         enable_unrestricted_guest, bool, S_IRUGO);
65
66 static int __read_mostly emulate_invalid_guest_state = 0;
67 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
68
69 static int __read_mostly vmm_exclusive = 1;
70 module_param(vmm_exclusive, bool, S_IRUGO);
71
72 static int __read_mostly yield_on_hlt = 1;
73 module_param(yield_on_hlt, bool, S_IRUGO);
74
75 static int __read_mostly fasteoi = 1;
76 module_param(fasteoi, bool, S_IRUGO);
77
78 /*
79  * If nested=1, nested virtualization is supported, i.e., guests may use
80  * VMX and be a hypervisor for its own guests. If nested=0, guests may not
81  * use VMX instructions.
82  */
83 static int __read_mostly nested = 0;
84 module_param(nested, bool, S_IRUGO);
85
86 #define KVM_GUEST_CR0_MASK_UNRESTRICTED_GUEST                           \
87         (X86_CR0_WP | X86_CR0_NE | X86_CR0_NW | X86_CR0_CD)
88 #define KVM_GUEST_CR0_MASK                                              \
89         (KVM_GUEST_CR0_MASK_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
90 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST                         \
91         (X86_CR0_WP | X86_CR0_NE)
92 #define KVM_VM_CR0_ALWAYS_ON                                            \
93         (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
94 #define KVM_CR4_GUEST_OWNED_BITS                                      \
95         (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR      \
96          | X86_CR4_OSXMMEXCPT)
97
98 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
99 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
100
101 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
102
103 /*
104  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
105  * ple_gap:    upper bound on the amount of time between two successive
106  *             executions of PAUSE in a loop. Also indicate if ple enabled.
107  *             According to test, this time is usually smaller than 128 cycles.
108  * ple_window: upper bound on the amount of time a guest is allowed to execute
109  *             in a PAUSE loop. Tests indicate that most spinlocks are held for
110  *             less than 2^12 cycles
111  * Time is measured based on a counter that runs at the same rate as the TSC,
112  * refer SDM volume 3b section 21.6.13 & 22.1.3.
113  */
114 #define KVM_VMX_DEFAULT_PLE_GAP    128
115 #define KVM_VMX_DEFAULT_PLE_WINDOW 4096
116 static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
117 module_param(ple_gap, int, S_IRUGO);
118
119 static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
120 module_param(ple_window, int, S_IRUGO);
121
122 #define NR_AUTOLOAD_MSRS 8
123 #define VMCS02_POOL_SIZE 1
124
125 struct vmcs {
126         u32 revision_id;
127         u32 abort;
128         char data[0];
129 };
130
131 /*
132  * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
133  * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
134  * loaded on this CPU (so we can clear them if the CPU goes down).
135  */
136 struct loaded_vmcs {
137         struct vmcs *vmcs;
138         int cpu;
139         int launched;
140         struct list_head loaded_vmcss_on_cpu_link;
141 };
142
143 struct shared_msr_entry {
144         unsigned index;
145         u64 data;
146         u64 mask;
147 };
148
149 /*
150  * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
151  * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
152  * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
153  * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
154  * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
155  * More than one of these structures may exist, if L1 runs multiple L2 guests.
156  * nested_vmx_run() will use the data here to build a vmcs02: a VMCS for the
157  * underlying hardware which will be used to run L2.
158  * This structure is packed to ensure that its layout is identical across
159  * machines (necessary for live migration).
160  * If there are changes in this struct, VMCS12_REVISION must be changed.
161  */
162 typedef u64 natural_width;
163 struct __packed vmcs12 {
164         /* According to the Intel spec, a VMCS region must start with the
165          * following two fields. Then follow implementation-specific data.
166          */
167         u32 revision_id;
168         u32 abort;
169
170         u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
171         u32 padding[7]; /* room for future expansion */
172
173         u64 io_bitmap_a;
174         u64 io_bitmap_b;
175         u64 msr_bitmap;
176         u64 vm_exit_msr_store_addr;
177         u64 vm_exit_msr_load_addr;
178         u64 vm_entry_msr_load_addr;
179         u64 tsc_offset;
180         u64 virtual_apic_page_addr;
181         u64 apic_access_addr;
182         u64 ept_pointer;
183         u64 guest_physical_address;
184         u64 vmcs_link_pointer;
185         u64 guest_ia32_debugctl;
186         u64 guest_ia32_pat;
187         u64 guest_ia32_efer;
188         u64 guest_ia32_perf_global_ctrl;
189         u64 guest_pdptr0;
190         u64 guest_pdptr1;
191         u64 guest_pdptr2;
192         u64 guest_pdptr3;
193         u64 host_ia32_pat;
194         u64 host_ia32_efer;
195         u64 host_ia32_perf_global_ctrl;
196         u64 padding64[8]; /* room for future expansion */
197         /*
198          * To allow migration of L1 (complete with its L2 guests) between
199          * machines of different natural widths (32 or 64 bit), we cannot have
200          * unsigned long fields with no explict size. We use u64 (aliased
201          * natural_width) instead. Luckily, x86 is little-endian.
202          */
203         natural_width cr0_guest_host_mask;
204         natural_width cr4_guest_host_mask;
205         natural_width cr0_read_shadow;
206         natural_width cr4_read_shadow;
207         natural_width cr3_target_value0;
208         natural_width cr3_target_value1;
209         natural_width cr3_target_value2;
210         natural_width cr3_target_value3;
211         natural_width exit_qualification;
212         natural_width guest_linear_address;
213         natural_width guest_cr0;
214         natural_width guest_cr3;
215         natural_width guest_cr4;
216         natural_width guest_es_base;
217         natural_width guest_cs_base;
218         natural_width guest_ss_base;
219         natural_width guest_ds_base;
220         natural_width guest_fs_base;
221         natural_width guest_gs_base;
222         natural_width guest_ldtr_base;
223         natural_width guest_tr_base;
224         natural_width guest_gdtr_base;
225         natural_width guest_idtr_base;
226         natural_width guest_dr7;
227         natural_width guest_rsp;
228         natural_width guest_rip;
229         natural_width guest_rflags;
230         natural_width guest_pending_dbg_exceptions;
231         natural_width guest_sysenter_esp;
232         natural_width guest_sysenter_eip;
233         natural_width host_cr0;
234         natural_width host_cr3;
235         natural_width host_cr4;
236         natural_width host_fs_base;
237         natural_width host_gs_base;
238         natural_width host_tr_base;
239         natural_width host_gdtr_base;
240         natural_width host_idtr_base;
241         natural_width host_ia32_sysenter_esp;
242         natural_width host_ia32_sysenter_eip;
243         natural_width host_rsp;
244         natural_width host_rip;
245         natural_width paddingl[8]; /* room for future expansion */
246         u32 pin_based_vm_exec_control;
247         u32 cpu_based_vm_exec_control;
248         u32 exception_bitmap;
249         u32 page_fault_error_code_mask;
250         u32 page_fault_error_code_match;
251         u32 cr3_target_count;
252         u32 vm_exit_controls;
253         u32 vm_exit_msr_store_count;
254         u32 vm_exit_msr_load_count;
255         u32 vm_entry_controls;
256         u32 vm_entry_msr_load_count;
257         u32 vm_entry_intr_info_field;
258         u32 vm_entry_exception_error_code;
259         u32 vm_entry_instruction_len;
260         u32 tpr_threshold;
261         u32 secondary_vm_exec_control;
262         u32 vm_instruction_error;
263         u32 vm_exit_reason;
264         u32 vm_exit_intr_info;
265         u32 vm_exit_intr_error_code;
266         u32 idt_vectoring_info_field;
267         u32 idt_vectoring_error_code;
268         u32 vm_exit_instruction_len;
269         u32 vmx_instruction_info;
270         u32 guest_es_limit;
271         u32 guest_cs_limit;
272         u32 guest_ss_limit;
273         u32 guest_ds_limit;
274         u32 guest_fs_limit;
275         u32 guest_gs_limit;
276         u32 guest_ldtr_limit;
277         u32 guest_tr_limit;
278         u32 guest_gdtr_limit;
279         u32 guest_idtr_limit;
280         u32 guest_es_ar_bytes;
281         u32 guest_cs_ar_bytes;
282         u32 guest_ss_ar_bytes;
283         u32 guest_ds_ar_bytes;
284         u32 guest_fs_ar_bytes;
285         u32 guest_gs_ar_bytes;
286         u32 guest_ldtr_ar_bytes;
287         u32 guest_tr_ar_bytes;
288         u32 guest_interruptibility_info;
289         u32 guest_activity_state;
290         u32 guest_sysenter_cs;
291         u32 host_ia32_sysenter_cs;
292         u32 padding32[8]; /* room for future expansion */
293         u16 virtual_processor_id;
294         u16 guest_es_selector;
295         u16 guest_cs_selector;
296         u16 guest_ss_selector;
297         u16 guest_ds_selector;
298         u16 guest_fs_selector;
299         u16 guest_gs_selector;
300         u16 guest_ldtr_selector;
301         u16 guest_tr_selector;
302         u16 host_es_selector;
303         u16 host_cs_selector;
304         u16 host_ss_selector;
305         u16 host_ds_selector;
306         u16 host_fs_selector;
307         u16 host_gs_selector;
308         u16 host_tr_selector;
309 };
310
311 /*
312  * VMCS12_REVISION is an arbitrary id that should be changed if the content or
313  * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
314  * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
315  */
316 #define VMCS12_REVISION 0x11e57ed0
317
318 /*
319  * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
320  * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
321  * current implementation, 4K are reserved to avoid future complications.
322  */
323 #define VMCS12_SIZE 0x1000
324
325 /* Used to remember the last vmcs02 used for some recently used vmcs12s */
326 struct vmcs02_list {
327         struct list_head list;
328         gpa_t vmptr;
329         struct loaded_vmcs vmcs02;
330 };
331
332 /*
333  * The nested_vmx structure is part of vcpu_vmx, and holds information we need
334  * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
335  */
336 struct nested_vmx {
337         /* Has the level1 guest done vmxon? */
338         bool vmxon;
339
340         /* The guest-physical address of the current VMCS L1 keeps for L2 */
341         gpa_t current_vmptr;
342         /* The host-usable pointer to the above */
343         struct page *current_vmcs12_page;
344         struct vmcs12 *current_vmcs12;
345
346         /* vmcs02_list cache of VMCSs recently used to run L2 guests */
347         struct list_head vmcs02_pool;
348         int vmcs02_num;
349         u64 vmcs01_tsc_offset;
350         /* L2 must run next, and mustn't decide to exit to L1. */
351         bool nested_run_pending;
352         /*
353          * Guest pages referred to in vmcs02 with host-physical pointers, so
354          * we must keep them pinned while L2 runs.
355          */
356         struct page *apic_access_page;
357 };
358
359 struct vcpu_vmx {
360         struct kvm_vcpu       vcpu;
361         unsigned long         host_rsp;
362         u8                    fail;
363         u8                    cpl;
364         bool                  nmi_known_unmasked;
365         u32                   exit_intr_info;
366         u32                   idt_vectoring_info;
367         ulong                 rflags;
368         struct shared_msr_entry *guest_msrs;
369         int                   nmsrs;
370         int                   save_nmsrs;
371 #ifdef CONFIG_X86_64
372         u64                   msr_host_kernel_gs_base;
373         u64                   msr_guest_kernel_gs_base;
374 #endif
375         /*
376          * loaded_vmcs points to the VMCS currently used in this vcpu. For a
377          * non-nested (L1) guest, it always points to vmcs01. For a nested
378          * guest (L2), it points to a different VMCS.
379          */
380         struct loaded_vmcs    vmcs01;
381         struct loaded_vmcs   *loaded_vmcs;
382         bool                  __launched; /* temporary, used in vmx_vcpu_run */
383         struct msr_autoload {
384                 unsigned nr;
385                 struct vmx_msr_entry guest[NR_AUTOLOAD_MSRS];
386                 struct vmx_msr_entry host[NR_AUTOLOAD_MSRS];
387         } msr_autoload;
388         struct {
389                 int           loaded;
390                 u16           fs_sel, gs_sel, ldt_sel;
391                 int           gs_ldt_reload_needed;
392                 int           fs_reload_needed;
393                 unsigned long vmcs_host_cr4;    /* May not match real cr4 */
394         } host_state;
395         struct {
396                 int vm86_active;
397                 ulong save_rflags;
398                 struct kvm_save_segment {
399                         u16 selector;
400                         unsigned long base;
401                         u32 limit;
402                         u32 ar;
403                 } tr, es, ds, fs, gs;
404         } rmode;
405         struct {
406                 u32 bitmask; /* 4 bits per segment (1 bit per field) */
407                 struct kvm_save_segment seg[8];
408         } segment_cache;
409         int vpid;
410         bool emulation_required;
411
412         /* Support for vnmi-less CPUs */
413         int soft_vnmi_blocked;
414         ktime_t entry_time;
415         s64 vnmi_blocked_time;
416         u32 exit_reason;
417
418         bool rdtscp_enabled;
419
420         /* Support for a guest hypervisor (nested VMX) */
421         struct nested_vmx nested;
422 };
423
424 enum segment_cache_field {
425         SEG_FIELD_SEL = 0,
426         SEG_FIELD_BASE = 1,
427         SEG_FIELD_LIMIT = 2,
428         SEG_FIELD_AR = 3,
429
430         SEG_FIELD_NR = 4
431 };
432
433 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
434 {
435         return container_of(vcpu, struct vcpu_vmx, vcpu);
436 }
437
438 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
439 #define FIELD(number, name)     [number] = VMCS12_OFFSET(name)
440 #define FIELD64(number, name)   [number] = VMCS12_OFFSET(name), \
441                                 [number##_HIGH] = VMCS12_OFFSET(name)+4
442
443 static unsigned short vmcs_field_to_offset_table[] = {
444         FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
445         FIELD(GUEST_ES_SELECTOR, guest_es_selector),
446         FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
447         FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
448         FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
449         FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
450         FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
451         FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
452         FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
453         FIELD(HOST_ES_SELECTOR, host_es_selector),
454         FIELD(HOST_CS_SELECTOR, host_cs_selector),
455         FIELD(HOST_SS_SELECTOR, host_ss_selector),
456         FIELD(HOST_DS_SELECTOR, host_ds_selector),
457         FIELD(HOST_FS_SELECTOR, host_fs_selector),
458         FIELD(HOST_GS_SELECTOR, host_gs_selector),
459         FIELD(HOST_TR_SELECTOR, host_tr_selector),
460         FIELD64(IO_BITMAP_A, io_bitmap_a),
461         FIELD64(IO_BITMAP_B, io_bitmap_b),
462         FIELD64(MSR_BITMAP, msr_bitmap),
463         FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
464         FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
465         FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
466         FIELD64(TSC_OFFSET, tsc_offset),
467         FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
468         FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
469         FIELD64(EPT_POINTER, ept_pointer),
470         FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
471         FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
472         FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
473         FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
474         FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
475         FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
476         FIELD64(GUEST_PDPTR0, guest_pdptr0),
477         FIELD64(GUEST_PDPTR1, guest_pdptr1),
478         FIELD64(GUEST_PDPTR2, guest_pdptr2),
479         FIELD64(GUEST_PDPTR3, guest_pdptr3),
480         FIELD64(HOST_IA32_PAT, host_ia32_pat),
481         FIELD64(HOST_IA32_EFER, host_ia32_efer),
482         FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
483         FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
484         FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
485         FIELD(EXCEPTION_BITMAP, exception_bitmap),
486         FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
487         FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
488         FIELD(CR3_TARGET_COUNT, cr3_target_count),
489         FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
490         FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
491         FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
492         FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
493         FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
494         FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
495         FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
496         FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
497         FIELD(TPR_THRESHOLD, tpr_threshold),
498         FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
499         FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
500         FIELD(VM_EXIT_REASON, vm_exit_reason),
501         FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
502         FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
503         FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
504         FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
505         FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
506         FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
507         FIELD(GUEST_ES_LIMIT, guest_es_limit),
508         FIELD(GUEST_CS_LIMIT, guest_cs_limit),
509         FIELD(GUEST_SS_LIMIT, guest_ss_limit),
510         FIELD(GUEST_DS_LIMIT, guest_ds_limit),
511         FIELD(GUEST_FS_LIMIT, guest_fs_limit),
512         FIELD(GUEST_GS_LIMIT, guest_gs_limit),
513         FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
514         FIELD(GUEST_TR_LIMIT, guest_tr_limit),
515         FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
516         FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
517         FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
518         FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
519         FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
520         FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
521         FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
522         FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
523         FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
524         FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
525         FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
526         FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
527         FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
528         FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
529         FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
530         FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
531         FIELD(CR0_READ_SHADOW, cr0_read_shadow),
532         FIELD(CR4_READ_SHADOW, cr4_read_shadow),
533         FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
534         FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
535         FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
536         FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
537         FIELD(EXIT_QUALIFICATION, exit_qualification),
538         FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
539         FIELD(GUEST_CR0, guest_cr0),
540         FIELD(GUEST_CR3, guest_cr3),
541         FIELD(GUEST_CR4, guest_cr4),
542         FIELD(GUEST_ES_BASE, guest_es_base),
543         FIELD(GUEST_CS_BASE, guest_cs_base),
544         FIELD(GUEST_SS_BASE, guest_ss_base),
545         FIELD(GUEST_DS_BASE, guest_ds_base),
546         FIELD(GUEST_FS_BASE, guest_fs_base),
547         FIELD(GUEST_GS_BASE, guest_gs_base),
548         FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
549         FIELD(GUEST_TR_BASE, guest_tr_base),
550         FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
551         FIELD(GUEST_IDTR_BASE, guest_idtr_base),
552         FIELD(GUEST_DR7, guest_dr7),
553         FIELD(GUEST_RSP, guest_rsp),
554         FIELD(GUEST_RIP, guest_rip),
555         FIELD(GUEST_RFLAGS, guest_rflags),
556         FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
557         FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
558         FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
559         FIELD(HOST_CR0, host_cr0),
560         FIELD(HOST_CR3, host_cr3),
561         FIELD(HOST_CR4, host_cr4),
562         FIELD(HOST_FS_BASE, host_fs_base),
563         FIELD(HOST_GS_BASE, host_gs_base),
564         FIELD(HOST_TR_BASE, host_tr_base),
565         FIELD(HOST_GDTR_BASE, host_gdtr_base),
566         FIELD(HOST_IDTR_BASE, host_idtr_base),
567         FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
568         FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
569         FIELD(HOST_RSP, host_rsp),
570         FIELD(HOST_RIP, host_rip),
571 };
572 static const int max_vmcs_field = ARRAY_SIZE(vmcs_field_to_offset_table);
573
574 static inline short vmcs_field_to_offset(unsigned long field)
575 {
576         if (field >= max_vmcs_field || vmcs_field_to_offset_table[field] == 0)
577                 return -1;
578         return vmcs_field_to_offset_table[field];
579 }
580
581 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
582 {
583         return to_vmx(vcpu)->nested.current_vmcs12;
584 }
585
586 static struct page *nested_get_page(struct kvm_vcpu *vcpu, gpa_t addr)
587 {
588         struct page *page = gfn_to_page(vcpu->kvm, addr >> PAGE_SHIFT);
589         if (is_error_page(page)) {
590                 kvm_release_page_clean(page);
591                 return NULL;
592         }
593         return page;
594 }
595
596 static void nested_release_page(struct page *page)
597 {
598         kvm_release_page_dirty(page);
599 }
600
601 static void nested_release_page_clean(struct page *page)
602 {
603         kvm_release_page_clean(page);
604 }
605
606 static u64 construct_eptp(unsigned long root_hpa);
607 static void kvm_cpu_vmxon(u64 addr);
608 static void kvm_cpu_vmxoff(void);
609 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3);
610 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr);
611
612 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
613 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
614 /*
615  * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
616  * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
617  */
618 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
619 static DEFINE_PER_CPU(struct desc_ptr, host_gdt);
620
621 static unsigned long *vmx_io_bitmap_a;
622 static unsigned long *vmx_io_bitmap_b;
623 static unsigned long *vmx_msr_bitmap_legacy;
624 static unsigned long *vmx_msr_bitmap_longmode;
625
626 static bool cpu_has_load_ia32_efer;
627 static bool cpu_has_load_perf_global_ctrl;
628
629 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
630 static DEFINE_SPINLOCK(vmx_vpid_lock);
631
632 static struct vmcs_config {
633         int size;
634         int order;
635         u32 revision_id;
636         u32 pin_based_exec_ctrl;
637         u32 cpu_based_exec_ctrl;
638         u32 cpu_based_2nd_exec_ctrl;
639         u32 vmexit_ctrl;
640         u32 vmentry_ctrl;
641 } vmcs_config;
642
643 static struct vmx_capability {
644         u32 ept;
645         u32 vpid;
646 } vmx_capability;
647
648 #define VMX_SEGMENT_FIELD(seg)                                  \
649         [VCPU_SREG_##seg] = {                                   \
650                 .selector = GUEST_##seg##_SELECTOR,             \
651                 .base = GUEST_##seg##_BASE,                     \
652                 .limit = GUEST_##seg##_LIMIT,                   \
653                 .ar_bytes = GUEST_##seg##_AR_BYTES,             \
654         }
655
656 static struct kvm_vmx_segment_field {
657         unsigned selector;
658         unsigned base;
659         unsigned limit;
660         unsigned ar_bytes;
661 } kvm_vmx_segment_fields[] = {
662         VMX_SEGMENT_FIELD(CS),
663         VMX_SEGMENT_FIELD(DS),
664         VMX_SEGMENT_FIELD(ES),
665         VMX_SEGMENT_FIELD(FS),
666         VMX_SEGMENT_FIELD(GS),
667         VMX_SEGMENT_FIELD(SS),
668         VMX_SEGMENT_FIELD(TR),
669         VMX_SEGMENT_FIELD(LDTR),
670 };
671
672 static u64 host_efer;
673
674 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
675
676 /*
677  * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
678  * away by decrementing the array size.
679  */
680 static const u32 vmx_msr_index[] = {
681 #ifdef CONFIG_X86_64
682         MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
683 #endif
684         MSR_EFER, MSR_TSC_AUX, MSR_STAR,
685 };
686 #define NR_VMX_MSR ARRAY_SIZE(vmx_msr_index)
687
688 static inline bool is_page_fault(u32 intr_info)
689 {
690         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
691                              INTR_INFO_VALID_MASK)) ==
692                 (INTR_TYPE_HARD_EXCEPTION | PF_VECTOR | INTR_INFO_VALID_MASK);
693 }
694
695 static inline bool is_no_device(u32 intr_info)
696 {
697         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
698                              INTR_INFO_VALID_MASK)) ==
699                 (INTR_TYPE_HARD_EXCEPTION | NM_VECTOR | INTR_INFO_VALID_MASK);
700 }
701
702 static inline bool is_invalid_opcode(u32 intr_info)
703 {
704         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
705                              INTR_INFO_VALID_MASK)) ==
706                 (INTR_TYPE_HARD_EXCEPTION | UD_VECTOR | INTR_INFO_VALID_MASK);
707 }
708
709 static inline bool is_external_interrupt(u32 intr_info)
710 {
711         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
712                 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
713 }
714
715 static inline bool is_machine_check(u32 intr_info)
716 {
717         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
718                              INTR_INFO_VALID_MASK)) ==
719                 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
720 }
721
722 static inline bool cpu_has_vmx_msr_bitmap(void)
723 {
724         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
725 }
726
727 static inline bool cpu_has_vmx_tpr_shadow(void)
728 {
729         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
730 }
731
732 static inline bool vm_need_tpr_shadow(struct kvm *kvm)
733 {
734         return (cpu_has_vmx_tpr_shadow()) && (irqchip_in_kernel(kvm));
735 }
736
737 static inline bool cpu_has_secondary_exec_ctrls(void)
738 {
739         return vmcs_config.cpu_based_exec_ctrl &
740                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
741 }
742
743 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
744 {
745         return vmcs_config.cpu_based_2nd_exec_ctrl &
746                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
747 }
748
749 static inline bool cpu_has_vmx_flexpriority(void)
750 {
751         return cpu_has_vmx_tpr_shadow() &&
752                 cpu_has_vmx_virtualize_apic_accesses();
753 }
754
755 static inline bool cpu_has_vmx_ept_execute_only(void)
756 {
757         return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
758 }
759
760 static inline bool cpu_has_vmx_eptp_uncacheable(void)
761 {
762         return vmx_capability.ept & VMX_EPTP_UC_BIT;
763 }
764
765 static inline bool cpu_has_vmx_eptp_writeback(void)
766 {
767         return vmx_capability.ept & VMX_EPTP_WB_BIT;
768 }
769
770 static inline bool cpu_has_vmx_ept_2m_page(void)
771 {
772         return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
773 }
774
775 static inline bool cpu_has_vmx_ept_1g_page(void)
776 {
777         return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
778 }
779
780 static inline bool cpu_has_vmx_ept_4levels(void)
781 {
782         return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
783 }
784
785 static inline bool cpu_has_vmx_invept_individual_addr(void)
786 {
787         return vmx_capability.ept & VMX_EPT_EXTENT_INDIVIDUAL_BIT;
788 }
789
790 static inline bool cpu_has_vmx_invept_context(void)
791 {
792         return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
793 }
794
795 static inline bool cpu_has_vmx_invept_global(void)
796 {
797         return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
798 }
799
800 static inline bool cpu_has_vmx_invvpid_single(void)
801 {
802         return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
803 }
804
805 static inline bool cpu_has_vmx_invvpid_global(void)
806 {
807         return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
808 }
809
810 static inline bool cpu_has_vmx_ept(void)
811 {
812         return vmcs_config.cpu_based_2nd_exec_ctrl &
813                 SECONDARY_EXEC_ENABLE_EPT;
814 }
815
816 static inline bool cpu_has_vmx_unrestricted_guest(void)
817 {
818         return vmcs_config.cpu_based_2nd_exec_ctrl &
819                 SECONDARY_EXEC_UNRESTRICTED_GUEST;
820 }
821
822 static inline bool cpu_has_vmx_ple(void)
823 {
824         return vmcs_config.cpu_based_2nd_exec_ctrl &
825                 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
826 }
827
828 static inline bool vm_need_virtualize_apic_accesses(struct kvm *kvm)
829 {
830         return flexpriority_enabled && irqchip_in_kernel(kvm);
831 }
832
833 static inline bool cpu_has_vmx_vpid(void)
834 {
835         return vmcs_config.cpu_based_2nd_exec_ctrl &
836                 SECONDARY_EXEC_ENABLE_VPID;
837 }
838
839 static inline bool cpu_has_vmx_rdtscp(void)
840 {
841         return vmcs_config.cpu_based_2nd_exec_ctrl &
842                 SECONDARY_EXEC_RDTSCP;
843 }
844
845 static inline bool cpu_has_virtual_nmis(void)
846 {
847         return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
848 }
849
850 static inline bool cpu_has_vmx_wbinvd_exit(void)
851 {
852         return vmcs_config.cpu_based_2nd_exec_ctrl &
853                 SECONDARY_EXEC_WBINVD_EXITING;
854 }
855
856 static inline bool report_flexpriority(void)
857 {
858         return flexpriority_enabled;
859 }
860
861 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
862 {
863         return vmcs12->cpu_based_vm_exec_control & bit;
864 }
865
866 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
867 {
868         return (vmcs12->cpu_based_vm_exec_control &
869                         CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
870                 (vmcs12->secondary_vm_exec_control & bit);
871 }
872
873 static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12,
874         struct kvm_vcpu *vcpu)
875 {
876         return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
877 }
878
879 static inline bool is_exception(u32 intr_info)
880 {
881         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
882                 == (INTR_TYPE_HARD_EXCEPTION | INTR_INFO_VALID_MASK);
883 }
884
885 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu);
886 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
887                         struct vmcs12 *vmcs12,
888                         u32 reason, unsigned long qualification);
889
890 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
891 {
892         int i;
893
894         for (i = 0; i < vmx->nmsrs; ++i)
895                 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
896                         return i;
897         return -1;
898 }
899
900 static inline void __invvpid(int ext, u16 vpid, gva_t gva)
901 {
902     struct {
903         u64 vpid : 16;
904         u64 rsvd : 48;
905         u64 gva;
906     } operand = { vpid, 0, gva };
907
908     asm volatile (__ex(ASM_VMX_INVVPID)
909                   /* CF==1 or ZF==1 --> rc = -1 */
910                   "; ja 1f ; ud2 ; 1:"
911                   : : "a"(&operand), "c"(ext) : "cc", "memory");
912 }
913
914 static inline void __invept(int ext, u64 eptp, gpa_t gpa)
915 {
916         struct {
917                 u64 eptp, gpa;
918         } operand = {eptp, gpa};
919
920         asm volatile (__ex(ASM_VMX_INVEPT)
921                         /* CF==1 or ZF==1 --> rc = -1 */
922                         "; ja 1f ; ud2 ; 1:\n"
923                         : : "a" (&operand), "c" (ext) : "cc", "memory");
924 }
925
926 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
927 {
928         int i;
929
930         i = __find_msr_index(vmx, msr);
931         if (i >= 0)
932                 return &vmx->guest_msrs[i];
933         return NULL;
934 }
935
936 static void vmcs_clear(struct vmcs *vmcs)
937 {
938         u64 phys_addr = __pa(vmcs);
939         u8 error;
940
941         asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
942                       : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
943                       : "cc", "memory");
944         if (error)
945                 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
946                        vmcs, phys_addr);
947 }
948
949 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
950 {
951         vmcs_clear(loaded_vmcs->vmcs);
952         loaded_vmcs->cpu = -1;
953         loaded_vmcs->launched = 0;
954 }
955
956 static void vmcs_load(struct vmcs *vmcs)
957 {
958         u64 phys_addr = __pa(vmcs);
959         u8 error;
960
961         asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
962                         : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
963                         : "cc", "memory");
964         if (error)
965                 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
966                        vmcs, phys_addr);
967 }
968
969 static void __loaded_vmcs_clear(void *arg)
970 {
971         struct loaded_vmcs *loaded_vmcs = arg;
972         int cpu = raw_smp_processor_id();
973
974         if (loaded_vmcs->cpu != cpu)
975                 return; /* vcpu migration can race with cpu offline */
976         if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
977                 per_cpu(current_vmcs, cpu) = NULL;
978         list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
979         loaded_vmcs_init(loaded_vmcs);
980 }
981
982 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
983 {
984         if (loaded_vmcs->cpu != -1)
985                 smp_call_function_single(
986                         loaded_vmcs->cpu, __loaded_vmcs_clear, loaded_vmcs, 1);
987 }
988
989 static inline void vpid_sync_vcpu_single(struct vcpu_vmx *vmx)
990 {
991         if (vmx->vpid == 0)
992                 return;
993
994         if (cpu_has_vmx_invvpid_single())
995                 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vmx->vpid, 0);
996 }
997
998 static inline void vpid_sync_vcpu_global(void)
999 {
1000         if (cpu_has_vmx_invvpid_global())
1001                 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
1002 }
1003
1004 static inline void vpid_sync_context(struct vcpu_vmx *vmx)
1005 {
1006         if (cpu_has_vmx_invvpid_single())
1007                 vpid_sync_vcpu_single(vmx);
1008         else
1009                 vpid_sync_vcpu_global();
1010 }
1011
1012 static inline void ept_sync_global(void)
1013 {
1014         if (cpu_has_vmx_invept_global())
1015                 __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
1016 }
1017
1018 static inline void ept_sync_context(u64 eptp)
1019 {
1020         if (enable_ept) {
1021                 if (cpu_has_vmx_invept_context())
1022                         __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
1023                 else
1024                         ept_sync_global();
1025         }
1026 }
1027
1028 static inline void ept_sync_individual_addr(u64 eptp, gpa_t gpa)
1029 {
1030         if (enable_ept) {
1031                 if (cpu_has_vmx_invept_individual_addr())
1032                         __invept(VMX_EPT_EXTENT_INDIVIDUAL_ADDR,
1033                                         eptp, gpa);
1034                 else
1035                         ept_sync_context(eptp);
1036         }
1037 }
1038
1039 static __always_inline unsigned long vmcs_readl(unsigned long field)
1040 {
1041         unsigned long value;
1042
1043         asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
1044                       : "=a"(value) : "d"(field) : "cc");
1045         return value;
1046 }
1047
1048 static __always_inline u16 vmcs_read16(unsigned long field)
1049 {
1050         return vmcs_readl(field);
1051 }
1052
1053 static __always_inline u32 vmcs_read32(unsigned long field)
1054 {
1055         return vmcs_readl(field);
1056 }
1057
1058 static __always_inline u64 vmcs_read64(unsigned long field)
1059 {
1060 #ifdef CONFIG_X86_64
1061         return vmcs_readl(field);
1062 #else
1063         return vmcs_readl(field) | ((u64)vmcs_readl(field+1) << 32);
1064 #endif
1065 }
1066
1067 static noinline void vmwrite_error(unsigned long field, unsigned long value)
1068 {
1069         printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
1070                field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
1071         dump_stack();
1072 }
1073
1074 static void vmcs_writel(unsigned long field, unsigned long value)
1075 {
1076         u8 error;
1077
1078         asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
1079                        : "=q"(error) : "a"(value), "d"(field) : "cc");
1080         if (unlikely(error))
1081                 vmwrite_error(field, value);
1082 }
1083
1084 static void vmcs_write16(unsigned long field, u16 value)
1085 {
1086         vmcs_writel(field, value);
1087 }
1088
1089 static void vmcs_write32(unsigned long field, u32 value)
1090 {
1091         vmcs_writel(field, value);
1092 }
1093
1094 static void vmcs_write64(unsigned long field, u64 value)
1095 {
1096         vmcs_writel(field, value);
1097 #ifndef CONFIG_X86_64
1098         asm volatile ("");
1099         vmcs_writel(field+1, value >> 32);
1100 #endif
1101 }
1102
1103 static void vmcs_clear_bits(unsigned long field, u32 mask)
1104 {
1105         vmcs_writel(field, vmcs_readl(field) & ~mask);
1106 }
1107
1108 static void vmcs_set_bits(unsigned long field, u32 mask)
1109 {
1110         vmcs_writel(field, vmcs_readl(field) | mask);
1111 }
1112
1113 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
1114 {
1115         vmx->segment_cache.bitmask = 0;
1116 }
1117
1118 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
1119                                        unsigned field)
1120 {
1121         bool ret;
1122         u32 mask = 1 << (seg * SEG_FIELD_NR + field);
1123
1124         if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
1125                 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
1126                 vmx->segment_cache.bitmask = 0;
1127         }
1128         ret = vmx->segment_cache.bitmask & mask;
1129         vmx->segment_cache.bitmask |= mask;
1130         return ret;
1131 }
1132
1133 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
1134 {
1135         u16 *p = &vmx->segment_cache.seg[seg].selector;
1136
1137         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
1138                 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
1139         return *p;
1140 }
1141
1142 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
1143 {
1144         ulong *p = &vmx->segment_cache.seg[seg].base;
1145
1146         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
1147                 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
1148         return *p;
1149 }
1150
1151 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
1152 {
1153         u32 *p = &vmx->segment_cache.seg[seg].limit;
1154
1155         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
1156                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
1157         return *p;
1158 }
1159
1160 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
1161 {
1162         u32 *p = &vmx->segment_cache.seg[seg].ar;
1163
1164         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
1165                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
1166         return *p;
1167 }
1168
1169 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
1170 {
1171         u32 eb;
1172
1173         eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
1174              (1u << NM_VECTOR) | (1u << DB_VECTOR) | (1u << AC_VECTOR);
1175         if ((vcpu->guest_debug &
1176              (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
1177             (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
1178                 eb |= 1u << BP_VECTOR;
1179         if (to_vmx(vcpu)->rmode.vm86_active)
1180                 eb = ~0;
1181         if (enable_ept)
1182                 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
1183         if (vcpu->fpu_active)
1184                 eb &= ~(1u << NM_VECTOR);
1185
1186         /* When we are running a nested L2 guest and L1 specified for it a
1187          * certain exception bitmap, we must trap the same exceptions and pass
1188          * them to L1. When running L2, we will only handle the exceptions
1189          * specified above if L1 did not want them.
1190          */
1191         if (is_guest_mode(vcpu))
1192                 eb |= get_vmcs12(vcpu)->exception_bitmap;
1193
1194         vmcs_write32(EXCEPTION_BITMAP, eb);
1195 }
1196
1197 static void clear_atomic_switch_msr_special(unsigned long entry,
1198                 unsigned long exit)
1199 {
1200         vmcs_clear_bits(VM_ENTRY_CONTROLS, entry);
1201         vmcs_clear_bits(VM_EXIT_CONTROLS, exit);
1202 }
1203
1204 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
1205 {
1206         unsigned i;
1207         struct msr_autoload *m = &vmx->msr_autoload;
1208
1209         switch (msr) {
1210         case MSR_EFER:
1211                 if (cpu_has_load_ia32_efer) {
1212                         clear_atomic_switch_msr_special(VM_ENTRY_LOAD_IA32_EFER,
1213                                         VM_EXIT_LOAD_IA32_EFER);
1214                         return;
1215                 }
1216                 break;
1217         case MSR_CORE_PERF_GLOBAL_CTRL:
1218                 if (cpu_has_load_perf_global_ctrl) {
1219                         clear_atomic_switch_msr_special(
1220                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1221                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
1222                         return;
1223                 }
1224                 break;
1225         }
1226
1227         for (i = 0; i < m->nr; ++i)
1228                 if (m->guest[i].index == msr)
1229                         break;
1230
1231         if (i == m->nr)
1232                 return;
1233         --m->nr;
1234         m->guest[i] = m->guest[m->nr];
1235         m->host[i] = m->host[m->nr];
1236         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1237         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1238 }
1239
1240 static void add_atomic_switch_msr_special(unsigned long entry,
1241                 unsigned long exit, unsigned long guest_val_vmcs,
1242                 unsigned long host_val_vmcs, u64 guest_val, u64 host_val)
1243 {
1244         vmcs_write64(guest_val_vmcs, guest_val);
1245         vmcs_write64(host_val_vmcs, host_val);
1246         vmcs_set_bits(VM_ENTRY_CONTROLS, entry);
1247         vmcs_set_bits(VM_EXIT_CONTROLS, exit);
1248 }
1249
1250 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
1251                                   u64 guest_val, u64 host_val)
1252 {
1253         unsigned i;
1254         struct msr_autoload *m = &vmx->msr_autoload;
1255
1256         switch (msr) {
1257         case MSR_EFER:
1258                 if (cpu_has_load_ia32_efer) {
1259                         add_atomic_switch_msr_special(VM_ENTRY_LOAD_IA32_EFER,
1260                                         VM_EXIT_LOAD_IA32_EFER,
1261                                         GUEST_IA32_EFER,
1262                                         HOST_IA32_EFER,
1263                                         guest_val, host_val);
1264                         return;
1265                 }
1266                 break;
1267         case MSR_CORE_PERF_GLOBAL_CTRL:
1268                 if (cpu_has_load_perf_global_ctrl) {
1269                         add_atomic_switch_msr_special(
1270                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1271                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
1272                                         GUEST_IA32_PERF_GLOBAL_CTRL,
1273                                         HOST_IA32_PERF_GLOBAL_CTRL,
1274                                         guest_val, host_val);
1275                         return;
1276                 }
1277                 break;
1278         }
1279
1280         for (i = 0; i < m->nr; ++i)
1281                 if (m->guest[i].index == msr)
1282                         break;
1283
1284         if (i == NR_AUTOLOAD_MSRS) {
1285                 printk_once(KERN_WARNING"Not enough mst switch entries. "
1286                                 "Can't add msr %x\n", msr);
1287                 return;
1288         } else if (i == m->nr) {
1289                 ++m->nr;
1290                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1291                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1292         }
1293
1294         m->guest[i].index = msr;
1295         m->guest[i].value = guest_val;
1296         m->host[i].index = msr;
1297         m->host[i].value = host_val;
1298 }
1299
1300 static void reload_tss(void)
1301 {
1302         /*
1303          * VT restores TR but not its size.  Useless.
1304          */
1305         struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
1306         struct desc_struct *descs;
1307
1308         descs = (void *)gdt->address;
1309         descs[GDT_ENTRY_TSS].type = 9; /* available TSS */
1310         load_TR_desc();
1311 }
1312
1313 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
1314 {
1315         u64 guest_efer;
1316         u64 ignore_bits;
1317
1318         guest_efer = vmx->vcpu.arch.efer;
1319
1320         /*
1321          * NX is emulated; LMA and LME handled by hardware; SCE meaninless
1322          * outside long mode
1323          */
1324         ignore_bits = EFER_NX | EFER_SCE;
1325 #ifdef CONFIG_X86_64
1326         ignore_bits |= EFER_LMA | EFER_LME;
1327         /* SCE is meaningful only in long mode on Intel */
1328         if (guest_efer & EFER_LMA)
1329                 ignore_bits &= ~(u64)EFER_SCE;
1330 #endif
1331         guest_efer &= ~ignore_bits;
1332         guest_efer |= host_efer & ignore_bits;
1333         vmx->guest_msrs[efer_offset].data = guest_efer;
1334         vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
1335
1336         clear_atomic_switch_msr(vmx, MSR_EFER);
1337         /* On ept, can't emulate nx, and must switch nx atomically */
1338         if (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX)) {
1339                 guest_efer = vmx->vcpu.arch.efer;
1340                 if (!(guest_efer & EFER_LMA))
1341                         guest_efer &= ~EFER_LME;
1342                 add_atomic_switch_msr(vmx, MSR_EFER, guest_efer, host_efer);
1343                 return false;
1344         }
1345
1346         return true;
1347 }
1348
1349 static unsigned long segment_base(u16 selector)
1350 {
1351         struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
1352         struct desc_struct *d;
1353         unsigned long table_base;
1354         unsigned long v;
1355
1356         if (!(selector & ~3))
1357                 return 0;
1358
1359         table_base = gdt->address;
1360
1361         if (selector & 4) {           /* from ldt */
1362                 u16 ldt_selector = kvm_read_ldt();
1363
1364                 if (!(ldt_selector & ~3))
1365                         return 0;
1366
1367                 table_base = segment_base(ldt_selector);
1368         }
1369         d = (struct desc_struct *)(table_base + (selector & ~7));
1370         v = get_desc_base(d);
1371 #ifdef CONFIG_X86_64
1372        if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
1373                v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
1374 #endif
1375         return v;
1376 }
1377
1378 static inline unsigned long kvm_read_tr_base(void)
1379 {
1380         u16 tr;
1381         asm("str %0" : "=g"(tr));
1382         return segment_base(tr);
1383 }
1384
1385 static void vmx_save_host_state(struct kvm_vcpu *vcpu)
1386 {
1387         struct vcpu_vmx *vmx = to_vmx(vcpu);
1388         int i;
1389
1390         if (vmx->host_state.loaded)
1391                 return;
1392
1393         vmx->host_state.loaded = 1;
1394         /*
1395          * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
1396          * allow segment selectors with cpl > 0 or ti == 1.
1397          */
1398         vmx->host_state.ldt_sel = kvm_read_ldt();
1399         vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
1400         savesegment(fs, vmx->host_state.fs_sel);
1401         if (!(vmx->host_state.fs_sel & 7)) {
1402                 vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
1403                 vmx->host_state.fs_reload_needed = 0;
1404         } else {
1405                 vmcs_write16(HOST_FS_SELECTOR, 0);
1406                 vmx->host_state.fs_reload_needed = 1;
1407         }
1408         savesegment(gs, vmx->host_state.gs_sel);
1409         if (!(vmx->host_state.gs_sel & 7))
1410                 vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
1411         else {
1412                 vmcs_write16(HOST_GS_SELECTOR, 0);
1413                 vmx->host_state.gs_ldt_reload_needed = 1;
1414         }
1415
1416 #ifdef CONFIG_X86_64
1417         vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
1418         vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
1419 #else
1420         vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
1421         vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
1422 #endif
1423
1424 #ifdef CONFIG_X86_64
1425         rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1426         if (is_long_mode(&vmx->vcpu))
1427                 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1428 #endif
1429         for (i = 0; i < vmx->save_nmsrs; ++i)
1430                 kvm_set_shared_msr(vmx->guest_msrs[i].index,
1431                                    vmx->guest_msrs[i].data,
1432                                    vmx->guest_msrs[i].mask);
1433 }
1434
1435 static void __vmx_load_host_state(struct vcpu_vmx *vmx)
1436 {
1437         if (!vmx->host_state.loaded)
1438                 return;
1439
1440         ++vmx->vcpu.stat.host_state_reload;
1441         vmx->host_state.loaded = 0;
1442 #ifdef CONFIG_X86_64
1443         if (is_long_mode(&vmx->vcpu))
1444                 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1445 #endif
1446         if (vmx->host_state.gs_ldt_reload_needed) {
1447                 kvm_load_ldt(vmx->host_state.ldt_sel);
1448 #ifdef CONFIG_X86_64
1449                 load_gs_index(vmx->host_state.gs_sel);
1450 #else
1451                 loadsegment(gs, vmx->host_state.gs_sel);
1452 #endif
1453         }
1454         if (vmx->host_state.fs_reload_needed)
1455                 loadsegment(fs, vmx->host_state.fs_sel);
1456         reload_tss();
1457 #ifdef CONFIG_X86_64
1458         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1459 #endif
1460         if (__thread_has_fpu(current))
1461                 clts();
1462         load_gdt(&__get_cpu_var(host_gdt));
1463 }
1464
1465 static void vmx_load_host_state(struct vcpu_vmx *vmx)
1466 {
1467         preempt_disable();
1468         __vmx_load_host_state(vmx);
1469         preempt_enable();
1470 }
1471
1472 /*
1473  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1474  * vcpu mutex is already taken.
1475  */
1476 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1477 {
1478         struct vcpu_vmx *vmx = to_vmx(vcpu);
1479         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
1480
1481         if (!vmm_exclusive)
1482                 kvm_cpu_vmxon(phys_addr);
1483         else if (vmx->loaded_vmcs->cpu != cpu)
1484                 loaded_vmcs_clear(vmx->loaded_vmcs);
1485
1486         if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
1487                 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1488                 vmcs_load(vmx->loaded_vmcs->vmcs);
1489         }
1490
1491         if (vmx->loaded_vmcs->cpu != cpu) {
1492                 struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
1493                 unsigned long sysenter_esp;
1494
1495                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1496                 local_irq_disable();
1497                 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1498                          &per_cpu(loaded_vmcss_on_cpu, cpu));
1499                 local_irq_enable();
1500
1501                 /*
1502                  * Linux uses per-cpu TSS and GDT, so set these when switching
1503                  * processors.
1504                  */
1505                 vmcs_writel(HOST_TR_BASE, kvm_read_tr_base()); /* 22.2.4 */
1506                 vmcs_writel(HOST_GDTR_BASE, gdt->address);   /* 22.2.4 */
1507
1508                 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1509                 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1510                 vmx->loaded_vmcs->cpu = cpu;
1511         }
1512 }
1513
1514 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1515 {
1516         __vmx_load_host_state(to_vmx(vcpu));
1517         if (!vmm_exclusive) {
1518                 __loaded_vmcs_clear(to_vmx(vcpu)->loaded_vmcs);
1519                 vcpu->cpu = -1;
1520                 kvm_cpu_vmxoff();
1521         }
1522 }
1523
1524 static void vmx_fpu_activate(struct kvm_vcpu *vcpu)
1525 {
1526         ulong cr0;
1527
1528         if (vcpu->fpu_active)
1529                 return;
1530         vcpu->fpu_active = 1;
1531         cr0 = vmcs_readl(GUEST_CR0);
1532         cr0 &= ~(X86_CR0_TS | X86_CR0_MP);
1533         cr0 |= kvm_read_cr0_bits(vcpu, X86_CR0_TS | X86_CR0_MP);
1534         vmcs_writel(GUEST_CR0, cr0);
1535         update_exception_bitmap(vcpu);
1536         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
1537         if (is_guest_mode(vcpu))
1538                 vcpu->arch.cr0_guest_owned_bits &=
1539                         ~get_vmcs12(vcpu)->cr0_guest_host_mask;
1540         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
1541 }
1542
1543 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
1544
1545 /*
1546  * Return the cr0 value that a nested guest would read. This is a combination
1547  * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
1548  * its hypervisor (cr0_read_shadow).
1549  */
1550 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
1551 {
1552         return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
1553                 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
1554 }
1555 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
1556 {
1557         return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
1558                 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
1559 }
1560
1561 static void vmx_fpu_deactivate(struct kvm_vcpu *vcpu)
1562 {
1563         /* Note that there is no vcpu->fpu_active = 0 here. The caller must
1564          * set this *before* calling this function.
1565          */
1566         vmx_decache_cr0_guest_bits(vcpu);
1567         vmcs_set_bits(GUEST_CR0, X86_CR0_TS | X86_CR0_MP);
1568         update_exception_bitmap(vcpu);
1569         vcpu->arch.cr0_guest_owned_bits = 0;
1570         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
1571         if (is_guest_mode(vcpu)) {
1572                 /*
1573                  * L1's specified read shadow might not contain the TS bit,
1574                  * so now that we turned on shadowing of this bit, we need to
1575                  * set this bit of the shadow. Like in nested_vmx_run we need
1576                  * nested_read_cr0(vmcs12), but vmcs12->guest_cr0 is not yet
1577                  * up-to-date here because we just decached cr0.TS (and we'll
1578                  * only update vmcs12->guest_cr0 on nested exit).
1579                  */
1580                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1581                 vmcs12->guest_cr0 = (vmcs12->guest_cr0 & ~X86_CR0_TS) |
1582                         (vcpu->arch.cr0 & X86_CR0_TS);
1583                 vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
1584         } else
1585                 vmcs_writel(CR0_READ_SHADOW, vcpu->arch.cr0);
1586 }
1587
1588 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1589 {
1590         unsigned long rflags, save_rflags;
1591
1592         if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
1593                 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1594                 rflags = vmcs_readl(GUEST_RFLAGS);
1595                 if (to_vmx(vcpu)->rmode.vm86_active) {
1596                         rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1597                         save_rflags = to_vmx(vcpu)->rmode.save_rflags;
1598                         rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1599                 }
1600                 to_vmx(vcpu)->rflags = rflags;
1601         }
1602         return to_vmx(vcpu)->rflags;
1603 }
1604
1605 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1606 {
1607         __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1608         __clear_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
1609         to_vmx(vcpu)->rflags = rflags;
1610         if (to_vmx(vcpu)->rmode.vm86_active) {
1611                 to_vmx(vcpu)->rmode.save_rflags = rflags;
1612                 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1613         }
1614         vmcs_writel(GUEST_RFLAGS, rflags);
1615 }
1616
1617 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1618 {
1619         u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1620         int ret = 0;
1621
1622         if (interruptibility & GUEST_INTR_STATE_STI)
1623                 ret |= KVM_X86_SHADOW_INT_STI;
1624         if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1625                 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1626
1627         return ret & mask;
1628 }
1629
1630 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1631 {
1632         u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1633         u32 interruptibility = interruptibility_old;
1634
1635         interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1636
1637         if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1638                 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1639         else if (mask & KVM_X86_SHADOW_INT_STI)
1640                 interruptibility |= GUEST_INTR_STATE_STI;
1641
1642         if ((interruptibility != interruptibility_old))
1643                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1644 }
1645
1646 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
1647 {
1648         unsigned long rip;
1649
1650         rip = kvm_rip_read(vcpu);
1651         rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1652         kvm_rip_write(vcpu, rip);
1653
1654         /* skipping an emulated instruction also counts */
1655         vmx_set_interrupt_shadow(vcpu, 0);
1656 }
1657
1658 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1659 {
1660         /* Ensure that we clear the HLT state in the VMCS.  We don't need to
1661          * explicitly skip the instruction because if the HLT state is set, then
1662          * the instruction is already executing and RIP has already been
1663          * advanced. */
1664         if (!yield_on_hlt &&
1665             vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1666                 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1667 }
1668
1669 /*
1670  * KVM wants to inject page-faults which it got to the guest. This function
1671  * checks whether in a nested guest, we need to inject them to L1 or L2.
1672  * This function assumes it is called with the exit reason in vmcs02 being
1673  * a #PF exception (this is the only case in which KVM injects a #PF when L2
1674  * is running).
1675  */
1676 static int nested_pf_handled(struct kvm_vcpu *vcpu)
1677 {
1678         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1679
1680         /* TODO: also check PFEC_MATCH/MASK, not just EB.PF. */
1681         if (!(vmcs12->exception_bitmap & (1u << PF_VECTOR)))
1682                 return 0;
1683
1684         nested_vmx_vmexit(vcpu);
1685         return 1;
1686 }
1687
1688 static void vmx_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
1689                                 bool has_error_code, u32 error_code,
1690                                 bool reinject)
1691 {
1692         struct vcpu_vmx *vmx = to_vmx(vcpu);
1693         u32 intr_info = nr | INTR_INFO_VALID_MASK;
1694
1695         if (nr == PF_VECTOR && is_guest_mode(vcpu) &&
1696                 nested_pf_handled(vcpu))
1697                 return;
1698
1699         if (has_error_code) {
1700                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1701                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1702         }
1703
1704         if (vmx->rmode.vm86_active) {
1705                 int inc_eip = 0;
1706                 if (kvm_exception_is_soft(nr))
1707                         inc_eip = vcpu->arch.event_exit_inst_len;
1708                 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
1709                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
1710                 return;
1711         }
1712
1713         if (kvm_exception_is_soft(nr)) {
1714                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1715                              vmx->vcpu.arch.event_exit_inst_len);
1716                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1717         } else
1718                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1719
1720         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1721         vmx_clear_hlt(vcpu);
1722 }
1723
1724 static bool vmx_rdtscp_supported(void)
1725 {
1726         return cpu_has_vmx_rdtscp();
1727 }
1728
1729 /*
1730  * Swap MSR entry in host/guest MSR entry array.
1731  */
1732 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
1733 {
1734         struct shared_msr_entry tmp;
1735
1736         tmp = vmx->guest_msrs[to];
1737         vmx->guest_msrs[to] = vmx->guest_msrs[from];
1738         vmx->guest_msrs[from] = tmp;
1739 }
1740
1741 /*
1742  * Set up the vmcs to automatically save and restore system
1743  * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
1744  * mode, as fiddling with msrs is very expensive.
1745  */
1746 static void setup_msrs(struct vcpu_vmx *vmx)
1747 {
1748         int save_nmsrs, index;
1749         unsigned long *msr_bitmap;
1750
1751         vmx_load_host_state(vmx);
1752         save_nmsrs = 0;
1753 #ifdef CONFIG_X86_64
1754         if (is_long_mode(&vmx->vcpu)) {
1755                 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
1756                 if (index >= 0)
1757                         move_msr_up(vmx, index, save_nmsrs++);
1758                 index = __find_msr_index(vmx, MSR_LSTAR);
1759                 if (index >= 0)
1760                         move_msr_up(vmx, index, save_nmsrs++);
1761                 index = __find_msr_index(vmx, MSR_CSTAR);
1762                 if (index >= 0)
1763                         move_msr_up(vmx, index, save_nmsrs++);
1764                 index = __find_msr_index(vmx, MSR_TSC_AUX);
1765                 if (index >= 0 && vmx->rdtscp_enabled)
1766                         move_msr_up(vmx, index, save_nmsrs++);
1767                 /*
1768                  * MSR_STAR is only needed on long mode guests, and only
1769                  * if efer.sce is enabled.
1770                  */
1771                 index = __find_msr_index(vmx, MSR_STAR);
1772                 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
1773                         move_msr_up(vmx, index, save_nmsrs++);
1774         }
1775 #endif
1776         index = __find_msr_index(vmx, MSR_EFER);
1777         if (index >= 0 && update_transition_efer(vmx, index))
1778                 move_msr_up(vmx, index, save_nmsrs++);
1779
1780         vmx->save_nmsrs = save_nmsrs;
1781
1782         if (cpu_has_vmx_msr_bitmap()) {
1783                 if (is_long_mode(&vmx->vcpu))
1784                         msr_bitmap = vmx_msr_bitmap_longmode;
1785                 else
1786                         msr_bitmap = vmx_msr_bitmap_legacy;
1787
1788                 vmcs_write64(MSR_BITMAP, __pa(msr_bitmap));
1789         }
1790 }
1791
1792 /*
1793  * reads and returns guest's timestamp counter "register"
1794  * guest_tsc = host_tsc + tsc_offset    -- 21.3
1795  */
1796 static u64 guest_read_tsc(void)
1797 {
1798         u64 host_tsc, tsc_offset;
1799
1800         rdtscll(host_tsc);
1801         tsc_offset = vmcs_read64(TSC_OFFSET);
1802         return host_tsc + tsc_offset;
1803 }
1804
1805 /*
1806  * Like guest_read_tsc, but always returns L1's notion of the timestamp
1807  * counter, even if a nested guest (L2) is currently running.
1808  */
1809 u64 vmx_read_l1_tsc(struct kvm_vcpu *vcpu)
1810 {
1811         u64 host_tsc, tsc_offset;
1812
1813         rdtscll(host_tsc);
1814         tsc_offset = is_guest_mode(vcpu) ?
1815                 to_vmx(vcpu)->nested.vmcs01_tsc_offset :
1816                 vmcs_read64(TSC_OFFSET);
1817         return host_tsc + tsc_offset;
1818 }
1819
1820 /*
1821  * Empty call-back. Needs to be implemented when VMX enables the SET_TSC_KHZ
1822  * ioctl. In this case the call-back should update internal vmx state to make
1823  * the changes effective.
1824  */
1825 static void vmx_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
1826 {
1827         /* Nothing to do here */
1828 }
1829
1830 /*
1831  * writes 'offset' into guest's timestamp counter offset register
1832  */
1833 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1834 {
1835         if (is_guest_mode(vcpu)) {
1836                 /*
1837                  * We're here if L1 chose not to trap WRMSR to TSC. According
1838                  * to the spec, this should set L1's TSC; The offset that L1
1839                  * set for L2 remains unchanged, and still needs to be added
1840                  * to the newly set TSC to get L2's TSC.
1841                  */
1842                 struct vmcs12 *vmcs12;
1843                 to_vmx(vcpu)->nested.vmcs01_tsc_offset = offset;
1844                 /* recalculate vmcs02.TSC_OFFSET: */
1845                 vmcs12 = get_vmcs12(vcpu);
1846                 vmcs_write64(TSC_OFFSET, offset +
1847                         (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
1848                          vmcs12->tsc_offset : 0));
1849         } else {
1850                 vmcs_write64(TSC_OFFSET, offset);
1851         }
1852 }
1853
1854 static void vmx_adjust_tsc_offset(struct kvm_vcpu *vcpu, s64 adjustment)
1855 {
1856         u64 offset = vmcs_read64(TSC_OFFSET);
1857         vmcs_write64(TSC_OFFSET, offset + adjustment);
1858         if (is_guest_mode(vcpu)) {
1859                 /* Even when running L2, the adjustment needs to apply to L1 */
1860                 to_vmx(vcpu)->nested.vmcs01_tsc_offset += adjustment;
1861         }
1862 }
1863
1864 static u64 vmx_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
1865 {
1866         return target_tsc - native_read_tsc();
1867 }
1868
1869 static bool guest_cpuid_has_vmx(struct kvm_vcpu *vcpu)
1870 {
1871         struct kvm_cpuid_entry2 *best = kvm_find_cpuid_entry(vcpu, 1, 0);
1872         return best && (best->ecx & (1 << (X86_FEATURE_VMX & 31)));
1873 }
1874
1875 /*
1876  * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1877  * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1878  * all guests if the "nested" module option is off, and can also be disabled
1879  * for a single guest by disabling its VMX cpuid bit.
1880  */
1881 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1882 {
1883         return nested && guest_cpuid_has_vmx(vcpu);
1884 }
1885
1886 /*
1887  * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
1888  * returned for the various VMX controls MSRs when nested VMX is enabled.
1889  * The same values should also be used to verify that vmcs12 control fields are
1890  * valid during nested entry from L1 to L2.
1891  * Each of these control msrs has a low and high 32-bit half: A low bit is on
1892  * if the corresponding bit in the (32-bit) control field *must* be on, and a
1893  * bit in the high half is on if the corresponding bit in the control field
1894  * may be on. See also vmx_control_verify().
1895  * TODO: allow these variables to be modified (downgraded) by module options
1896  * or other means.
1897  */
1898 static u32 nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high;
1899 static u32 nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high;
1900 static u32 nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high;
1901 static u32 nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high;
1902 static u32 nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high;
1903 static __init void nested_vmx_setup_ctls_msrs(void)
1904 {
1905         /*
1906          * Note that as a general rule, the high half of the MSRs (bits in
1907          * the control fields which may be 1) should be initialized by the
1908          * intersection of the underlying hardware's MSR (i.e., features which
1909          * can be supported) and the list of features we want to expose -
1910          * because they are known to be properly supported in our code.
1911          * Also, usually, the low half of the MSRs (bits which must be 1) can
1912          * be set to 0, meaning that L1 may turn off any of these bits. The
1913          * reason is that if one of these bits is necessary, it will appear
1914          * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
1915          * fields of vmcs01 and vmcs02, will turn these bits off - and
1916          * nested_vmx_exit_handled() will not pass related exits to L1.
1917          * These rules have exceptions below.
1918          */
1919
1920         /* pin-based controls */
1921         /*
1922          * According to the Intel spec, if bit 55 of VMX_BASIC is off (as it is
1923          * in our case), bits 1, 2 and 4 (i.e., 0x16) must be 1 in this MSR.
1924          */
1925         nested_vmx_pinbased_ctls_low = 0x16 ;
1926         nested_vmx_pinbased_ctls_high = 0x16 |
1927                 PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING |
1928                 PIN_BASED_VIRTUAL_NMIS;
1929
1930         /* exit controls */
1931         nested_vmx_exit_ctls_low = 0;
1932         /* Note that guest use of VM_EXIT_ACK_INTR_ON_EXIT is not supported. */
1933 #ifdef CONFIG_X86_64
1934         nested_vmx_exit_ctls_high = VM_EXIT_HOST_ADDR_SPACE_SIZE;
1935 #else
1936         nested_vmx_exit_ctls_high = 0;
1937 #endif
1938
1939         /* entry controls */
1940         rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
1941                 nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high);
1942         nested_vmx_entry_ctls_low = 0;
1943         nested_vmx_entry_ctls_high &=
1944                 VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_IA32E_MODE;
1945
1946         /* cpu-based controls */
1947         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
1948                 nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high);
1949         nested_vmx_procbased_ctls_low = 0;
1950         nested_vmx_procbased_ctls_high &=
1951                 CPU_BASED_VIRTUAL_INTR_PENDING | CPU_BASED_USE_TSC_OFFSETING |
1952                 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
1953                 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
1954                 CPU_BASED_CR3_STORE_EXITING |
1955 #ifdef CONFIG_X86_64
1956                 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
1957 #endif
1958                 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
1959                 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_EXITING |
1960                 CPU_BASED_RDPMC_EXITING |
1961                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1962         /*
1963          * We can allow some features even when not supported by the
1964          * hardware. For example, L1 can specify an MSR bitmap - and we
1965          * can use it to avoid exits to L1 - even when L0 runs L2
1966          * without MSR bitmaps.
1967          */
1968         nested_vmx_procbased_ctls_high |= CPU_BASED_USE_MSR_BITMAPS;
1969
1970         /* secondary cpu-based controls */
1971         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
1972                 nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high);
1973         nested_vmx_secondary_ctls_low = 0;
1974         nested_vmx_secondary_ctls_high &=
1975                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1976 }
1977
1978 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
1979 {
1980         /*
1981          * Bits 0 in high must be 0, and bits 1 in low must be 1.
1982          */
1983         return ((control & high) | low) == control;
1984 }
1985
1986 static inline u64 vmx_control_msr(u32 low, u32 high)
1987 {
1988         return low | ((u64)high << 32);
1989 }
1990
1991 /*
1992  * If we allow our guest to use VMX instructions (i.e., nested VMX), we should
1993  * also let it use VMX-specific MSRs.
1994  * vmx_get_vmx_msr() and vmx_set_vmx_msr() return 1 when we handled a
1995  * VMX-specific MSR, or 0 when we haven't (and the caller should handle it
1996  * like all other MSRs).
1997  */
1998 static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
1999 {
2000         if (!nested_vmx_allowed(vcpu) && msr_index >= MSR_IA32_VMX_BASIC &&
2001                      msr_index <= MSR_IA32_VMX_TRUE_ENTRY_CTLS) {
2002                 /*
2003                  * According to the spec, processors which do not support VMX
2004                  * should throw a #GP(0) when VMX capability MSRs are read.
2005                  */
2006                 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
2007                 return 1;
2008         }
2009
2010         switch (msr_index) {
2011         case MSR_IA32_FEATURE_CONTROL:
2012                 *pdata = 0;
2013                 break;
2014         case MSR_IA32_VMX_BASIC:
2015                 /*
2016                  * This MSR reports some information about VMX support. We
2017                  * should return information about the VMX we emulate for the
2018                  * guest, and the VMCS structure we give it - not about the
2019                  * VMX support of the underlying hardware.
2020                  */
2021                 *pdata = VMCS12_REVISION |
2022                            ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
2023                            (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
2024                 break;
2025         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2026         case MSR_IA32_VMX_PINBASED_CTLS:
2027                 *pdata = vmx_control_msr(nested_vmx_pinbased_ctls_low,
2028                                         nested_vmx_pinbased_ctls_high);
2029                 break;
2030         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
2031         case MSR_IA32_VMX_PROCBASED_CTLS:
2032                 *pdata = vmx_control_msr(nested_vmx_procbased_ctls_low,
2033                                         nested_vmx_procbased_ctls_high);
2034                 break;
2035         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
2036         case MSR_IA32_VMX_EXIT_CTLS:
2037                 *pdata = vmx_control_msr(nested_vmx_exit_ctls_low,
2038                                         nested_vmx_exit_ctls_high);
2039                 break;
2040         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
2041         case MSR_IA32_VMX_ENTRY_CTLS:
2042                 *pdata = vmx_control_msr(nested_vmx_entry_ctls_low,
2043                                         nested_vmx_entry_ctls_high);
2044                 break;
2045         case MSR_IA32_VMX_MISC:
2046                 *pdata = 0;
2047                 break;
2048         /*
2049          * These MSRs specify bits which the guest must keep fixed (on or off)
2050          * while L1 is in VMXON mode (in L1's root mode, or running an L2).
2051          * We picked the standard core2 setting.
2052          */
2053 #define VMXON_CR0_ALWAYSON      (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
2054 #define VMXON_CR4_ALWAYSON      X86_CR4_VMXE
2055         case MSR_IA32_VMX_CR0_FIXED0:
2056                 *pdata = VMXON_CR0_ALWAYSON;
2057                 break;
2058         case MSR_IA32_VMX_CR0_FIXED1:
2059                 *pdata = -1ULL;
2060                 break;
2061         case MSR_IA32_VMX_CR4_FIXED0:
2062                 *pdata = VMXON_CR4_ALWAYSON;
2063                 break;
2064         case MSR_IA32_VMX_CR4_FIXED1:
2065                 *pdata = -1ULL;
2066                 break;
2067         case MSR_IA32_VMX_VMCS_ENUM:
2068                 *pdata = 0x1f;
2069                 break;
2070         case MSR_IA32_VMX_PROCBASED_CTLS2:
2071                 *pdata = vmx_control_msr(nested_vmx_secondary_ctls_low,
2072                                         nested_vmx_secondary_ctls_high);
2073                 break;
2074         case MSR_IA32_VMX_EPT_VPID_CAP:
2075                 /* Currently, no nested ept or nested vpid */
2076                 *pdata = 0;
2077                 break;
2078         default:
2079                 return 0;
2080         }
2081
2082         return 1;
2083 }
2084
2085 static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
2086 {
2087         if (!nested_vmx_allowed(vcpu))
2088                 return 0;
2089
2090         if (msr_index == MSR_IA32_FEATURE_CONTROL)
2091                 /* TODO: the right thing. */
2092                 return 1;
2093         /*
2094          * No need to treat VMX capability MSRs specially: If we don't handle
2095          * them, handle_wrmsr will #GP(0), which is correct (they are readonly)
2096          */
2097         return 0;
2098 }
2099
2100 /*
2101  * Reads an msr value (of 'msr_index') into 'pdata'.
2102  * Returns 0 on success, non-0 otherwise.
2103  * Assumes vcpu_load() was already called.
2104  */
2105 static int vmx_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
2106 {
2107         u64 data;
2108         struct shared_msr_entry *msr;
2109
2110         if (!pdata) {
2111                 printk(KERN_ERR "BUG: get_msr called with NULL pdata\n");
2112                 return -EINVAL;
2113         }
2114
2115         switch (msr_index) {
2116 #ifdef CONFIG_X86_64
2117         case MSR_FS_BASE:
2118                 data = vmcs_readl(GUEST_FS_BASE);
2119                 break;
2120         case MSR_GS_BASE:
2121                 data = vmcs_readl(GUEST_GS_BASE);
2122                 break;
2123         case MSR_KERNEL_GS_BASE:
2124                 vmx_load_host_state(to_vmx(vcpu));
2125                 data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
2126                 break;
2127 #endif
2128         case MSR_EFER:
2129                 return kvm_get_msr_common(vcpu, msr_index, pdata);
2130         case MSR_IA32_TSC:
2131                 data = guest_read_tsc();
2132                 break;
2133         case MSR_IA32_SYSENTER_CS:
2134                 data = vmcs_read32(GUEST_SYSENTER_CS);
2135                 break;
2136         case MSR_IA32_SYSENTER_EIP:
2137                 data = vmcs_readl(GUEST_SYSENTER_EIP);
2138                 break;
2139         case MSR_IA32_SYSENTER_ESP:
2140                 data = vmcs_readl(GUEST_SYSENTER_ESP);
2141                 break;
2142         case MSR_TSC_AUX:
2143                 if (!to_vmx(vcpu)->rdtscp_enabled)
2144                         return 1;
2145                 /* Otherwise falls through */
2146         default:
2147                 vmx_load_host_state(to_vmx(vcpu));
2148                 if (vmx_get_vmx_msr(vcpu, msr_index, pdata))
2149                         return 0;
2150                 msr = find_msr_entry(to_vmx(vcpu), msr_index);
2151                 if (msr) {
2152                         vmx_load_host_state(to_vmx(vcpu));
2153                         data = msr->data;
2154                         break;
2155                 }
2156                 return kvm_get_msr_common(vcpu, msr_index, pdata);
2157         }
2158
2159         *pdata = data;
2160         return 0;
2161 }
2162
2163 /*
2164  * Writes msr value into into the appropriate "register".
2165  * Returns 0 on success, non-0 otherwise.
2166  * Assumes vcpu_load() was already called.
2167  */
2168 static int vmx_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
2169 {
2170         struct vcpu_vmx *vmx = to_vmx(vcpu);
2171         struct shared_msr_entry *msr;
2172         int ret = 0;
2173
2174         switch (msr_index) {
2175         case MSR_EFER:
2176                 vmx_load_host_state(vmx);
2177                 ret = kvm_set_msr_common(vcpu, msr_index, data);
2178                 break;
2179 #ifdef CONFIG_X86_64
2180         case MSR_FS_BASE:
2181                 vmx_segment_cache_clear(vmx);
2182                 vmcs_writel(GUEST_FS_BASE, data);
2183                 break;
2184         case MSR_GS_BASE:
2185                 vmx_segment_cache_clear(vmx);
2186                 vmcs_writel(GUEST_GS_BASE, data);
2187                 break;
2188         case MSR_KERNEL_GS_BASE:
2189                 vmx_load_host_state(vmx);
2190                 vmx->msr_guest_kernel_gs_base = data;
2191                 break;
2192 #endif
2193         case MSR_IA32_SYSENTER_CS:
2194                 vmcs_write32(GUEST_SYSENTER_CS, data);
2195                 break;
2196         case MSR_IA32_SYSENTER_EIP:
2197                 vmcs_writel(GUEST_SYSENTER_EIP, data);
2198                 break;
2199         case MSR_IA32_SYSENTER_ESP:
2200                 vmcs_writel(GUEST_SYSENTER_ESP, data);
2201                 break;
2202         case MSR_IA32_TSC:
2203                 kvm_write_tsc(vcpu, data);
2204                 break;
2205         case MSR_IA32_CR_PAT:
2206                 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2207                         vmcs_write64(GUEST_IA32_PAT, data);
2208                         vcpu->arch.pat = data;
2209                         break;
2210                 }
2211                 ret = kvm_set_msr_common(vcpu, msr_index, data);
2212                 break;
2213         case MSR_TSC_AUX:
2214                 if (!vmx->rdtscp_enabled)
2215                         return 1;
2216                 /* Check reserved bit, higher 32 bits should be zero */
2217                 if ((data >> 32) != 0)
2218                         return 1;
2219                 /* Otherwise falls through */
2220         default:
2221                 if (vmx_set_vmx_msr(vcpu, msr_index, data))
2222                         break;
2223                 msr = find_msr_entry(vmx, msr_index);
2224                 if (msr) {
2225                         vmx_load_host_state(vmx);
2226                         msr->data = data;
2227                         break;
2228                 }
2229                 ret = kvm_set_msr_common(vcpu, msr_index, data);
2230         }
2231
2232         return ret;
2233 }
2234
2235 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2236 {
2237         __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
2238         switch (reg) {
2239         case VCPU_REGS_RSP:
2240                 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2241                 break;
2242         case VCPU_REGS_RIP:
2243                 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2244                 break;
2245         case VCPU_EXREG_PDPTR:
2246                 if (enable_ept)
2247                         ept_save_pdptrs(vcpu);
2248                 break;
2249         default:
2250                 break;
2251         }
2252 }
2253
2254 static void set_guest_debug(struct kvm_vcpu *vcpu, struct kvm_guest_debug *dbg)
2255 {
2256         if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
2257                 vmcs_writel(GUEST_DR7, dbg->arch.debugreg[7]);
2258         else
2259                 vmcs_writel(GUEST_DR7, vcpu->arch.dr7);
2260
2261         update_exception_bitmap(vcpu);
2262 }
2263
2264 static __init int cpu_has_kvm_support(void)
2265 {
2266         return cpu_has_vmx();
2267 }
2268
2269 static __init int vmx_disabled_by_bios(void)
2270 {
2271         u64 msr;
2272
2273         rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
2274         if (msr & FEATURE_CONTROL_LOCKED) {
2275                 /* launched w/ TXT and VMX disabled */
2276                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2277                         && tboot_enabled())
2278                         return 1;
2279                 /* launched w/o TXT and VMX only enabled w/ TXT */
2280                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2281                         && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2282                         && !tboot_enabled()) {
2283                         printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
2284                                 "activate TXT before enabling KVM\n");
2285                         return 1;
2286                 }
2287                 /* launched w/o TXT and VMX disabled */
2288                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2289                         && !tboot_enabled())
2290                         return 1;
2291         }
2292
2293         return 0;
2294 }
2295
2296 static void kvm_cpu_vmxon(u64 addr)
2297 {
2298         asm volatile (ASM_VMX_VMXON_RAX
2299                         : : "a"(&addr), "m"(addr)
2300                         : "memory", "cc");
2301 }
2302
2303 static int hardware_enable(void *garbage)
2304 {
2305         int cpu = raw_smp_processor_id();
2306         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2307         u64 old, test_bits;
2308
2309         if (read_cr4() & X86_CR4_VMXE)
2310                 return -EBUSY;
2311
2312         INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
2313         rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
2314
2315         test_bits = FEATURE_CONTROL_LOCKED;
2316         test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
2317         if (tboot_enabled())
2318                 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
2319
2320         if ((old & test_bits) != test_bits) {
2321                 /* enable and lock */
2322                 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
2323         }
2324         write_cr4(read_cr4() | X86_CR4_VMXE); /* FIXME: not cpu hotplug safe */
2325
2326         if (vmm_exclusive) {
2327                 kvm_cpu_vmxon(phys_addr);
2328                 ept_sync_global();
2329         }
2330
2331         store_gdt(&__get_cpu_var(host_gdt));
2332
2333         return 0;
2334 }
2335
2336 static void vmclear_local_loaded_vmcss(void)
2337 {
2338         int cpu = raw_smp_processor_id();
2339         struct loaded_vmcs *v, *n;
2340
2341         list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2342                                  loaded_vmcss_on_cpu_link)
2343                 __loaded_vmcs_clear(v);
2344 }
2345
2346
2347 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
2348  * tricks.
2349  */
2350 static void kvm_cpu_vmxoff(void)
2351 {
2352         asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
2353 }
2354
2355 static void hardware_disable(void *garbage)
2356 {
2357         if (vmm_exclusive) {
2358                 vmclear_local_loaded_vmcss();
2359                 kvm_cpu_vmxoff();
2360         }
2361         write_cr4(read_cr4() & ~X86_CR4_VMXE);
2362 }
2363
2364 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2365                                       u32 msr, u32 *result)
2366 {
2367         u32 vmx_msr_low, vmx_msr_high;
2368         u32 ctl = ctl_min | ctl_opt;
2369
2370         rdmsr(msr, vmx_msr_low, vmx_msr_high);
2371
2372         ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2373         ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
2374
2375         /* Ensure minimum (required) set of control bits are supported. */
2376         if (ctl_min & ~ctl)
2377                 return -EIO;
2378
2379         *result = ctl;
2380         return 0;
2381 }
2382
2383 static __init bool allow_1_setting(u32 msr, u32 ctl)
2384 {
2385         u32 vmx_msr_low, vmx_msr_high;
2386
2387         rdmsr(msr, vmx_msr_low, vmx_msr_high);
2388         return vmx_msr_high & ctl;
2389 }
2390
2391 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
2392 {
2393         u32 vmx_msr_low, vmx_msr_high;
2394         u32 min, opt, min2, opt2;
2395         u32 _pin_based_exec_control = 0;
2396         u32 _cpu_based_exec_control = 0;
2397         u32 _cpu_based_2nd_exec_control = 0;
2398         u32 _vmexit_control = 0;
2399         u32 _vmentry_control = 0;
2400
2401         min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2402         opt = PIN_BASED_VIRTUAL_NMIS;
2403         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2404                                 &_pin_based_exec_control) < 0)
2405                 return -EIO;
2406
2407         min =
2408 #ifdef CONFIG_X86_64
2409               CPU_BASED_CR8_LOAD_EXITING |
2410               CPU_BASED_CR8_STORE_EXITING |
2411 #endif
2412               CPU_BASED_CR3_LOAD_EXITING |
2413               CPU_BASED_CR3_STORE_EXITING |
2414               CPU_BASED_USE_IO_BITMAPS |
2415               CPU_BASED_MOV_DR_EXITING |
2416               CPU_BASED_USE_TSC_OFFSETING |
2417               CPU_BASED_MWAIT_EXITING |
2418               CPU_BASED_MONITOR_EXITING |
2419               CPU_BASED_INVLPG_EXITING;
2420
2421         if (yield_on_hlt)
2422                 min |= CPU_BASED_HLT_EXITING;
2423
2424         opt = CPU_BASED_TPR_SHADOW |
2425               CPU_BASED_USE_MSR_BITMAPS |
2426               CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2427         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2428                                 &_cpu_based_exec_control) < 0)
2429                 return -EIO;
2430 #ifdef CONFIG_X86_64
2431         if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2432                 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2433                                            ~CPU_BASED_CR8_STORE_EXITING;
2434 #endif
2435         if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2436                 min2 = 0;
2437                 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2438                         SECONDARY_EXEC_WBINVD_EXITING |
2439                         SECONDARY_EXEC_ENABLE_VPID |
2440                         SECONDARY_EXEC_ENABLE_EPT |
2441                         SECONDARY_EXEC_UNRESTRICTED_GUEST |
2442                         SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2443                         SECONDARY_EXEC_RDTSCP;
2444                 if (adjust_vmx_controls(min2, opt2,
2445                                         MSR_IA32_VMX_PROCBASED_CTLS2,
2446                                         &_cpu_based_2nd_exec_control) < 0)
2447                         return -EIO;
2448         }
2449 #ifndef CONFIG_X86_64
2450         if (!(_cpu_based_2nd_exec_control &
2451                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2452                 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2453 #endif
2454         if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2455                 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2456                    enabled */
2457                 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2458                                              CPU_BASED_CR3_STORE_EXITING |
2459                                              CPU_BASED_INVLPG_EXITING);
2460                 rdmsr(MSR_IA32_VMX_EPT_VPID_CAP,
2461                       vmx_capability.ept, vmx_capability.vpid);
2462         }
2463
2464         min = 0;
2465 #ifdef CONFIG_X86_64
2466         min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2467 #endif
2468         opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT;
2469         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2470                                 &_vmexit_control) < 0)
2471                 return -EIO;
2472
2473         min = 0;
2474         opt = VM_ENTRY_LOAD_IA32_PAT;
2475         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2476                                 &_vmentry_control) < 0)
2477                 return -EIO;
2478
2479         rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2480
2481         /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2482         if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2483                 return -EIO;
2484
2485 #ifdef CONFIG_X86_64
2486         /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2487         if (vmx_msr_high & (1u<<16))
2488                 return -EIO;
2489 #endif
2490
2491         /* Require Write-Back (WB) memory type for VMCS accesses. */
2492         if (((vmx_msr_high >> 18) & 15) != 6)
2493                 return -EIO;
2494
2495         vmcs_conf->size = vmx_msr_high & 0x1fff;
2496         vmcs_conf->order = get_order(vmcs_config.size);
2497         vmcs_conf->revision_id = vmx_msr_low;
2498
2499         vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2500         vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2501         vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2502         vmcs_conf->vmexit_ctrl         = _vmexit_control;
2503         vmcs_conf->vmentry_ctrl        = _vmentry_control;
2504
2505         cpu_has_load_ia32_efer =
2506                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
2507                                 VM_ENTRY_LOAD_IA32_EFER)
2508                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
2509                                    VM_EXIT_LOAD_IA32_EFER);
2510
2511         cpu_has_load_perf_global_ctrl =
2512                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
2513                                 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
2514                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
2515                                    VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
2516
2517         /*
2518          * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
2519          * but due to arrata below it can't be used. Workaround is to use
2520          * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2521          *
2522          * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
2523          *
2524          * AAK155             (model 26)
2525          * AAP115             (model 30)
2526          * AAT100             (model 37)
2527          * BC86,AAY89,BD102   (model 44)
2528          * BA97               (model 46)
2529          *
2530          */
2531         if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
2532                 switch (boot_cpu_data.x86_model) {
2533                 case 26:
2534                 case 30:
2535                 case 37:
2536                 case 44:
2537                 case 46:
2538                         cpu_has_load_perf_global_ctrl = false;
2539                         printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2540                                         "does not work properly. Using workaround\n");
2541                         break;
2542                 default:
2543                         break;
2544                 }
2545         }
2546
2547         return 0;
2548 }
2549
2550 static struct vmcs *alloc_vmcs_cpu(int cpu)
2551 {
2552         int node = cpu_to_node(cpu);
2553         struct page *pages;
2554         struct vmcs *vmcs;
2555
2556         pages = alloc_pages_exact_node(node, GFP_KERNEL, vmcs_config.order);
2557         if (!pages)
2558                 return NULL;
2559         vmcs = page_address(pages);
2560         memset(vmcs, 0, vmcs_config.size);
2561         vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
2562         return vmcs;
2563 }
2564
2565 static struct vmcs *alloc_vmcs(void)
2566 {
2567         return alloc_vmcs_cpu(raw_smp_processor_id());
2568 }
2569
2570 static void free_vmcs(struct vmcs *vmcs)
2571 {
2572         free_pages((unsigned long)vmcs, vmcs_config.order);
2573 }
2574
2575 /*
2576  * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2577  */
2578 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2579 {
2580         if (!loaded_vmcs->vmcs)
2581                 return;
2582         loaded_vmcs_clear(loaded_vmcs);
2583         free_vmcs(loaded_vmcs->vmcs);
2584         loaded_vmcs->vmcs = NULL;
2585 }
2586
2587 static void free_kvm_area(void)
2588 {
2589         int cpu;
2590
2591         for_each_possible_cpu(cpu) {
2592                 free_vmcs(per_cpu(vmxarea, cpu));
2593                 per_cpu(vmxarea, cpu) = NULL;
2594         }
2595 }
2596
2597 static __init int alloc_kvm_area(void)
2598 {
2599         int cpu;
2600
2601         for_each_possible_cpu(cpu) {
2602                 struct vmcs *vmcs;
2603
2604                 vmcs = alloc_vmcs_cpu(cpu);
2605                 if (!vmcs) {
2606                         free_kvm_area();
2607                         return -ENOMEM;
2608                 }
2609
2610                 per_cpu(vmxarea, cpu) = vmcs;
2611         }
2612         return 0;
2613 }
2614
2615 static __init int hardware_setup(void)
2616 {
2617         if (setup_vmcs_config(&vmcs_config) < 0)
2618                 return -EIO;
2619
2620         if (boot_cpu_has(X86_FEATURE_NX))
2621                 kvm_enable_efer_bits(EFER_NX);
2622
2623         if (!cpu_has_vmx_vpid())
2624                 enable_vpid = 0;
2625
2626         if (!cpu_has_vmx_ept() ||
2627             !cpu_has_vmx_ept_4levels()) {
2628                 enable_ept = 0;
2629                 enable_unrestricted_guest = 0;
2630         }
2631
2632         if (!cpu_has_vmx_unrestricted_guest())
2633                 enable_unrestricted_guest = 0;
2634
2635         if (!cpu_has_vmx_flexpriority())
2636                 flexpriority_enabled = 0;
2637
2638         if (!cpu_has_vmx_tpr_shadow())
2639                 kvm_x86_ops->update_cr8_intercept = NULL;
2640
2641         if (enable_ept && !cpu_has_vmx_ept_2m_page())
2642                 kvm_disable_largepages();
2643
2644         if (!cpu_has_vmx_ple())
2645                 ple_gap = 0;
2646
2647         if (nested)
2648                 nested_vmx_setup_ctls_msrs();
2649
2650         return alloc_kvm_area();
2651 }
2652
2653 static __exit void hardware_unsetup(void)
2654 {
2655         free_kvm_area();
2656 }
2657
2658 static void fix_pmode_dataseg(int seg, struct kvm_save_segment *save)
2659 {
2660         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2661
2662         if (vmcs_readl(sf->base) == save->base && (save->base & AR_S_MASK)) {
2663                 vmcs_write16(sf->selector, save->selector);
2664                 vmcs_writel(sf->base, save->base);
2665                 vmcs_write32(sf->limit, save->limit);
2666                 vmcs_write32(sf->ar_bytes, save->ar);
2667         } else {
2668                 u32 dpl = (vmcs_read16(sf->selector) & SELECTOR_RPL_MASK)
2669                         << AR_DPL_SHIFT;
2670                 vmcs_write32(sf->ar_bytes, 0x93 | dpl);
2671         }
2672 }
2673
2674 static void enter_pmode(struct kvm_vcpu *vcpu)
2675 {
2676         unsigned long flags;
2677         struct vcpu_vmx *vmx = to_vmx(vcpu);
2678
2679         vmx->emulation_required = 1;
2680         vmx->rmode.vm86_active = 0;
2681
2682         vmx_segment_cache_clear(vmx);
2683
2684         vmcs_write16(GUEST_TR_SELECTOR, vmx->rmode.tr.selector);
2685         vmcs_writel(GUEST_TR_BASE, vmx->rmode.tr.base);
2686         vmcs_write32(GUEST_TR_LIMIT, vmx->rmode.tr.limit);
2687         vmcs_write32(GUEST_TR_AR_BYTES, vmx->rmode.tr.ar);
2688
2689         flags = vmcs_readl(GUEST_RFLAGS);
2690         flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2691         flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2692         vmcs_writel(GUEST_RFLAGS, flags);
2693
2694         vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2695                         (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2696
2697         update_exception_bitmap(vcpu);
2698
2699         if (emulate_invalid_guest_state)
2700                 return;
2701
2702         fix_pmode_dataseg(VCPU_SREG_ES, &vmx->rmode.es);
2703         fix_pmode_dataseg(VCPU_SREG_DS, &vmx->rmode.ds);
2704         fix_pmode_dataseg(VCPU_SREG_GS, &vmx->rmode.gs);
2705         fix_pmode_dataseg(VCPU_SREG_FS, &vmx->rmode.fs);
2706
2707         vmx_segment_cache_clear(vmx);
2708
2709         vmcs_write16(GUEST_SS_SELECTOR, 0);
2710         vmcs_write32(GUEST_SS_AR_BYTES, 0x93);
2711
2712         vmcs_write16(GUEST_CS_SELECTOR,
2713                      vmcs_read16(GUEST_CS_SELECTOR) & ~SELECTOR_RPL_MASK);
2714         vmcs_write32(GUEST_CS_AR_BYTES, 0x9b);
2715 }
2716
2717 static gva_t rmode_tss_base(struct kvm *kvm)
2718 {
2719         if (!kvm->arch.tss_addr) {
2720                 struct kvm_memslots *slots;
2721                 gfn_t base_gfn;
2722
2723                 slots = kvm_memslots(kvm);
2724                 base_gfn = slots->memslots[0].base_gfn +
2725                                  kvm->memslots->memslots[0].npages - 3;
2726                 return base_gfn << PAGE_SHIFT;
2727         }
2728         return kvm->arch.tss_addr;
2729 }
2730
2731 static void fix_rmode_seg(int seg, struct kvm_save_segment *save)
2732 {
2733         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2734
2735         save->selector = vmcs_read16(sf->selector);
2736         save->base = vmcs_readl(sf->base);
2737         save->limit = vmcs_read32(sf->limit);
2738         save->ar = vmcs_read32(sf->ar_bytes);
2739         vmcs_write16(sf->selector, save->base >> 4);
2740         vmcs_write32(sf->base, save->base & 0xffff0);
2741         vmcs_write32(sf->limit, 0xffff);
2742         vmcs_write32(sf->ar_bytes, 0xf3);
2743         if (save->base & 0xf)
2744                 printk_once(KERN_WARNING "kvm: segment base is not paragraph"
2745                             " aligned when entering protected mode (seg=%d)",
2746                             seg);
2747 }
2748
2749 static void enter_rmode(struct kvm_vcpu *vcpu)
2750 {
2751         unsigned long flags;
2752         struct vcpu_vmx *vmx = to_vmx(vcpu);
2753
2754         if (enable_unrestricted_guest)
2755                 return;
2756
2757         vmx->emulation_required = 1;
2758         vmx->rmode.vm86_active = 1;
2759
2760         /*
2761          * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2762          * vcpu. Call it here with phys address pointing 16M below 4G.
2763          */
2764         if (!vcpu->kvm->arch.tss_addr) {
2765                 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2766                              "called before entering vcpu\n");
2767                 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
2768                 vmx_set_tss_addr(vcpu->kvm, 0xfeffd000);
2769                 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
2770         }
2771
2772         vmx_segment_cache_clear(vmx);
2773
2774         vmx->rmode.tr.selector = vmcs_read16(GUEST_TR_SELECTOR);
2775         vmx->rmode.tr.base = vmcs_readl(GUEST_TR_BASE);
2776         vmcs_writel(GUEST_TR_BASE, rmode_tss_base(vcpu->kvm));
2777
2778         vmx->rmode.tr.limit = vmcs_read32(GUEST_TR_LIMIT);
2779         vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2780
2781         vmx->rmode.tr.ar = vmcs_read32(GUEST_TR_AR_BYTES);
2782         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2783
2784         flags = vmcs_readl(GUEST_RFLAGS);
2785         vmx->rmode.save_rflags = flags;
2786
2787         flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2788
2789         vmcs_writel(GUEST_RFLAGS, flags);
2790         vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2791         update_exception_bitmap(vcpu);
2792
2793         if (emulate_invalid_guest_state)
2794                 goto continue_rmode;
2795
2796         vmcs_write16(GUEST_SS_SELECTOR, vmcs_readl(GUEST_SS_BASE) >> 4);
2797         vmcs_write32(GUEST_SS_LIMIT, 0xffff);
2798         vmcs_write32(GUEST_SS_AR_BYTES, 0xf3);
2799
2800         vmcs_write32(GUEST_CS_AR_BYTES, 0xf3);
2801         vmcs_write32(GUEST_CS_LIMIT, 0xffff);
2802         if (vmcs_readl(GUEST_CS_BASE) == 0xffff0000)
2803                 vmcs_writel(GUEST_CS_BASE, 0xf0000);
2804         vmcs_write16(GUEST_CS_SELECTOR, vmcs_readl(GUEST_CS_BASE) >> 4);
2805
2806         fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.es);
2807         fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.ds);
2808         fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.gs);
2809         fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.fs);
2810
2811 continue_rmode:
2812         kvm_mmu_reset_context(vcpu);
2813 }
2814
2815 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2816 {
2817         struct vcpu_vmx *vmx = to_vmx(vcpu);
2818         struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
2819
2820         if (!msr)
2821                 return;
2822
2823         /*
2824          * Force kernel_gs_base reloading before EFER changes, as control
2825          * of this msr depends on is_long_mode().
2826          */
2827         vmx_load_host_state(to_vmx(vcpu));
2828         vcpu->arch.efer = efer;
2829         if (efer & EFER_LMA) {
2830                 vmcs_write32(VM_ENTRY_CONTROLS,
2831                              vmcs_read32(VM_ENTRY_CONTROLS) |
2832                              VM_ENTRY_IA32E_MODE);
2833                 msr->data = efer;
2834         } else {
2835                 vmcs_write32(VM_ENTRY_CONTROLS,
2836                              vmcs_read32(VM_ENTRY_CONTROLS) &
2837                              ~VM_ENTRY_IA32E_MODE);
2838
2839                 msr->data = efer & ~EFER_LME;
2840         }
2841         setup_msrs(vmx);
2842 }
2843
2844 #ifdef CONFIG_X86_64
2845
2846 static void enter_lmode(struct kvm_vcpu *vcpu)
2847 {
2848         u32 guest_tr_ar;
2849
2850         vmx_segment_cache_clear(to_vmx(vcpu));
2851
2852         guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2853         if ((guest_tr_ar & AR_TYPE_MASK) != AR_TYPE_BUSY_64_TSS) {
2854                 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2855                                      __func__);
2856                 vmcs_write32(GUEST_TR_AR_BYTES,
2857                              (guest_tr_ar & ~AR_TYPE_MASK)
2858                              | AR_TYPE_BUSY_64_TSS);
2859         }
2860         vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
2861 }
2862
2863 static void exit_lmode(struct kvm_vcpu *vcpu)
2864 {
2865         vmcs_write32(VM_ENTRY_CONTROLS,
2866                      vmcs_read32(VM_ENTRY_CONTROLS)
2867                      & ~VM_ENTRY_IA32E_MODE);
2868         vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
2869 }
2870
2871 #endif
2872
2873 static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
2874 {
2875         vpid_sync_context(to_vmx(vcpu));
2876         if (enable_ept) {
2877                 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
2878                         return;
2879                 ept_sync_context(construct_eptp(vcpu->arch.mmu.root_hpa));
2880         }
2881 }
2882
2883 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2884 {
2885         ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2886
2887         vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
2888         vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
2889 }
2890
2891 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
2892 {
2893         if (enable_ept && is_paging(vcpu))
2894                 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2895         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
2896 }
2897
2898 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2899 {
2900         ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2901
2902         vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
2903         vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
2904 }
2905
2906 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
2907 {
2908         if (!test_bit(VCPU_EXREG_PDPTR,
2909                       (unsigned long *)&vcpu->arch.regs_dirty))
2910                 return;
2911
2912         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
2913                 vmcs_write64(GUEST_PDPTR0, vcpu->arch.mmu.pdptrs[0]);
2914                 vmcs_write64(GUEST_PDPTR1, vcpu->arch.mmu.pdptrs[1]);
2915                 vmcs_write64(GUEST_PDPTR2, vcpu->arch.mmu.pdptrs[2]);
2916                 vmcs_write64(GUEST_PDPTR3, vcpu->arch.mmu.pdptrs[3]);
2917         }
2918 }
2919
2920 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
2921 {
2922         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
2923                 vcpu->arch.mmu.pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
2924                 vcpu->arch.mmu.pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
2925                 vcpu->arch.mmu.pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
2926                 vcpu->arch.mmu.pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
2927         }
2928
2929         __set_bit(VCPU_EXREG_PDPTR,
2930                   (unsigned long *)&vcpu->arch.regs_avail);
2931         __set_bit(VCPU_EXREG_PDPTR,
2932                   (unsigned long *)&vcpu->arch.regs_dirty);
2933 }
2934
2935 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
2936
2937 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
2938                                         unsigned long cr0,
2939                                         struct kvm_vcpu *vcpu)
2940 {
2941         if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
2942                 vmx_decache_cr3(vcpu);
2943         if (!(cr0 & X86_CR0_PG)) {
2944                 /* From paging/starting to nonpaging */
2945                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
2946                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
2947                              (CPU_BASED_CR3_LOAD_EXITING |
2948                               CPU_BASED_CR3_STORE_EXITING));
2949                 vcpu->arch.cr0 = cr0;
2950                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2951         } else if (!is_paging(vcpu)) {
2952                 /* From nonpaging to paging */
2953                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
2954                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
2955                              ~(CPU_BASED_CR3_LOAD_EXITING |
2956                                CPU_BASED_CR3_STORE_EXITING));
2957                 vcpu->arch.cr0 = cr0;
2958                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2959         }
2960
2961         if (!(cr0 & X86_CR0_WP))
2962                 *hw_cr0 &= ~X86_CR0_WP;
2963 }
2964
2965 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2966 {
2967         struct vcpu_vmx *vmx = to_vmx(vcpu);
2968         unsigned long hw_cr0;
2969
2970         if (enable_unrestricted_guest)
2971                 hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK_UNRESTRICTED_GUEST)
2972                         | KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
2973         else
2974                 hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK) | KVM_VM_CR0_ALWAYS_ON;
2975
2976         if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
2977                 enter_pmode(vcpu);
2978
2979         if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
2980                 enter_rmode(vcpu);
2981
2982 #ifdef CONFIG_X86_64
2983         if (vcpu->arch.efer & EFER_LME) {
2984                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
2985                         enter_lmode(vcpu);
2986                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
2987                         exit_lmode(vcpu);
2988         }
2989 #endif
2990
2991         if (enable_ept)
2992                 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
2993
2994         if (!vcpu->fpu_active)
2995                 hw_cr0 |= X86_CR0_TS | X86_CR0_MP;
2996
2997         vmcs_writel(CR0_READ_SHADOW, cr0);
2998         vmcs_writel(GUEST_CR0, hw_cr0);
2999         vcpu->arch.cr0 = cr0;
3000         __clear_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
3001 }
3002
3003 static u64 construct_eptp(unsigned long root_hpa)
3004 {
3005         u64 eptp;
3006
3007         /* TODO write the value reading from MSR */
3008         eptp = VMX_EPT_DEFAULT_MT |
3009                 VMX_EPT_DEFAULT_GAW << VMX_EPT_GAW_EPTP_SHIFT;
3010         eptp |= (root_hpa & PAGE_MASK);
3011
3012         return eptp;
3013 }
3014
3015 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
3016 {
3017         unsigned long guest_cr3;
3018         u64 eptp;
3019
3020         guest_cr3 = cr3;
3021         if (enable_ept) {
3022                 eptp = construct_eptp(cr3);
3023                 vmcs_write64(EPT_POINTER, eptp);
3024                 guest_cr3 = is_paging(vcpu) ? kvm_read_cr3(vcpu) :
3025                         vcpu->kvm->arch.ept_identity_map_addr;
3026                 ept_load_pdptrs(vcpu);
3027         }
3028
3029         vmx_flush_tlb(vcpu);
3030         vmcs_writel(GUEST_CR3, guest_cr3);
3031 }
3032
3033 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3034 {
3035         /*
3036          * Pass through host's Machine Check Enable value to hw_cr4, which
3037          * is in force while we are in guest mode.  Do not let guests control
3038          * this bit, even if host CR4.MCE == 0.
3039          */
3040         unsigned long hw_cr4 =
3041                 (read_cr4() & X86_CR4_MCE) |
3042                 (cr4 & ~X86_CR4_MCE) |
3043                 (to_vmx(vcpu)->rmode.vm86_active ?
3044                  KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
3045
3046         if (cr4 & X86_CR4_VMXE) {
3047                 /*
3048                  * To use VMXON (and later other VMX instructions), a guest
3049                  * must first be able to turn on cr4.VMXE (see handle_vmon()).
3050                  * So basically the check on whether to allow nested VMX
3051                  * is here.
3052                  */
3053                 if (!nested_vmx_allowed(vcpu))
3054                         return 1;
3055         } else if (to_vmx(vcpu)->nested.vmxon)
3056                 return 1;
3057
3058         vcpu->arch.cr4 = cr4;
3059         if (enable_ept) {
3060                 if (!is_paging(vcpu)) {
3061                         hw_cr4 &= ~X86_CR4_PAE;
3062                         hw_cr4 |= X86_CR4_PSE;
3063                 } else if (!(cr4 & X86_CR4_PAE)) {
3064                         hw_cr4 &= ~X86_CR4_PAE;
3065                 }
3066         }
3067
3068         vmcs_writel(CR4_READ_SHADOW, cr4);
3069         vmcs_writel(GUEST_CR4, hw_cr4);
3070         return 0;
3071 }
3072
3073 static void vmx_get_segment(struct kvm_vcpu *vcpu,
3074                             struct kvm_segment *var, int seg)
3075 {
3076         struct vcpu_vmx *vmx = to_vmx(vcpu);
3077         struct kvm_save_segment *save;
3078         u32 ar;
3079
3080         if (vmx->rmode.vm86_active
3081             && (seg == VCPU_SREG_TR || seg == VCPU_SREG_ES
3082                 || seg == VCPU_SREG_DS || seg == VCPU_SREG_FS
3083                 || seg == VCPU_SREG_GS)
3084             && !emulate_invalid_guest_state) {
3085                 switch (seg) {
3086                 case VCPU_SREG_TR: save = &vmx->rmode.tr; break;
3087                 case VCPU_SREG_ES: save = &vmx->rmode.es; break;
3088                 case VCPU_SREG_DS: save = &vmx->rmode.ds; break;
3089                 case VCPU_SREG_FS: save = &vmx->rmode.fs; break;
3090                 case VCPU_SREG_GS: save = &vmx->rmode.gs; break;
3091                 default: BUG();
3092                 }
3093                 var->selector = save->selector;
3094                 var->base = save->base;
3095                 var->limit = save->limit;
3096                 ar = save->ar;
3097                 if (seg == VCPU_SREG_TR
3098                     || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3099                         goto use_saved_rmode_seg;
3100         }
3101         var->base = vmx_read_guest_seg_base(vmx, seg);
3102         var->limit = vmx_read_guest_seg_limit(vmx, seg);
3103         var->selector = vmx_read_guest_seg_selector(vmx, seg);
3104         ar = vmx_read_guest_seg_ar(vmx, seg);
3105 use_saved_rmode_seg:
3106         if ((ar & AR_UNUSABLE_MASK) && !emulate_invalid_guest_state)
3107                 ar = 0;
3108         var->type = ar & 15;
3109         var->s = (ar >> 4) & 1;
3110         var->dpl = (ar >> 5) & 3;
3111         var->present = (ar >> 7) & 1;
3112         var->avl = (ar >> 12) & 1;
3113         var->l = (ar >> 13) & 1;
3114         var->db = (ar >> 14) & 1;
3115         var->g = (ar >> 15) & 1;
3116         var->unusable = (ar >> 16) & 1;
3117 }
3118
3119 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3120 {
3121         struct kvm_segment s;
3122
3123         if (to_vmx(vcpu)->rmode.vm86_active) {
3124                 vmx_get_segment(vcpu, &s, seg);
3125                 return s.base;
3126         }
3127         return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3128 }
3129
3130 static int __vmx_get_cpl(struct kvm_vcpu *vcpu)
3131 {
3132         if (!is_protmode(vcpu))
3133                 return 0;
3134
3135         if (!is_long_mode(vcpu)
3136             && (kvm_get_rflags(vcpu) & X86_EFLAGS_VM)) /* if virtual 8086 */
3137                 return 3;
3138
3139         return vmx_read_guest_seg_selector(to_vmx(vcpu), VCPU_SREG_CS) & 3;
3140 }
3141
3142 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
3143 {
3144         if (!test_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail)) {
3145                 __set_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
3146                 to_vmx(vcpu)->cpl = __vmx_get_cpl(vcpu);
3147         }
3148         return to_vmx(vcpu)->cpl;
3149 }
3150
3151
3152 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3153 {
3154         u32 ar;
3155
3156         if (var->unusable)
3157                 ar = 1 << 16;
3158         else {
3159                 ar = var->type & 15;
3160                 ar |= (var->s & 1) << 4;
3161                 ar |= (var->dpl & 3) << 5;
3162                 ar |= (var->present & 1) << 7;
3163                 ar |= (var->avl & 1) << 12;
3164                 ar |= (var->l & 1) << 13;
3165                 ar |= (var->db & 1) << 14;
3166                 ar |= (var->g & 1) << 15;
3167         }
3168         if (ar == 0) /* a 0 value means unusable */
3169                 ar = AR_UNUSABLE_MASK;
3170
3171         return ar;
3172 }
3173
3174 static void vmx_set_segment(struct kvm_vcpu *vcpu,
3175                             struct kvm_segment *var, int seg)
3176 {
3177         struct vcpu_vmx *vmx = to_vmx(vcpu);
3178         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3179         u32 ar;
3180
3181         vmx_segment_cache_clear(vmx);
3182
3183         if (vmx->rmode.vm86_active && seg == VCPU_SREG_TR) {
3184                 vmcs_write16(sf->selector, var->selector);
3185                 vmx->rmode.tr.selector = var->selector;
3186                 vmx->rmode.tr.base = var->base;
3187                 vmx->rmode.tr.limit = var->limit;
3188                 vmx->rmode.tr.ar = vmx_segment_access_rights(var);
3189                 return;
3190         }
3191         vmcs_writel(sf->base, var->base);
3192         vmcs_write32(sf->limit, var->limit);
3193         vmcs_write16(sf->selector, var->selector);
3194         if (vmx->rmode.vm86_active && var->s) {
3195                 /*
3196                  * Hack real-mode segments into vm86 compatibility.
3197                  */
3198                 if (var->base == 0xffff0000 && var->selector == 0xf000)
3199                         vmcs_writel(sf->base, 0xf0000);
3200                 ar = 0xf3;
3201         } else
3202                 ar = vmx_segment_access_rights(var);
3203
3204         /*
3205          *   Fix the "Accessed" bit in AR field of segment registers for older
3206          * qemu binaries.
3207          *   IA32 arch specifies that at the time of processor reset the
3208          * "Accessed" bit in the AR field of segment registers is 1. And qemu
3209          * is setting it to 0 in the usedland code. This causes invalid guest
3210          * state vmexit when "unrestricted guest" mode is turned on.
3211          *    Fix for this setup issue in cpu_reset is being pushed in the qemu
3212          * tree. Newer qemu binaries with that qemu fix would not need this
3213          * kvm hack.
3214          */
3215         if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
3216                 ar |= 0x1; /* Accessed */
3217
3218         vmcs_write32(sf->ar_bytes, ar);
3219         __clear_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
3220 }
3221
3222 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3223 {
3224         u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3225
3226         *db = (ar >> 14) & 1;
3227         *l = (ar >> 13) & 1;
3228 }
3229
3230 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3231 {
3232         dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3233         dt->address = vmcs_readl(GUEST_IDTR_BASE);
3234 }
3235
3236 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3237 {
3238         vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3239         vmcs_writel(GUEST_IDTR_BASE, dt->address);
3240 }
3241
3242 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3243 {
3244         dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3245         dt->address = vmcs_readl(GUEST_GDTR_BASE);
3246 }
3247
3248 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3249 {
3250         vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3251         vmcs_writel(GUEST_GDTR_BASE, dt->address);
3252 }
3253
3254 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3255 {
3256         struct kvm_segment var;
3257         u32 ar;
3258
3259         vmx_get_segment(vcpu, &var, seg);
3260         ar = vmx_segment_access_rights(&var);
3261
3262         if (var.base != (var.selector << 4))
3263                 return false;
3264         if (var.limit != 0xffff)
3265                 return false;
3266         if (ar != 0xf3)
3267                 return false;
3268
3269         return true;
3270 }
3271
3272 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3273 {
3274         struct kvm_segment cs;
3275         unsigned int cs_rpl;
3276
3277         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3278         cs_rpl = cs.selector & SELECTOR_RPL_MASK;
3279
3280         if (cs.unusable)
3281                 return false;
3282         if (~cs.type & (AR_TYPE_CODE_MASK|AR_TYPE_ACCESSES_MASK))
3283                 return false;
3284         if (!cs.s)
3285                 return false;
3286         if (cs.type & AR_TYPE_WRITEABLE_MASK) {
3287                 if (cs.dpl > cs_rpl)
3288                         return false;
3289         } else {
3290                 if (cs.dpl != cs_rpl)
3291                         return false;
3292         }
3293         if (!cs.present)
3294                 return false;
3295
3296         /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3297         return true;
3298 }
3299
3300 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3301 {
3302         struct kvm_segment ss;
3303         unsigned int ss_rpl;
3304
3305         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3306         ss_rpl = ss.selector & SELECTOR_RPL_MASK;
3307
3308         if (ss.unusable)
3309                 return true;
3310         if (ss.type != 3 && ss.type != 7)
3311                 return false;
3312         if (!ss.s)
3313                 return false;
3314         if (ss.dpl != ss_rpl) /* DPL != RPL */
3315                 return false;
3316         if (!ss.present)
3317                 return false;
3318
3319         return true;
3320 }
3321
3322 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3323 {
3324         struct kvm_segment var;
3325         unsigned int rpl;
3326
3327         vmx_get_segment(vcpu, &var, seg);
3328         rpl = var.selector & SELECTOR_RPL_MASK;
3329
3330         if (var.unusable)
3331                 return true;
3332         if (!var.s)
3333                 return false;
3334         if (!var.present)
3335                 return false;
3336         if (~var.type & (AR_TYPE_CODE_MASK|AR_TYPE_WRITEABLE_MASK)) {
3337                 if (var.dpl < rpl) /* DPL < RPL */
3338                         return false;
3339         }
3340
3341         /* TODO: Add other members to kvm_segment_field to allow checking for other access
3342          * rights flags
3343          */
3344         return true;
3345 }
3346
3347 static bool tr_valid(struct kvm_vcpu *vcpu)
3348 {
3349         struct kvm_segment tr;
3350
3351         vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3352
3353         if (tr.unusable)
3354                 return false;
3355         if (tr.selector & SELECTOR_TI_MASK)     /* TI = 1 */
3356                 return false;
3357         if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3358                 return false;
3359         if (!tr.present)
3360                 return false;
3361
3362         return true;
3363 }
3364
3365 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3366 {
3367         struct kvm_segment ldtr;
3368
3369         vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3370
3371         if (ldtr.unusable)
3372                 return true;
3373         if (ldtr.selector & SELECTOR_TI_MASK)   /* TI = 1 */
3374                 return false;
3375         if (ldtr.type != 2)
3376                 return false;
3377         if (!ldtr.present)
3378                 return false;
3379
3380         return true;
3381 }
3382
3383 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3384 {
3385         struct kvm_segment cs, ss;
3386
3387         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3388         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3389
3390         return ((cs.selector & SELECTOR_RPL_MASK) ==
3391                  (ss.selector & SELECTOR_RPL_MASK));
3392 }
3393
3394 /*
3395  * Check if guest state is valid. Returns true if valid, false if
3396  * not.
3397  * We assume that registers are always usable
3398  */
3399 static bool guest_state_valid(struct kvm_vcpu *vcpu)
3400 {
3401         /* real mode guest state checks */
3402         if (!is_protmode(vcpu)) {
3403                 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3404                         return false;
3405                 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3406                         return false;
3407                 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3408                         return false;
3409                 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3410                         return false;
3411                 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3412                         return false;
3413                 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3414                         return false;
3415         } else {
3416         /* protected mode guest state checks */
3417                 if (!cs_ss_rpl_check(vcpu))
3418                         return false;
3419                 if (!code_segment_valid(vcpu))
3420                         return false;
3421                 if (!stack_segment_valid(vcpu))
3422                         return false;
3423                 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3424                         return false;
3425                 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3426                         return false;
3427                 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3428                         return false;
3429                 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3430                         return false;
3431                 if (!tr_valid(vcpu))
3432                         return false;
3433                 if (!ldtr_valid(vcpu))
3434                         return false;
3435         }
3436         /* TODO:
3437          * - Add checks on RIP
3438          * - Add checks on RFLAGS
3439          */
3440
3441         return true;
3442 }
3443
3444 static int init_rmode_tss(struct kvm *kvm)
3445 {
3446         gfn_t fn;
3447         u16 data = 0;
3448         int r, idx, ret = 0;
3449
3450         idx = srcu_read_lock(&kvm->srcu);
3451         fn = rmode_tss_base(kvm) >> PAGE_SHIFT;
3452         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3453         if (r < 0)
3454                 goto out;
3455         data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3456         r = kvm_write_guest_page(kvm, fn++, &data,
3457                         TSS_IOPB_BASE_OFFSET, sizeof(u16));
3458         if (r < 0)
3459                 goto out;
3460         r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
3461         if (r < 0)
3462                 goto out;
3463         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3464         if (r < 0)
3465                 goto out;
3466         data = ~0;
3467         r = kvm_write_guest_page(kvm, fn, &data,
3468                                  RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
3469                                  sizeof(u8));
3470         if (r < 0)
3471                 goto out;
3472
3473         ret = 1;
3474 out:
3475         srcu_read_unlock(&kvm->srcu, idx);
3476         return ret;
3477 }
3478
3479 static int init_rmode_identity_map(struct kvm *kvm)
3480 {
3481         int i, idx, r, ret;
3482         pfn_t identity_map_pfn;
3483         u32 tmp;
3484
3485         if (!enable_ept)
3486                 return 1;
3487         if (unlikely(!kvm->arch.ept_identity_pagetable)) {
3488                 printk(KERN_ERR "EPT: identity-mapping pagetable "
3489                         "haven't been allocated!\n");
3490                 return 0;
3491         }
3492         if (likely(kvm->arch.ept_identity_pagetable_done))
3493                 return 1;
3494         ret = 0;
3495         identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
3496         idx = srcu_read_lock(&kvm->srcu);
3497         r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
3498         if (r < 0)
3499                 goto out;
3500         /* Set up identity-mapping pagetable for EPT in real mode */
3501         for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3502                 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3503                         _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3504                 r = kvm_write_guest_page(kvm, identity_map_pfn,
3505                                 &tmp, i * sizeof(tmp), sizeof(tmp));
3506                 if (r < 0)
3507                         goto out;
3508         }
3509         kvm->arch.ept_identity_pagetable_done = true;
3510         ret = 1;
3511 out:
3512         srcu_read_unlock(&kvm->srcu, idx);
3513         return ret;
3514 }
3515
3516 static void seg_setup(int seg)
3517 {
3518         struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3519         unsigned int ar;
3520
3521         vmcs_write16(sf->selector, 0);
3522         vmcs_writel(sf->base, 0);
3523         vmcs_write32(sf->limit, 0xffff);
3524         if (enable_unrestricted_guest) {
3525                 ar = 0x93;
3526                 if (seg == VCPU_SREG_CS)
3527                         ar |= 0x08; /* code segment */
3528         } else
3529                 ar = 0xf3;
3530
3531         vmcs_write32(sf->ar_bytes, ar);
3532 }
3533
3534 static int alloc_apic_access_page(struct kvm *kvm)
3535 {
3536         struct kvm_userspace_memory_region kvm_userspace_mem;
3537         int r = 0;
3538
3539         mutex_lock(&kvm->slots_lock);
3540         if (kvm->arch.apic_access_page)
3541                 goto out;
3542         kvm_userspace_mem.slot = APIC_ACCESS_PAGE_PRIVATE_MEMSLOT;
3543         kvm_userspace_mem.flags = 0;
3544         kvm_userspace_mem.guest_phys_addr = 0xfee00000ULL;
3545         kvm_userspace_mem.memory_size = PAGE_SIZE;
3546         r = __kvm_set_memory_region(kvm, &kvm_userspace_mem, 0);
3547         if (r)
3548                 goto out;
3549
3550         kvm->arch.apic_access_page = gfn_to_page(kvm, 0xfee00);
3551 out:
3552         mutex_unlock(&kvm->slots_lock);
3553         return r;
3554 }
3555
3556 static int alloc_identity_pagetable(struct kvm *kvm)
3557 {
3558         struct kvm_userspace_memory_region kvm_userspace_mem;
3559         int r = 0;
3560
3561         mutex_lock(&kvm->slots_lock);
3562         if (kvm->arch.ept_identity_pagetable)
3563                 goto out;
3564         kvm_userspace_mem.slot = IDENTITY_PAGETABLE_PRIVATE_MEMSLOT;
3565         kvm_userspace_mem.flags = 0;
3566         kvm_userspace_mem.guest_phys_addr =
3567                 kvm->arch.ept_identity_map_addr;
3568         kvm_userspace_mem.memory_size = PAGE_SIZE;
3569         r = __kvm_set_memory_region(kvm, &kvm_userspace_mem, 0);
3570         if (r)
3571                 goto out;
3572
3573         kvm->arch.ept_identity_pagetable = gfn_to_page(kvm,
3574                         kvm->arch.ept_identity_map_addr >> PAGE_SHIFT);
3575 out:
3576         mutex_unlock(&kvm->slots_lock);
3577         return r;
3578 }
3579
3580 static void allocate_vpid(struct vcpu_vmx *vmx)
3581 {
3582         int vpid;
3583
3584         vmx->vpid = 0;
3585         if (!enable_vpid)
3586                 return;
3587         spin_lock(&vmx_vpid_lock);
3588         vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3589         if (vpid < VMX_NR_VPIDS) {
3590                 vmx->vpid = vpid;
3591                 __set_bit(vpid, vmx_vpid_bitmap);
3592         }
3593         spin_unlock(&vmx_vpid_lock);
3594 }
3595
3596 static void free_vpid(struct vcpu_vmx *vmx)
3597 {
3598         if (!enable_vpid)
3599                 return;
3600         spin_lock(&vmx_vpid_lock);
3601         if (vmx->vpid != 0)
3602                 __clear_bit(vmx->vpid, vmx_vpid_bitmap);
3603         spin_unlock(&vmx_vpid_lock);
3604 }
3605
3606 static void __vmx_disable_intercept_for_msr(unsigned long *msr_bitmap, u32 msr)
3607 {
3608         int f = sizeof(unsigned long);
3609
3610         if (!cpu_has_vmx_msr_bitmap())
3611                 return;
3612
3613         /*
3614          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3615          * have the write-low and read-high bitmap offsets the wrong way round.
3616          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3617          */
3618         if (msr <= 0x1fff) {
3619                 __clear_bit(msr, msr_bitmap + 0x000 / f); /* read-low */
3620                 __clear_bit(msr, msr_bitmap + 0x800 / f); /* write-low */
3621         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3622                 msr &= 0x1fff;
3623                 __clear_bit(msr, msr_bitmap + 0x400 / f); /* read-high */
3624                 __clear_bit(msr, msr_bitmap + 0xc00 / f); /* write-high */
3625         }
3626 }
3627
3628 static void vmx_disable_intercept_for_msr(u32 msr, bool longmode_only)
3629 {
3630         if (!longmode_only)
3631                 __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy, msr);
3632         __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode, msr);
3633 }
3634
3635 /*
3636  * Set up the vmcs's constant host-state fields, i.e., host-state fields that
3637  * will not change in the lifetime of the guest.
3638  * Note that host-state that does change is set elsewhere. E.g., host-state
3639  * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
3640  */
3641 static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
3642 {
3643         u32 low32, high32;
3644         unsigned long tmpl;
3645         struct desc_ptr dt;
3646         unsigned long cr4;
3647
3648         vmcs_writel(HOST_CR0, read_cr0() | X86_CR0_TS);  /* 22.2.3 */
3649         vmcs_writel(HOST_CR3, read_cr3());  /* 22.2.3  FIXME: shadow tables */
3650
3651         /* Save the most likely value for this task's CR4 in the VMCS. */
3652         cr4 = read_cr4();
3653         vmcs_writel(HOST_CR4, cr4);                     /* 22.2.3, 22.2.5 */
3654         vmx->host_state.vmcs_host_cr4 = cr4;
3655
3656         vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
3657         vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
3658         vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
3659         vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
3660         vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
3661
3662         native_store_idt(&dt);
3663         vmcs_writel(HOST_IDTR_BASE, dt.address);   /* 22.2.4 */
3664
3665         asm("mov $.Lkvm_vmx_return, %0" : "=r"(tmpl));
3666         vmcs_writel(HOST_RIP, tmpl); /* 22.2.5 */
3667
3668         rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
3669         vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
3670         rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
3671         vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl);   /* 22.2.3 */
3672
3673         if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
3674                 rdmsr(MSR_IA32_CR_PAT, low32, high32);
3675                 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
3676         }
3677 }
3678
3679 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
3680 {
3681         vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
3682         if (enable_ept)
3683                 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
3684         if (is_guest_mode(&vmx->vcpu))
3685                 vmx->vcpu.arch.cr4_guest_owned_bits &=
3686                         ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
3687         vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
3688 }
3689
3690 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
3691 {
3692         u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
3693         if (!vm_need_tpr_shadow(vmx->vcpu.kvm)) {
3694                 exec_control &= ~CPU_BASED_TPR_SHADOW;
3695 #ifdef CONFIG_X86_64
3696                 exec_control |= CPU_BASED_CR8_STORE_EXITING |
3697                                 CPU_BASED_CR8_LOAD_EXITING;
3698 #endif
3699         }
3700         if (!enable_ept)
3701                 exec_control |= CPU_BASED_CR3_STORE_EXITING |
3702                                 CPU_BASED_CR3_LOAD_EXITING  |
3703                                 CPU_BASED_INVLPG_EXITING;
3704         return exec_control;
3705 }
3706
3707 static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
3708 {
3709         u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
3710         if (!vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
3711                 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
3712         if (vmx->vpid == 0)
3713                 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
3714         if (!enable_ept) {
3715                 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
3716                 enable_unrestricted_guest = 0;
3717         }
3718         if (!enable_unrestricted_guest)
3719                 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
3720         if (!ple_gap)
3721                 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
3722         return exec_control;
3723 }
3724
3725 static void ept_set_mmio_spte_mask(void)
3726 {
3727         /*
3728          * EPT Misconfigurations can be generated if the value of bits 2:0
3729          * of an EPT paging-structure entry is 110b (write/execute).
3730          * Also, magic bits (0xffull << 49) is set to quickly identify mmio
3731          * spte.
3732          */
3733         kvm_mmu_set_mmio_spte_mask(0xffull << 49 | 0x6ull);
3734 }
3735
3736 /*
3737  * Sets up the vmcs for emulated real mode.
3738  */
3739 static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
3740 {
3741 #ifdef CONFIG_X86_64
3742         unsigned long a;
3743 #endif
3744         int i;
3745
3746         /* I/O */
3747         vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
3748         vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));
3749
3750         if (cpu_has_vmx_msr_bitmap())
3751                 vmcs_write64(MSR_BITMAP, __pa(vmx_msr_bitmap_legacy));
3752
3753         vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
3754
3755         /* Control */
3756         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL,
3757                 vmcs_config.pin_based_exec_ctrl);
3758
3759         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
3760
3761         if (cpu_has_secondary_exec_ctrls()) {
3762                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
3763                                 vmx_secondary_exec_control(vmx));
3764         }
3765
3766         if (ple_gap) {
3767                 vmcs_write32(PLE_GAP, ple_gap);
3768                 vmcs_write32(PLE_WINDOW, ple_window);
3769         }
3770
3771         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
3772         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
3773         vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
3774
3775         vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
3776         vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
3777         vmx_set_constant_host_state(vmx);
3778 #ifdef CONFIG_X86_64
3779         rdmsrl(MSR_FS_BASE, a);
3780         vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
3781         rdmsrl(MSR_GS_BASE, a);
3782         vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
3783 #else
3784         vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
3785         vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
3786 #endif
3787
3788         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
3789         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
3790         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
3791         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
3792         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
3793
3794         if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
3795                 u32 msr_low, msr_high;
3796                 u64 host_pat;
3797                 rdmsr(MSR_IA32_CR_PAT, msr_low, msr_high);
3798                 host_pat = msr_low | ((u64) msr_high << 32);
3799                 /* Write the default value follow host pat */
3800                 vmcs_write64(GUEST_IA32_PAT, host_pat);
3801                 /* Keep arch.pat sync with GUEST_IA32_PAT */
3802                 vmx->vcpu.arch.pat = host_pat;
3803         }
3804
3805         for (i = 0; i < NR_VMX_MSR; ++i) {
3806                 u32 index = vmx_msr_index[i];
3807                 u32 data_low, data_high;
3808                 int j = vmx->nmsrs;
3809
3810                 if (rdmsr_safe(index, &data_low, &data_high) < 0)
3811                         continue;
3812                 if (wrmsr_safe(index, data_low, data_high) < 0)
3813                         continue;
3814                 vmx->guest_msrs[j].index = i;
3815                 vmx->guest_msrs[j].data = 0;
3816                 vmx->guest_msrs[j].mask = -1ull;
3817                 ++vmx->nmsrs;
3818         }
3819
3820         vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
3821
3822         /* 22.2.1, 20.8.1 */
3823         vmcs_write32(VM_ENTRY_CONTROLS, vmcs_config.vmentry_ctrl);
3824
3825         vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL);
3826         set_cr4_guest_host_mask(vmx);
3827
3828         kvm_write_tsc(&vmx->vcpu, 0);
3829
3830         return 0;
3831 }
3832
3833 static int vmx_vcpu_reset(struct kvm_vcpu *vcpu)
3834 {
3835         struct vcpu_vmx *vmx = to_vmx(vcpu);
3836         u64 msr;
3837         int ret;
3838
3839         vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP));
3840
3841         vmx->rmode.vm86_active = 0;
3842
3843         vmx->soft_vnmi_blocked = 0;
3844
3845         vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
3846         kvm_set_cr8(&vmx->vcpu, 0);
3847         msr = 0xfee00000 | MSR_IA32_APICBASE_ENABLE;
3848         if (kvm_vcpu_is_bsp(&vmx->vcpu))
3849                 msr |= MSR_IA32_APICBASE_BSP;
3850         kvm_set_apic_base(&vmx->vcpu, msr);
3851
3852         ret = fx_init(&vmx->vcpu);
3853         if (ret != 0)
3854                 goto out;
3855
3856         vmx_segment_cache_clear(vmx);
3857
3858         seg_setup(VCPU_SREG_CS);
3859         /*
3860          * GUEST_CS_BASE should really be 0xffff0000, but VT vm86 mode
3861          * insists on having GUEST_CS_BASE == GUEST_CS_SELECTOR << 4.  Sigh.
3862          */
3863         if (kvm_vcpu_is_bsp(&vmx->vcpu)) {
3864                 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
3865                 vmcs_writel(GUEST_CS_BASE, 0x000f0000);
3866         } else {
3867                 vmcs_write16(GUEST_CS_SELECTOR, vmx->vcpu.arch.sipi_vector << 8);
3868                 vmcs_writel(GUEST_CS_BASE, vmx->vcpu.arch.sipi_vector << 12);
3869         }
3870
3871         seg_setup(VCPU_SREG_DS);
3872         seg_setup(VCPU_SREG_ES);
3873         seg_setup(VCPU_SREG_FS);
3874         seg_setup(VCPU_SREG_GS);
3875         seg_setup(VCPU_SREG_SS);