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