kvm: nVMX: Fix fault priority for VMX operations
[linux-2.6-microblaze.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 #include "lapic.h"
23
24 #include <linux/kvm_host.h>
25 #include <linux/module.h>
26 #include <linux/kernel.h>
27 #include <linux/mm.h>
28 #include <linux/highmem.h>
29 #include <linux/sched.h>
30 #include <linux/moduleparam.h>
31 #include <linux/mod_devicetable.h>
32 #include <linux/trace_events.h>
33 #include <linux/slab.h>
34 #include <linux/tboot.h>
35 #include <linux/hrtimer.h>
36 #include <linux/frame.h>
37 #include <linux/nospec.h>
38 #include "kvm_cache_regs.h"
39 #include "x86.h"
40
41 #include <asm/cpu.h>
42 #include <asm/io.h>
43 #include <asm/desc.h>
44 #include <asm/vmx.h>
45 #include <asm/virtext.h>
46 #include <asm/mce.h>
47 #include <asm/fpu/internal.h>
48 #include <asm/perf_event.h>
49 #include <asm/debugreg.h>
50 #include <asm/kexec.h>
51 #include <asm/apic.h>
52 #include <asm/irq_remapping.h>
53 #include <asm/mmu_context.h>
54 #include <asm/spec-ctrl.h>
55 #include <asm/mshyperv.h>
56
57 #include "trace.h"
58 #include "pmu.h"
59 #include "vmx_evmcs.h"
60
61 #define __ex(x) __kvm_handle_fault_on_reboot(x)
62 #define __ex_clear(x, reg) \
63         ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
64
65 MODULE_AUTHOR("Qumranet");
66 MODULE_LICENSE("GPL");
67
68 static const struct x86_cpu_id vmx_cpu_id[] = {
69         X86_FEATURE_MATCH(X86_FEATURE_VMX),
70         {}
71 };
72 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
73
74 static bool __read_mostly enable_vpid = 1;
75 module_param_named(vpid, enable_vpid, bool, 0444);
76
77 static bool __read_mostly enable_vnmi = 1;
78 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
79
80 static bool __read_mostly flexpriority_enabled = 1;
81 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
82
83 static bool __read_mostly enable_ept = 1;
84 module_param_named(ept, enable_ept, bool, S_IRUGO);
85
86 static bool __read_mostly enable_unrestricted_guest = 1;
87 module_param_named(unrestricted_guest,
88                         enable_unrestricted_guest, bool, S_IRUGO);
89
90 static bool __read_mostly enable_ept_ad_bits = 1;
91 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
92
93 static bool __read_mostly emulate_invalid_guest_state = true;
94 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
95
96 static bool __read_mostly fasteoi = 1;
97 module_param(fasteoi, bool, S_IRUGO);
98
99 static bool __read_mostly enable_apicv = 1;
100 module_param(enable_apicv, bool, S_IRUGO);
101
102 static bool __read_mostly enable_shadow_vmcs = 1;
103 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
104 /*
105  * If nested=1, nested virtualization is supported, i.e., guests may use
106  * VMX and be a hypervisor for its own guests. If nested=0, guests may not
107  * use VMX instructions.
108  */
109 static bool __read_mostly nested = 0;
110 module_param(nested, bool, S_IRUGO);
111
112 static u64 __read_mostly host_xss;
113
114 static bool __read_mostly enable_pml = 1;
115 module_param_named(pml, enable_pml, bool, S_IRUGO);
116
117 #define MSR_TYPE_R      1
118 #define MSR_TYPE_W      2
119 #define MSR_TYPE_RW     3
120
121 #define MSR_BITMAP_MODE_X2APIC          1
122 #define MSR_BITMAP_MODE_X2APIC_APICV    2
123 #define MSR_BITMAP_MODE_LM              4
124
125 #define KVM_VMX_TSC_MULTIPLIER_MAX     0xffffffffffffffffULL
126
127 /* Guest_tsc -> host_tsc conversion requires 64-bit division.  */
128 static int __read_mostly cpu_preemption_timer_multi;
129 static bool __read_mostly enable_preemption_timer = 1;
130 #ifdef CONFIG_X86_64
131 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
132 #endif
133
134 #define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
135 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
136 #define KVM_VM_CR0_ALWAYS_ON                            \
137         (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST |      \
138          X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
139 #define KVM_CR4_GUEST_OWNED_BITS                                      \
140         (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR      \
141          | X86_CR4_OSXMMEXCPT | X86_CR4_LA57 | X86_CR4_TSD)
142
143 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
144 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
145 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
146
147 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
148
149 #define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
150
151 /*
152  * Hyper-V requires all of these, so mark them as supported even though
153  * they are just treated the same as all-context.
154  */
155 #define VMX_VPID_EXTENT_SUPPORTED_MASK          \
156         (VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT |  \
157         VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT |    \
158         VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT |    \
159         VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
160
161 /*
162  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
163  * ple_gap:    upper bound on the amount of time between two successive
164  *             executions of PAUSE in a loop. Also indicate if ple enabled.
165  *             According to test, this time is usually smaller than 128 cycles.
166  * ple_window: upper bound on the amount of time a guest is allowed to execute
167  *             in a PAUSE loop. Tests indicate that most spinlocks are held for
168  *             less than 2^12 cycles
169  * Time is measured based on a counter that runs at the same rate as the TSC,
170  * refer SDM volume 3b section 21.6.13 & 22.1.3.
171  */
172 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
173
174 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
175 module_param(ple_window, uint, 0444);
176
177 /* Default doubles per-vcpu window every exit. */
178 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
179 module_param(ple_window_grow, uint, 0444);
180
181 /* Default resets per-vcpu window every exit to ple_window. */
182 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
183 module_param(ple_window_shrink, uint, 0444);
184
185 /* Default is to compute the maximum so we can never overflow. */
186 static unsigned int ple_window_max        = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
187 module_param(ple_window_max, uint, 0444);
188
189 extern const ulong vmx_return;
190
191 enum ept_pointers_status {
192         EPT_POINTERS_CHECK = 0,
193         EPT_POINTERS_MATCH = 1,
194         EPT_POINTERS_MISMATCH = 2
195 };
196
197 struct kvm_vmx {
198         struct kvm kvm;
199
200         unsigned int tss_addr;
201         bool ept_identity_pagetable_done;
202         gpa_t ept_identity_map_addr;
203
204         enum ept_pointers_status ept_pointers_match;
205         spinlock_t ept_pointer_lock;
206 };
207
208 #define NR_AUTOLOAD_MSRS 8
209
210 struct vmcs_hdr {
211         u32 revision_id:31;
212         u32 shadow_vmcs:1;
213 };
214
215 struct vmcs {
216         struct vmcs_hdr hdr;
217         u32 abort;
218         char data[0];
219 };
220
221 /*
222  * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
223  * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
224  * loaded on this CPU (so we can clear them if the CPU goes down).
225  */
226 struct loaded_vmcs {
227         struct vmcs *vmcs;
228         struct vmcs *shadow_vmcs;
229         int cpu;
230         bool launched;
231         bool nmi_known_unmasked;
232         unsigned long vmcs_host_cr3;    /* May not match real cr3 */
233         unsigned long vmcs_host_cr4;    /* May not match real cr4 */
234         /* Support for vnmi-less CPUs */
235         int soft_vnmi_blocked;
236         ktime_t entry_time;
237         s64 vnmi_blocked_time;
238         unsigned long *msr_bitmap;
239         struct list_head loaded_vmcss_on_cpu_link;
240 };
241
242 struct shared_msr_entry {
243         unsigned index;
244         u64 data;
245         u64 mask;
246 };
247
248 /*
249  * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
250  * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
251  * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
252  * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
253  * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
254  * More than one of these structures may exist, if L1 runs multiple L2 guests.
255  * nested_vmx_run() will use the data here to build the vmcs02: a VMCS for the
256  * underlying hardware which will be used to run L2.
257  * This structure is packed to ensure that its layout is identical across
258  * machines (necessary for live migration).
259  *
260  * IMPORTANT: Changing the layout of existing fields in this structure
261  * will break save/restore compatibility with older kvm releases. When
262  * adding new fields, either use space in the reserved padding* arrays
263  * or add the new fields to the end of the structure.
264  */
265 typedef u64 natural_width;
266 struct __packed vmcs12 {
267         /* According to the Intel spec, a VMCS region must start with the
268          * following two fields. Then follow implementation-specific data.
269          */
270         struct vmcs_hdr hdr;
271         u32 abort;
272
273         u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
274         u32 padding[7]; /* room for future expansion */
275
276         u64 io_bitmap_a;
277         u64 io_bitmap_b;
278         u64 msr_bitmap;
279         u64 vm_exit_msr_store_addr;
280         u64 vm_exit_msr_load_addr;
281         u64 vm_entry_msr_load_addr;
282         u64 tsc_offset;
283         u64 virtual_apic_page_addr;
284         u64 apic_access_addr;
285         u64 posted_intr_desc_addr;
286         u64 ept_pointer;
287         u64 eoi_exit_bitmap0;
288         u64 eoi_exit_bitmap1;
289         u64 eoi_exit_bitmap2;
290         u64 eoi_exit_bitmap3;
291         u64 xss_exit_bitmap;
292         u64 guest_physical_address;
293         u64 vmcs_link_pointer;
294         u64 guest_ia32_debugctl;
295         u64 guest_ia32_pat;
296         u64 guest_ia32_efer;
297         u64 guest_ia32_perf_global_ctrl;
298         u64 guest_pdptr0;
299         u64 guest_pdptr1;
300         u64 guest_pdptr2;
301         u64 guest_pdptr3;
302         u64 guest_bndcfgs;
303         u64 host_ia32_pat;
304         u64 host_ia32_efer;
305         u64 host_ia32_perf_global_ctrl;
306         u64 vmread_bitmap;
307         u64 vmwrite_bitmap;
308         u64 vm_function_control;
309         u64 eptp_list_address;
310         u64 pml_address;
311         u64 padding64[3]; /* room for future expansion */
312         /*
313          * To allow migration of L1 (complete with its L2 guests) between
314          * machines of different natural widths (32 or 64 bit), we cannot have
315          * unsigned long fields with no explict size. We use u64 (aliased
316          * natural_width) instead. Luckily, x86 is little-endian.
317          */
318         natural_width cr0_guest_host_mask;
319         natural_width cr4_guest_host_mask;
320         natural_width cr0_read_shadow;
321         natural_width cr4_read_shadow;
322         natural_width cr3_target_value0;
323         natural_width cr3_target_value1;
324         natural_width cr3_target_value2;
325         natural_width cr3_target_value3;
326         natural_width exit_qualification;
327         natural_width guest_linear_address;
328         natural_width guest_cr0;
329         natural_width guest_cr3;
330         natural_width guest_cr4;
331         natural_width guest_es_base;
332         natural_width guest_cs_base;
333         natural_width guest_ss_base;
334         natural_width guest_ds_base;
335         natural_width guest_fs_base;
336         natural_width guest_gs_base;
337         natural_width guest_ldtr_base;
338         natural_width guest_tr_base;
339         natural_width guest_gdtr_base;
340         natural_width guest_idtr_base;
341         natural_width guest_dr7;
342         natural_width guest_rsp;
343         natural_width guest_rip;
344         natural_width guest_rflags;
345         natural_width guest_pending_dbg_exceptions;
346         natural_width guest_sysenter_esp;
347         natural_width guest_sysenter_eip;
348         natural_width host_cr0;
349         natural_width host_cr3;
350         natural_width host_cr4;
351         natural_width host_fs_base;
352         natural_width host_gs_base;
353         natural_width host_tr_base;
354         natural_width host_gdtr_base;
355         natural_width host_idtr_base;
356         natural_width host_ia32_sysenter_esp;
357         natural_width host_ia32_sysenter_eip;
358         natural_width host_rsp;
359         natural_width host_rip;
360         natural_width paddingl[8]; /* room for future expansion */
361         u32 pin_based_vm_exec_control;
362         u32 cpu_based_vm_exec_control;
363         u32 exception_bitmap;
364         u32 page_fault_error_code_mask;
365         u32 page_fault_error_code_match;
366         u32 cr3_target_count;
367         u32 vm_exit_controls;
368         u32 vm_exit_msr_store_count;
369         u32 vm_exit_msr_load_count;
370         u32 vm_entry_controls;
371         u32 vm_entry_msr_load_count;
372         u32 vm_entry_intr_info_field;
373         u32 vm_entry_exception_error_code;
374         u32 vm_entry_instruction_len;
375         u32 tpr_threshold;
376         u32 secondary_vm_exec_control;
377         u32 vm_instruction_error;
378         u32 vm_exit_reason;
379         u32 vm_exit_intr_info;
380         u32 vm_exit_intr_error_code;
381         u32 idt_vectoring_info_field;
382         u32 idt_vectoring_error_code;
383         u32 vm_exit_instruction_len;
384         u32 vmx_instruction_info;
385         u32 guest_es_limit;
386         u32 guest_cs_limit;
387         u32 guest_ss_limit;
388         u32 guest_ds_limit;
389         u32 guest_fs_limit;
390         u32 guest_gs_limit;
391         u32 guest_ldtr_limit;
392         u32 guest_tr_limit;
393         u32 guest_gdtr_limit;
394         u32 guest_idtr_limit;
395         u32 guest_es_ar_bytes;
396         u32 guest_cs_ar_bytes;
397         u32 guest_ss_ar_bytes;
398         u32 guest_ds_ar_bytes;
399         u32 guest_fs_ar_bytes;
400         u32 guest_gs_ar_bytes;
401         u32 guest_ldtr_ar_bytes;
402         u32 guest_tr_ar_bytes;
403         u32 guest_interruptibility_info;
404         u32 guest_activity_state;
405         u32 guest_sysenter_cs;
406         u32 host_ia32_sysenter_cs;
407         u32 vmx_preemption_timer_value;
408         u32 padding32[7]; /* room for future expansion */
409         u16 virtual_processor_id;
410         u16 posted_intr_nv;
411         u16 guest_es_selector;
412         u16 guest_cs_selector;
413         u16 guest_ss_selector;
414         u16 guest_ds_selector;
415         u16 guest_fs_selector;
416         u16 guest_gs_selector;
417         u16 guest_ldtr_selector;
418         u16 guest_tr_selector;
419         u16 guest_intr_status;
420         u16 host_es_selector;
421         u16 host_cs_selector;
422         u16 host_ss_selector;
423         u16 host_ds_selector;
424         u16 host_fs_selector;
425         u16 host_gs_selector;
426         u16 host_tr_selector;
427         u16 guest_pml_index;
428 };
429
430 /*
431  * For save/restore compatibility, the vmcs12 field offsets must not change.
432  */
433 #define CHECK_OFFSET(field, loc)                                \
434         BUILD_BUG_ON_MSG(offsetof(struct vmcs12, field) != (loc),       \
435                 "Offset of " #field " in struct vmcs12 has changed.")
436
437 static inline void vmx_check_vmcs12_offsets(void) {
438         CHECK_OFFSET(hdr, 0);
439         CHECK_OFFSET(abort, 4);
440         CHECK_OFFSET(launch_state, 8);
441         CHECK_OFFSET(io_bitmap_a, 40);
442         CHECK_OFFSET(io_bitmap_b, 48);
443         CHECK_OFFSET(msr_bitmap, 56);
444         CHECK_OFFSET(vm_exit_msr_store_addr, 64);
445         CHECK_OFFSET(vm_exit_msr_load_addr, 72);
446         CHECK_OFFSET(vm_entry_msr_load_addr, 80);
447         CHECK_OFFSET(tsc_offset, 88);
448         CHECK_OFFSET(virtual_apic_page_addr, 96);
449         CHECK_OFFSET(apic_access_addr, 104);
450         CHECK_OFFSET(posted_intr_desc_addr, 112);
451         CHECK_OFFSET(ept_pointer, 120);
452         CHECK_OFFSET(eoi_exit_bitmap0, 128);
453         CHECK_OFFSET(eoi_exit_bitmap1, 136);
454         CHECK_OFFSET(eoi_exit_bitmap2, 144);
455         CHECK_OFFSET(eoi_exit_bitmap3, 152);
456         CHECK_OFFSET(xss_exit_bitmap, 160);
457         CHECK_OFFSET(guest_physical_address, 168);
458         CHECK_OFFSET(vmcs_link_pointer, 176);
459         CHECK_OFFSET(guest_ia32_debugctl, 184);
460         CHECK_OFFSET(guest_ia32_pat, 192);
461         CHECK_OFFSET(guest_ia32_efer, 200);
462         CHECK_OFFSET(guest_ia32_perf_global_ctrl, 208);
463         CHECK_OFFSET(guest_pdptr0, 216);
464         CHECK_OFFSET(guest_pdptr1, 224);
465         CHECK_OFFSET(guest_pdptr2, 232);
466         CHECK_OFFSET(guest_pdptr3, 240);
467         CHECK_OFFSET(guest_bndcfgs, 248);
468         CHECK_OFFSET(host_ia32_pat, 256);
469         CHECK_OFFSET(host_ia32_efer, 264);
470         CHECK_OFFSET(host_ia32_perf_global_ctrl, 272);
471         CHECK_OFFSET(vmread_bitmap, 280);
472         CHECK_OFFSET(vmwrite_bitmap, 288);
473         CHECK_OFFSET(vm_function_control, 296);
474         CHECK_OFFSET(eptp_list_address, 304);
475         CHECK_OFFSET(pml_address, 312);
476         CHECK_OFFSET(cr0_guest_host_mask, 344);
477         CHECK_OFFSET(cr4_guest_host_mask, 352);
478         CHECK_OFFSET(cr0_read_shadow, 360);
479         CHECK_OFFSET(cr4_read_shadow, 368);
480         CHECK_OFFSET(cr3_target_value0, 376);
481         CHECK_OFFSET(cr3_target_value1, 384);
482         CHECK_OFFSET(cr3_target_value2, 392);
483         CHECK_OFFSET(cr3_target_value3, 400);
484         CHECK_OFFSET(exit_qualification, 408);
485         CHECK_OFFSET(guest_linear_address, 416);
486         CHECK_OFFSET(guest_cr0, 424);
487         CHECK_OFFSET(guest_cr3, 432);
488         CHECK_OFFSET(guest_cr4, 440);
489         CHECK_OFFSET(guest_es_base, 448);
490         CHECK_OFFSET(guest_cs_base, 456);
491         CHECK_OFFSET(guest_ss_base, 464);
492         CHECK_OFFSET(guest_ds_base, 472);
493         CHECK_OFFSET(guest_fs_base, 480);
494         CHECK_OFFSET(guest_gs_base, 488);
495         CHECK_OFFSET(guest_ldtr_base, 496);
496         CHECK_OFFSET(guest_tr_base, 504);
497         CHECK_OFFSET(guest_gdtr_base, 512);
498         CHECK_OFFSET(guest_idtr_base, 520);
499         CHECK_OFFSET(guest_dr7, 528);
500         CHECK_OFFSET(guest_rsp, 536);
501         CHECK_OFFSET(guest_rip, 544);
502         CHECK_OFFSET(guest_rflags, 552);
503         CHECK_OFFSET(guest_pending_dbg_exceptions, 560);
504         CHECK_OFFSET(guest_sysenter_esp, 568);
505         CHECK_OFFSET(guest_sysenter_eip, 576);
506         CHECK_OFFSET(host_cr0, 584);
507         CHECK_OFFSET(host_cr3, 592);
508         CHECK_OFFSET(host_cr4, 600);
509         CHECK_OFFSET(host_fs_base, 608);
510         CHECK_OFFSET(host_gs_base, 616);
511         CHECK_OFFSET(host_tr_base, 624);
512         CHECK_OFFSET(host_gdtr_base, 632);
513         CHECK_OFFSET(host_idtr_base, 640);
514         CHECK_OFFSET(host_ia32_sysenter_esp, 648);
515         CHECK_OFFSET(host_ia32_sysenter_eip, 656);
516         CHECK_OFFSET(host_rsp, 664);
517         CHECK_OFFSET(host_rip, 672);
518         CHECK_OFFSET(pin_based_vm_exec_control, 744);
519         CHECK_OFFSET(cpu_based_vm_exec_control, 748);
520         CHECK_OFFSET(exception_bitmap, 752);
521         CHECK_OFFSET(page_fault_error_code_mask, 756);
522         CHECK_OFFSET(page_fault_error_code_match, 760);
523         CHECK_OFFSET(cr3_target_count, 764);
524         CHECK_OFFSET(vm_exit_controls, 768);
525         CHECK_OFFSET(vm_exit_msr_store_count, 772);
526         CHECK_OFFSET(vm_exit_msr_load_count, 776);
527         CHECK_OFFSET(vm_entry_controls, 780);
528         CHECK_OFFSET(vm_entry_msr_load_count, 784);
529         CHECK_OFFSET(vm_entry_intr_info_field, 788);
530         CHECK_OFFSET(vm_entry_exception_error_code, 792);
531         CHECK_OFFSET(vm_entry_instruction_len, 796);
532         CHECK_OFFSET(tpr_threshold, 800);
533         CHECK_OFFSET(secondary_vm_exec_control, 804);
534         CHECK_OFFSET(vm_instruction_error, 808);
535         CHECK_OFFSET(vm_exit_reason, 812);
536         CHECK_OFFSET(vm_exit_intr_info, 816);
537         CHECK_OFFSET(vm_exit_intr_error_code, 820);
538         CHECK_OFFSET(idt_vectoring_info_field, 824);
539         CHECK_OFFSET(idt_vectoring_error_code, 828);
540         CHECK_OFFSET(vm_exit_instruction_len, 832);
541         CHECK_OFFSET(vmx_instruction_info, 836);
542         CHECK_OFFSET(guest_es_limit, 840);
543         CHECK_OFFSET(guest_cs_limit, 844);
544         CHECK_OFFSET(guest_ss_limit, 848);
545         CHECK_OFFSET(guest_ds_limit, 852);
546         CHECK_OFFSET(guest_fs_limit, 856);
547         CHECK_OFFSET(guest_gs_limit, 860);
548         CHECK_OFFSET(guest_ldtr_limit, 864);
549         CHECK_OFFSET(guest_tr_limit, 868);
550         CHECK_OFFSET(guest_gdtr_limit, 872);
551         CHECK_OFFSET(guest_idtr_limit, 876);
552         CHECK_OFFSET(guest_es_ar_bytes, 880);
553         CHECK_OFFSET(guest_cs_ar_bytes, 884);
554         CHECK_OFFSET(guest_ss_ar_bytes, 888);
555         CHECK_OFFSET(guest_ds_ar_bytes, 892);
556         CHECK_OFFSET(guest_fs_ar_bytes, 896);
557         CHECK_OFFSET(guest_gs_ar_bytes, 900);
558         CHECK_OFFSET(guest_ldtr_ar_bytes, 904);
559         CHECK_OFFSET(guest_tr_ar_bytes, 908);
560         CHECK_OFFSET(guest_interruptibility_info, 912);
561         CHECK_OFFSET(guest_activity_state, 916);
562         CHECK_OFFSET(guest_sysenter_cs, 920);
563         CHECK_OFFSET(host_ia32_sysenter_cs, 924);
564         CHECK_OFFSET(vmx_preemption_timer_value, 928);
565         CHECK_OFFSET(virtual_processor_id, 960);
566         CHECK_OFFSET(posted_intr_nv, 962);
567         CHECK_OFFSET(guest_es_selector, 964);
568         CHECK_OFFSET(guest_cs_selector, 966);
569         CHECK_OFFSET(guest_ss_selector, 968);
570         CHECK_OFFSET(guest_ds_selector, 970);
571         CHECK_OFFSET(guest_fs_selector, 972);
572         CHECK_OFFSET(guest_gs_selector, 974);
573         CHECK_OFFSET(guest_ldtr_selector, 976);
574         CHECK_OFFSET(guest_tr_selector, 978);
575         CHECK_OFFSET(guest_intr_status, 980);
576         CHECK_OFFSET(host_es_selector, 982);
577         CHECK_OFFSET(host_cs_selector, 984);
578         CHECK_OFFSET(host_ss_selector, 986);
579         CHECK_OFFSET(host_ds_selector, 988);
580         CHECK_OFFSET(host_fs_selector, 990);
581         CHECK_OFFSET(host_gs_selector, 992);
582         CHECK_OFFSET(host_tr_selector, 994);
583         CHECK_OFFSET(guest_pml_index, 996);
584 }
585
586 /*
587  * VMCS12_REVISION is an arbitrary id that should be changed if the content or
588  * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
589  * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
590  *
591  * IMPORTANT: Changing this value will break save/restore compatibility with
592  * older kvm releases.
593  */
594 #define VMCS12_REVISION 0x11e57ed0
595
596 /*
597  * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
598  * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
599  * current implementation, 4K are reserved to avoid future complications.
600  */
601 #define VMCS12_SIZE 0x1000
602
603 /*
604  * VMCS12_MAX_FIELD_INDEX is the highest index value used in any
605  * supported VMCS12 field encoding.
606  */
607 #define VMCS12_MAX_FIELD_INDEX 0x17
608
609 struct nested_vmx_msrs {
610         /*
611          * We only store the "true" versions of the VMX capability MSRs. We
612          * generate the "non-true" versions by setting the must-be-1 bits
613          * according to the SDM.
614          */
615         u32 procbased_ctls_low;
616         u32 procbased_ctls_high;
617         u32 secondary_ctls_low;
618         u32 secondary_ctls_high;
619         u32 pinbased_ctls_low;
620         u32 pinbased_ctls_high;
621         u32 exit_ctls_low;
622         u32 exit_ctls_high;
623         u32 entry_ctls_low;
624         u32 entry_ctls_high;
625         u32 misc_low;
626         u32 misc_high;
627         u32 ept_caps;
628         u32 vpid_caps;
629         u64 basic;
630         u64 cr0_fixed0;
631         u64 cr0_fixed1;
632         u64 cr4_fixed0;
633         u64 cr4_fixed1;
634         u64 vmcs_enum;
635         u64 vmfunc_controls;
636 };
637
638 /*
639  * The nested_vmx structure is part of vcpu_vmx, and holds information we need
640  * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
641  */
642 struct nested_vmx {
643         /* Has the level1 guest done vmxon? */
644         bool vmxon;
645         gpa_t vmxon_ptr;
646         bool pml_full;
647
648         /* The guest-physical address of the current VMCS L1 keeps for L2 */
649         gpa_t current_vmptr;
650         /*
651          * Cache of the guest's VMCS, existing outside of guest memory.
652          * Loaded from guest memory during VMPTRLD. Flushed to guest
653          * memory during VMCLEAR and VMPTRLD.
654          */
655         struct vmcs12 *cached_vmcs12;
656         /*
657          * Cache of the guest's shadow VMCS, existing outside of guest
658          * memory. Loaded from guest memory during VM entry. Flushed
659          * to guest memory during VM exit.
660          */
661         struct vmcs12 *cached_shadow_vmcs12;
662         /*
663          * Indicates if the shadow vmcs must be updated with the
664          * data hold by vmcs12
665          */
666         bool sync_shadow_vmcs;
667         bool dirty_vmcs12;
668
669         bool change_vmcs01_virtual_apic_mode;
670
671         /* L2 must run next, and mustn't decide to exit to L1. */
672         bool nested_run_pending;
673
674         struct loaded_vmcs vmcs02;
675
676         /*
677          * Guest pages referred to in the vmcs02 with host-physical
678          * pointers, so we must keep them pinned while L2 runs.
679          */
680         struct page *apic_access_page;
681         struct page *virtual_apic_page;
682         struct page *pi_desc_page;
683         struct pi_desc *pi_desc;
684         bool pi_pending;
685         u16 posted_intr_nv;
686
687         struct hrtimer preemption_timer;
688         bool preemption_timer_expired;
689
690         /* to migrate it to L2 if VM_ENTRY_LOAD_DEBUG_CONTROLS is off */
691         u64 vmcs01_debugctl;
692
693         u16 vpid02;
694         u16 last_vpid;
695
696         struct nested_vmx_msrs msrs;
697
698         /* SMM related state */
699         struct {
700                 /* in VMX operation on SMM entry? */
701                 bool vmxon;
702                 /* in guest mode on SMM entry? */
703                 bool guest_mode;
704         } smm;
705 };
706
707 #define POSTED_INTR_ON  0
708 #define POSTED_INTR_SN  1
709
710 /* Posted-Interrupt Descriptor */
711 struct pi_desc {
712         u32 pir[8];     /* Posted interrupt requested */
713         union {
714                 struct {
715                                 /* bit 256 - Outstanding Notification */
716                         u16     on      : 1,
717                                 /* bit 257 - Suppress Notification */
718                                 sn      : 1,
719                                 /* bit 271:258 - Reserved */
720                                 rsvd_1  : 14;
721                                 /* bit 279:272 - Notification Vector */
722                         u8      nv;
723                                 /* bit 287:280 - Reserved */
724                         u8      rsvd_2;
725                                 /* bit 319:288 - Notification Destination */
726                         u32     ndst;
727                 };
728                 u64 control;
729         };
730         u32 rsvd[6];
731 } __aligned(64);
732
733 static bool pi_test_and_set_on(struct pi_desc *pi_desc)
734 {
735         return test_and_set_bit(POSTED_INTR_ON,
736                         (unsigned long *)&pi_desc->control);
737 }
738
739 static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
740 {
741         return test_and_clear_bit(POSTED_INTR_ON,
742                         (unsigned long *)&pi_desc->control);
743 }
744
745 static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
746 {
747         return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
748 }
749
750 static inline void pi_clear_sn(struct pi_desc *pi_desc)
751 {
752         return clear_bit(POSTED_INTR_SN,
753                         (unsigned long *)&pi_desc->control);
754 }
755
756 static inline void pi_set_sn(struct pi_desc *pi_desc)
757 {
758         return set_bit(POSTED_INTR_SN,
759                         (unsigned long *)&pi_desc->control);
760 }
761
762 static inline void pi_clear_on(struct pi_desc *pi_desc)
763 {
764         clear_bit(POSTED_INTR_ON,
765                   (unsigned long *)&pi_desc->control);
766 }
767
768 static inline int pi_test_on(struct pi_desc *pi_desc)
769 {
770         return test_bit(POSTED_INTR_ON,
771                         (unsigned long *)&pi_desc->control);
772 }
773
774 static inline int pi_test_sn(struct pi_desc *pi_desc)
775 {
776         return test_bit(POSTED_INTR_SN,
777                         (unsigned long *)&pi_desc->control);
778 }
779
780 struct vcpu_vmx {
781         struct kvm_vcpu       vcpu;
782         unsigned long         host_rsp;
783         u8                    fail;
784         u8                    msr_bitmap_mode;
785         u32                   exit_intr_info;
786         u32                   idt_vectoring_info;
787         ulong                 rflags;
788         struct shared_msr_entry *guest_msrs;
789         int                   nmsrs;
790         int                   save_nmsrs;
791         unsigned long         host_idt_base;
792 #ifdef CONFIG_X86_64
793         u64                   msr_host_kernel_gs_base;
794         u64                   msr_guest_kernel_gs_base;
795 #endif
796
797         u64                   arch_capabilities;
798         u64                   spec_ctrl;
799
800         u32 vm_entry_controls_shadow;
801         u32 vm_exit_controls_shadow;
802         u32 secondary_exec_control;
803
804         /*
805          * loaded_vmcs points to the VMCS currently used in this vcpu. For a
806          * non-nested (L1) guest, it always points to vmcs01. For a nested
807          * guest (L2), it points to a different VMCS.
808          */
809         struct loaded_vmcs    vmcs01;
810         struct loaded_vmcs   *loaded_vmcs;
811         bool                  __launched; /* temporary, used in vmx_vcpu_run */
812         struct msr_autoload {
813                 unsigned nr;
814                 struct vmx_msr_entry guest[NR_AUTOLOAD_MSRS];
815                 struct vmx_msr_entry host[NR_AUTOLOAD_MSRS];
816         } msr_autoload;
817         struct {
818                 int           loaded;
819                 u16           fs_sel, gs_sel, ldt_sel;
820 #ifdef CONFIG_X86_64
821                 u16           ds_sel, es_sel;
822 #endif
823                 int           gs_ldt_reload_needed;
824                 int           fs_reload_needed;
825         } host_state;
826         struct {
827                 int vm86_active;
828                 ulong save_rflags;
829                 struct kvm_segment segs[8];
830         } rmode;
831         struct {
832                 u32 bitmask; /* 4 bits per segment (1 bit per field) */
833                 struct kvm_save_segment {
834                         u16 selector;
835                         unsigned long base;
836                         u32 limit;
837                         u32 ar;
838                 } seg[8];
839         } segment_cache;
840         int vpid;
841         bool emulation_required;
842
843         u32 exit_reason;
844
845         /* Posted interrupt descriptor */
846         struct pi_desc pi_desc;
847
848         /* Support for a guest hypervisor (nested VMX) */
849         struct nested_vmx nested;
850
851         /* Dynamic PLE window. */
852         int ple_window;
853         bool ple_window_dirty;
854
855         /* Support for PML */
856 #define PML_ENTITY_NUM          512
857         struct page *pml_pg;
858
859         /* apic deadline value in host tsc */
860         u64 hv_deadline_tsc;
861
862         u64 current_tsc_ratio;
863
864         u32 host_pkru;
865
866         unsigned long host_debugctlmsr;
867
868         /*
869          * Only bits masked by msr_ia32_feature_control_valid_bits can be set in
870          * msr_ia32_feature_control. FEATURE_CONTROL_LOCKED is always included
871          * in msr_ia32_feature_control_valid_bits.
872          */
873         u64 msr_ia32_feature_control;
874         u64 msr_ia32_feature_control_valid_bits;
875         u64 ept_pointer;
876 };
877
878 enum segment_cache_field {
879         SEG_FIELD_SEL = 0,
880         SEG_FIELD_BASE = 1,
881         SEG_FIELD_LIMIT = 2,
882         SEG_FIELD_AR = 3,
883
884         SEG_FIELD_NR = 4
885 };
886
887 static inline struct kvm_vmx *to_kvm_vmx(struct kvm *kvm)
888 {
889         return container_of(kvm, struct kvm_vmx, kvm);
890 }
891
892 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
893 {
894         return container_of(vcpu, struct vcpu_vmx, vcpu);
895 }
896
897 static struct pi_desc *vcpu_to_pi_desc(struct kvm_vcpu *vcpu)
898 {
899         return &(to_vmx(vcpu)->pi_desc);
900 }
901
902 #define ROL16(val, n) ((u16)(((u16)(val) << (n)) | ((u16)(val) >> (16 - (n)))))
903 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
904 #define FIELD(number, name)     [ROL16(number, 6)] = VMCS12_OFFSET(name)
905 #define FIELD64(number, name)                                           \
906         FIELD(number, name),                                            \
907         [ROL16(number##_HIGH, 6)] = VMCS12_OFFSET(name) + sizeof(u32)
908
909
910 static u16 shadow_read_only_fields[] = {
911 #define SHADOW_FIELD_RO(x) x,
912 #include "vmx_shadow_fields.h"
913 };
914 static int max_shadow_read_only_fields =
915         ARRAY_SIZE(shadow_read_only_fields);
916
917 static u16 shadow_read_write_fields[] = {
918 #define SHADOW_FIELD_RW(x) x,
919 #include "vmx_shadow_fields.h"
920 };
921 static int max_shadow_read_write_fields =
922         ARRAY_SIZE(shadow_read_write_fields);
923
924 static const unsigned short vmcs_field_to_offset_table[] = {
925         FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
926         FIELD(POSTED_INTR_NV, posted_intr_nv),
927         FIELD(GUEST_ES_SELECTOR, guest_es_selector),
928         FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
929         FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
930         FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
931         FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
932         FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
933         FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
934         FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
935         FIELD(GUEST_INTR_STATUS, guest_intr_status),
936         FIELD(GUEST_PML_INDEX, guest_pml_index),
937         FIELD(HOST_ES_SELECTOR, host_es_selector),
938         FIELD(HOST_CS_SELECTOR, host_cs_selector),
939         FIELD(HOST_SS_SELECTOR, host_ss_selector),
940         FIELD(HOST_DS_SELECTOR, host_ds_selector),
941         FIELD(HOST_FS_SELECTOR, host_fs_selector),
942         FIELD(HOST_GS_SELECTOR, host_gs_selector),
943         FIELD(HOST_TR_SELECTOR, host_tr_selector),
944         FIELD64(IO_BITMAP_A, io_bitmap_a),
945         FIELD64(IO_BITMAP_B, io_bitmap_b),
946         FIELD64(MSR_BITMAP, msr_bitmap),
947         FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
948         FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
949         FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
950         FIELD64(PML_ADDRESS, pml_address),
951         FIELD64(TSC_OFFSET, tsc_offset),
952         FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
953         FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
954         FIELD64(POSTED_INTR_DESC_ADDR, posted_intr_desc_addr),
955         FIELD64(VM_FUNCTION_CONTROL, vm_function_control),
956         FIELD64(EPT_POINTER, ept_pointer),
957         FIELD64(EOI_EXIT_BITMAP0, eoi_exit_bitmap0),
958         FIELD64(EOI_EXIT_BITMAP1, eoi_exit_bitmap1),
959         FIELD64(EOI_EXIT_BITMAP2, eoi_exit_bitmap2),
960         FIELD64(EOI_EXIT_BITMAP3, eoi_exit_bitmap3),
961         FIELD64(EPTP_LIST_ADDRESS, eptp_list_address),
962         FIELD64(VMREAD_BITMAP, vmread_bitmap),
963         FIELD64(VMWRITE_BITMAP, vmwrite_bitmap),
964         FIELD64(XSS_EXIT_BITMAP, xss_exit_bitmap),
965         FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
966         FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
967         FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
968         FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
969         FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
970         FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
971         FIELD64(GUEST_PDPTR0, guest_pdptr0),
972         FIELD64(GUEST_PDPTR1, guest_pdptr1),
973         FIELD64(GUEST_PDPTR2, guest_pdptr2),
974         FIELD64(GUEST_PDPTR3, guest_pdptr3),
975         FIELD64(GUEST_BNDCFGS, guest_bndcfgs),
976         FIELD64(HOST_IA32_PAT, host_ia32_pat),
977         FIELD64(HOST_IA32_EFER, host_ia32_efer),
978         FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
979         FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
980         FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
981         FIELD(EXCEPTION_BITMAP, exception_bitmap),
982         FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
983         FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
984         FIELD(CR3_TARGET_COUNT, cr3_target_count),
985         FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
986         FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
987         FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
988         FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
989         FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
990         FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
991         FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
992         FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
993         FIELD(TPR_THRESHOLD, tpr_threshold),
994         FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
995         FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
996         FIELD(VM_EXIT_REASON, vm_exit_reason),
997         FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
998         FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
999         FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
1000         FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
1001         FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
1002         FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
1003         FIELD(GUEST_ES_LIMIT, guest_es_limit),
1004         FIELD(GUEST_CS_LIMIT, guest_cs_limit),
1005         FIELD(GUEST_SS_LIMIT, guest_ss_limit),
1006         FIELD(GUEST_DS_LIMIT, guest_ds_limit),
1007         FIELD(GUEST_FS_LIMIT, guest_fs_limit),
1008         FIELD(GUEST_GS_LIMIT, guest_gs_limit),
1009         FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
1010         FIELD(GUEST_TR_LIMIT, guest_tr_limit),
1011         FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
1012         FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
1013         FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
1014         FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
1015         FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
1016         FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
1017         FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
1018         FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
1019         FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
1020         FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
1021         FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
1022         FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
1023         FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
1024         FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
1025         FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
1026         FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
1027         FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
1028         FIELD(CR0_READ_SHADOW, cr0_read_shadow),
1029         FIELD(CR4_READ_SHADOW, cr4_read_shadow),
1030         FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
1031         FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
1032         FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
1033         FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
1034         FIELD(EXIT_QUALIFICATION, exit_qualification),
1035         FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
1036         FIELD(GUEST_CR0, guest_cr0),
1037         FIELD(GUEST_CR3, guest_cr3),
1038         FIELD(GUEST_CR4, guest_cr4),
1039         FIELD(GUEST_ES_BASE, guest_es_base),
1040         FIELD(GUEST_CS_BASE, guest_cs_base),
1041         FIELD(GUEST_SS_BASE, guest_ss_base),
1042         FIELD(GUEST_DS_BASE, guest_ds_base),
1043         FIELD(GUEST_FS_BASE, guest_fs_base),
1044         FIELD(GUEST_GS_BASE, guest_gs_base),
1045         FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
1046         FIELD(GUEST_TR_BASE, guest_tr_base),
1047         FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
1048         FIELD(GUEST_IDTR_BASE, guest_idtr_base),
1049         FIELD(GUEST_DR7, guest_dr7),
1050         FIELD(GUEST_RSP, guest_rsp),
1051         FIELD(GUEST_RIP, guest_rip),
1052         FIELD(GUEST_RFLAGS, guest_rflags),
1053         FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
1054         FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
1055         FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
1056         FIELD(HOST_CR0, host_cr0),
1057         FIELD(HOST_CR3, host_cr3),
1058         FIELD(HOST_CR4, host_cr4),
1059         FIELD(HOST_FS_BASE, host_fs_base),
1060         FIELD(HOST_GS_BASE, host_gs_base),
1061         FIELD(HOST_TR_BASE, host_tr_base),
1062         FIELD(HOST_GDTR_BASE, host_gdtr_base),
1063         FIELD(HOST_IDTR_BASE, host_idtr_base),
1064         FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
1065         FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
1066         FIELD(HOST_RSP, host_rsp),
1067         FIELD(HOST_RIP, host_rip),
1068 };
1069
1070 static inline short vmcs_field_to_offset(unsigned long field)
1071 {
1072         const size_t size = ARRAY_SIZE(vmcs_field_to_offset_table);
1073         unsigned short offset;
1074         unsigned index;
1075
1076         if (field >> 15)
1077                 return -ENOENT;
1078
1079         index = ROL16(field, 6);
1080         if (index >= size)
1081                 return -ENOENT;
1082
1083         index = array_index_nospec(index, size);
1084         offset = vmcs_field_to_offset_table[index];
1085         if (offset == 0)
1086                 return -ENOENT;
1087         return offset;
1088 }
1089
1090 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
1091 {
1092         return to_vmx(vcpu)->nested.cached_vmcs12;
1093 }
1094
1095 static inline struct vmcs12 *get_shadow_vmcs12(struct kvm_vcpu *vcpu)
1096 {
1097         return to_vmx(vcpu)->nested.cached_shadow_vmcs12;
1098 }
1099
1100 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu);
1101 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
1102 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa);
1103 static bool vmx_xsaves_supported(void);
1104 static void vmx_set_segment(struct kvm_vcpu *vcpu,
1105                             struct kvm_segment *var, int seg);
1106 static void vmx_get_segment(struct kvm_vcpu *vcpu,
1107                             struct kvm_segment *var, int seg);
1108 static bool guest_state_valid(struct kvm_vcpu *vcpu);
1109 static u32 vmx_segment_access_rights(struct kvm_segment *var);
1110 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
1111 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu);
1112 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked);
1113 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
1114                                             u16 error_code);
1115 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu);
1116 static void __always_inline vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
1117                                                           u32 msr, int type);
1118
1119 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
1120 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
1121 /*
1122  * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
1123  * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
1124  */
1125 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
1126
1127 /*
1128  * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
1129  * can find which vCPU should be waken up.
1130  */
1131 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
1132 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
1133
1134 enum {
1135         VMX_VMREAD_BITMAP,
1136         VMX_VMWRITE_BITMAP,
1137         VMX_BITMAP_NR
1138 };
1139
1140 static unsigned long *vmx_bitmap[VMX_BITMAP_NR];
1141
1142 #define vmx_vmread_bitmap                    (vmx_bitmap[VMX_VMREAD_BITMAP])
1143 #define vmx_vmwrite_bitmap                   (vmx_bitmap[VMX_VMWRITE_BITMAP])
1144
1145 static bool cpu_has_load_ia32_efer;
1146 static bool cpu_has_load_perf_global_ctrl;
1147
1148 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
1149 static DEFINE_SPINLOCK(vmx_vpid_lock);
1150
1151 static struct vmcs_config {
1152         int size;
1153         int order;
1154         u32 basic_cap;
1155         u32 revision_id;
1156         u32 pin_based_exec_ctrl;
1157         u32 cpu_based_exec_ctrl;
1158         u32 cpu_based_2nd_exec_ctrl;
1159         u32 vmexit_ctrl;
1160         u32 vmentry_ctrl;
1161         struct nested_vmx_msrs nested;
1162 } vmcs_config;
1163
1164 static struct vmx_capability {
1165         u32 ept;
1166         u32 vpid;
1167 } vmx_capability;
1168
1169 #define VMX_SEGMENT_FIELD(seg)                                  \
1170         [VCPU_SREG_##seg] = {                                   \
1171                 .selector = GUEST_##seg##_SELECTOR,             \
1172                 .base = GUEST_##seg##_BASE,                     \
1173                 .limit = GUEST_##seg##_LIMIT,                   \
1174                 .ar_bytes = GUEST_##seg##_AR_BYTES,             \
1175         }
1176
1177 static const struct kvm_vmx_segment_field {
1178         unsigned selector;
1179         unsigned base;
1180         unsigned limit;
1181         unsigned ar_bytes;
1182 } kvm_vmx_segment_fields[] = {
1183         VMX_SEGMENT_FIELD(CS),
1184         VMX_SEGMENT_FIELD(DS),
1185         VMX_SEGMENT_FIELD(ES),
1186         VMX_SEGMENT_FIELD(FS),
1187         VMX_SEGMENT_FIELD(GS),
1188         VMX_SEGMENT_FIELD(SS),
1189         VMX_SEGMENT_FIELD(TR),
1190         VMX_SEGMENT_FIELD(LDTR),
1191 };
1192
1193 static u64 host_efer;
1194
1195 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
1196
1197 /*
1198  * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
1199  * away by decrementing the array size.
1200  */
1201 static const u32 vmx_msr_index[] = {
1202 #ifdef CONFIG_X86_64
1203         MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
1204 #endif
1205         MSR_EFER, MSR_TSC_AUX, MSR_STAR,
1206 };
1207
1208 DEFINE_STATIC_KEY_FALSE(enable_evmcs);
1209
1210 #define current_evmcs ((struct hv_enlightened_vmcs *)this_cpu_read(current_vmcs))
1211
1212 #define KVM_EVMCS_VERSION 1
1213
1214 #if IS_ENABLED(CONFIG_HYPERV)
1215 static bool __read_mostly enlightened_vmcs = true;
1216 module_param(enlightened_vmcs, bool, 0444);
1217
1218 static inline void evmcs_write64(unsigned long field, u64 value)
1219 {
1220         u16 clean_field;
1221         int offset = get_evmcs_offset(field, &clean_field);
1222
1223         if (offset < 0)
1224                 return;
1225
1226         *(u64 *)((char *)current_evmcs + offset) = value;
1227
1228         current_evmcs->hv_clean_fields &= ~clean_field;
1229 }
1230
1231 static inline void evmcs_write32(unsigned long field, u32 value)
1232 {
1233         u16 clean_field;
1234         int offset = get_evmcs_offset(field, &clean_field);
1235
1236         if (offset < 0)
1237                 return;
1238
1239         *(u32 *)((char *)current_evmcs + offset) = value;
1240         current_evmcs->hv_clean_fields &= ~clean_field;
1241 }
1242
1243 static inline void evmcs_write16(unsigned long field, u16 value)
1244 {
1245         u16 clean_field;
1246         int offset = get_evmcs_offset(field, &clean_field);
1247
1248         if (offset < 0)
1249                 return;
1250
1251         *(u16 *)((char *)current_evmcs + offset) = value;
1252         current_evmcs->hv_clean_fields &= ~clean_field;
1253 }
1254
1255 static inline u64 evmcs_read64(unsigned long field)
1256 {
1257         int offset = get_evmcs_offset(field, NULL);
1258
1259         if (offset < 0)
1260                 return 0;
1261
1262         return *(u64 *)((char *)current_evmcs + offset);
1263 }
1264
1265 static inline u32 evmcs_read32(unsigned long field)
1266 {
1267         int offset = get_evmcs_offset(field, NULL);
1268
1269         if (offset < 0)
1270                 return 0;
1271
1272         return *(u32 *)((char *)current_evmcs + offset);
1273 }
1274
1275 static inline u16 evmcs_read16(unsigned long field)
1276 {
1277         int offset = get_evmcs_offset(field, NULL);
1278
1279         if (offset < 0)
1280                 return 0;
1281
1282         return *(u16 *)((char *)current_evmcs + offset);
1283 }
1284
1285 static inline void evmcs_touch_msr_bitmap(void)
1286 {
1287         if (unlikely(!current_evmcs))
1288                 return;
1289
1290         if (current_evmcs->hv_enlightenments_control.msr_bitmap)
1291                 current_evmcs->hv_clean_fields &=
1292                         ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP;
1293 }
1294
1295 static void evmcs_load(u64 phys_addr)
1296 {
1297         struct hv_vp_assist_page *vp_ap =
1298                 hv_get_vp_assist_page(smp_processor_id());
1299
1300         vp_ap->current_nested_vmcs = phys_addr;
1301         vp_ap->enlighten_vmentry = 1;
1302 }
1303
1304 static void evmcs_sanitize_exec_ctrls(struct vmcs_config *vmcs_conf)
1305 {
1306         /*
1307          * Enlightened VMCSv1 doesn't support these:
1308          *
1309          *      POSTED_INTR_NV                  = 0x00000002,
1310          *      GUEST_INTR_STATUS               = 0x00000810,
1311          *      APIC_ACCESS_ADDR                = 0x00002014,
1312          *      POSTED_INTR_DESC_ADDR           = 0x00002016,
1313          *      EOI_EXIT_BITMAP0                = 0x0000201c,
1314          *      EOI_EXIT_BITMAP1                = 0x0000201e,
1315          *      EOI_EXIT_BITMAP2                = 0x00002020,
1316          *      EOI_EXIT_BITMAP3                = 0x00002022,
1317          */
1318         vmcs_conf->pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
1319         vmcs_conf->cpu_based_2nd_exec_ctrl &=
1320                 ~SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1321         vmcs_conf->cpu_based_2nd_exec_ctrl &=
1322                 ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1323         vmcs_conf->cpu_based_2nd_exec_ctrl &=
1324                 ~SECONDARY_EXEC_APIC_REGISTER_VIRT;
1325
1326         /*
1327          *      GUEST_PML_INDEX                 = 0x00000812,
1328          *      PML_ADDRESS                     = 0x0000200e,
1329          */
1330         vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_ENABLE_PML;
1331
1332         /*      VM_FUNCTION_CONTROL             = 0x00002018, */
1333         vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_ENABLE_VMFUNC;
1334
1335         /*
1336          *      EPTP_LIST_ADDRESS               = 0x00002024,
1337          *      VMREAD_BITMAP                   = 0x00002026,
1338          *      VMWRITE_BITMAP                  = 0x00002028,
1339          */
1340         vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_SHADOW_VMCS;
1341
1342         /*
1343          *      TSC_MULTIPLIER                  = 0x00002032,
1344          */
1345         vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_TSC_SCALING;
1346
1347         /*
1348          *      PLE_GAP                         = 0x00004020,
1349          *      PLE_WINDOW                      = 0x00004022,
1350          */
1351         vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1352
1353         /*
1354          *      VMX_PREEMPTION_TIMER_VALUE      = 0x0000482E,
1355          */
1356         vmcs_conf->pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
1357
1358         /*
1359          *      GUEST_IA32_PERF_GLOBAL_CTRL     = 0x00002808,
1360          *      HOST_IA32_PERF_GLOBAL_CTRL      = 0x00002c04,
1361          */
1362         vmcs_conf->vmexit_ctrl &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
1363         vmcs_conf->vmentry_ctrl &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
1364
1365         /*
1366          * Currently unsupported in KVM:
1367          *      GUEST_IA32_RTIT_CTL             = 0x00002814,
1368          */
1369 }
1370
1371 /* check_ept_pointer() should be under protection of ept_pointer_lock. */
1372 static void check_ept_pointer_match(struct kvm *kvm)
1373 {
1374         struct kvm_vcpu *vcpu;
1375         u64 tmp_eptp = INVALID_PAGE;
1376         int i;
1377
1378         kvm_for_each_vcpu(i, vcpu, kvm) {
1379                 if (!VALID_PAGE(tmp_eptp)) {
1380                         tmp_eptp = to_vmx(vcpu)->ept_pointer;
1381                 } else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
1382                         to_kvm_vmx(kvm)->ept_pointers_match
1383                                 = EPT_POINTERS_MISMATCH;
1384                         return;
1385                 }
1386         }
1387
1388         to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
1389 }
1390
1391 static int vmx_hv_remote_flush_tlb(struct kvm *kvm)
1392 {
1393         int ret;
1394
1395         spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
1396
1397         if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
1398                 check_ept_pointer_match(kvm);
1399
1400         if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
1401                 ret = -ENOTSUPP;
1402                 goto out;
1403         }
1404
1405         ret = hyperv_flush_guest_mapping(
1406                         to_vmx(kvm_get_vcpu(kvm, 0))->ept_pointer);
1407
1408 out:
1409         spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
1410         return ret;
1411 }
1412 #else /* !IS_ENABLED(CONFIG_HYPERV) */
1413 static inline void evmcs_write64(unsigned long field, u64 value) {}
1414 static inline void evmcs_write32(unsigned long field, u32 value) {}
1415 static inline void evmcs_write16(unsigned long field, u16 value) {}
1416 static inline u64 evmcs_read64(unsigned long field) { return 0; }
1417 static inline u32 evmcs_read32(unsigned long field) { return 0; }
1418 static inline u16 evmcs_read16(unsigned long field) { return 0; }
1419 static inline void evmcs_load(u64 phys_addr) {}
1420 static inline void evmcs_sanitize_exec_ctrls(struct vmcs_config *vmcs_conf) {}
1421 static inline void evmcs_touch_msr_bitmap(void) {}
1422 #endif /* IS_ENABLED(CONFIG_HYPERV) */
1423
1424 static inline bool is_exception_n(u32 intr_info, u8 vector)
1425 {
1426         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1427                              INTR_INFO_VALID_MASK)) ==
1428                 (INTR_TYPE_HARD_EXCEPTION | vector | INTR_INFO_VALID_MASK);
1429 }
1430
1431 static inline bool is_debug(u32 intr_info)
1432 {
1433         return is_exception_n(intr_info, DB_VECTOR);
1434 }
1435
1436 static inline bool is_breakpoint(u32 intr_info)
1437 {
1438         return is_exception_n(intr_info, BP_VECTOR);
1439 }
1440
1441 static inline bool is_page_fault(u32 intr_info)
1442 {
1443         return is_exception_n(intr_info, PF_VECTOR);
1444 }
1445
1446 static inline bool is_no_device(u32 intr_info)
1447 {
1448         return is_exception_n(intr_info, NM_VECTOR);
1449 }
1450
1451 static inline bool is_invalid_opcode(u32 intr_info)
1452 {
1453         return is_exception_n(intr_info, UD_VECTOR);
1454 }
1455
1456 static inline bool is_gp_fault(u32 intr_info)
1457 {
1458         return is_exception_n(intr_info, GP_VECTOR);
1459 }
1460
1461 static inline bool is_external_interrupt(u32 intr_info)
1462 {
1463         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1464                 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
1465 }
1466
1467 static inline bool is_machine_check(u32 intr_info)
1468 {
1469         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1470                              INTR_INFO_VALID_MASK)) ==
1471                 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
1472 }
1473
1474 /* Undocumented: icebp/int1 */
1475 static inline bool is_icebp(u32 intr_info)
1476 {
1477         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1478                 == (INTR_TYPE_PRIV_SW_EXCEPTION | INTR_INFO_VALID_MASK);
1479 }
1480
1481 static inline bool cpu_has_vmx_msr_bitmap(void)
1482 {
1483         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
1484 }
1485
1486 static inline bool cpu_has_vmx_tpr_shadow(void)
1487 {
1488         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
1489 }
1490
1491 static inline bool cpu_need_tpr_shadow(struct kvm_vcpu *vcpu)
1492 {
1493         return cpu_has_vmx_tpr_shadow() && lapic_in_kernel(vcpu);
1494 }
1495
1496 static inline bool cpu_has_secondary_exec_ctrls(void)
1497 {
1498         return vmcs_config.cpu_based_exec_ctrl &
1499                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1500 }
1501
1502 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
1503 {
1504         return vmcs_config.cpu_based_2nd_exec_ctrl &
1505                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1506 }
1507
1508 static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
1509 {
1510         return vmcs_config.cpu_based_2nd_exec_ctrl &
1511                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
1512 }
1513
1514 static inline bool cpu_has_vmx_apic_register_virt(void)
1515 {
1516         return vmcs_config.cpu_based_2nd_exec_ctrl &
1517                 SECONDARY_EXEC_APIC_REGISTER_VIRT;
1518 }
1519
1520 static inline bool cpu_has_vmx_virtual_intr_delivery(void)
1521 {
1522         return vmcs_config.cpu_based_2nd_exec_ctrl &
1523                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1524 }
1525
1526 /*
1527  * Comment's format: document - errata name - stepping - processor name.
1528  * Refer from
1529  * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
1530  */
1531 static u32 vmx_preemption_cpu_tfms[] = {
1532 /* 323344.pdf - BA86   - D0 - Xeon 7500 Series */
1533 0x000206E6,
1534 /* 323056.pdf - AAX65  - C2 - Xeon L3406 */
1535 /* 322814.pdf - AAT59  - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
1536 /* 322911.pdf - AAU65  - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
1537 0x00020652,
1538 /* 322911.pdf - AAU65  - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
1539 0x00020655,
1540 /* 322373.pdf - AAO95  - B1 - Xeon 3400 Series */
1541 /* 322166.pdf - AAN92  - B1 - i7-800 and i5-700 Desktop */
1542 /*
1543  * 320767.pdf - AAP86  - B1 -
1544  * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
1545  */
1546 0x000106E5,
1547 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
1548 0x000106A0,
1549 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
1550 0x000106A1,
1551 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
1552 0x000106A4,
1553  /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
1554  /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
1555  /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
1556 0x000106A5,
1557 };
1558
1559 static inline bool cpu_has_broken_vmx_preemption_timer(void)
1560 {
1561         u32 eax = cpuid_eax(0x00000001), i;
1562
1563         /* Clear the reserved bits */
1564         eax &= ~(0x3U << 14 | 0xfU << 28);
1565         for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
1566                 if (eax == vmx_preemption_cpu_tfms[i])
1567                         return true;
1568
1569         return false;
1570 }
1571
1572 static inline bool cpu_has_vmx_preemption_timer(void)
1573 {
1574         return vmcs_config.pin_based_exec_ctrl &
1575                 PIN_BASED_VMX_PREEMPTION_TIMER;
1576 }
1577
1578 static inline bool cpu_has_vmx_posted_intr(void)
1579 {
1580         return IS_ENABLED(CONFIG_X86_LOCAL_APIC) &&
1581                 vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
1582 }
1583
1584 static inline bool cpu_has_vmx_apicv(void)
1585 {
1586         return cpu_has_vmx_apic_register_virt() &&
1587                 cpu_has_vmx_virtual_intr_delivery() &&
1588                 cpu_has_vmx_posted_intr();
1589 }
1590
1591 static inline bool cpu_has_vmx_flexpriority(void)
1592 {
1593         return cpu_has_vmx_tpr_shadow() &&
1594                 cpu_has_vmx_virtualize_apic_accesses();
1595 }
1596
1597 static inline bool cpu_has_vmx_ept_execute_only(void)
1598 {
1599         return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
1600 }
1601
1602 static inline bool cpu_has_vmx_ept_2m_page(void)
1603 {
1604         return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
1605 }
1606
1607 static inline bool cpu_has_vmx_ept_1g_page(void)
1608 {
1609         return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
1610 }
1611
1612 static inline bool cpu_has_vmx_ept_4levels(void)
1613 {
1614         return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
1615 }
1616
1617 static inline bool cpu_has_vmx_ept_mt_wb(void)
1618 {
1619         return vmx_capability.ept & VMX_EPTP_WB_BIT;
1620 }
1621
1622 static inline bool cpu_has_vmx_ept_5levels(void)
1623 {
1624         return vmx_capability.ept & VMX_EPT_PAGE_WALK_5_BIT;
1625 }
1626
1627 static inline bool cpu_has_vmx_ept_ad_bits(void)
1628 {
1629         return vmx_capability.ept & VMX_EPT_AD_BIT;
1630 }
1631
1632 static inline bool cpu_has_vmx_invept_context(void)
1633 {
1634         return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
1635 }
1636
1637 static inline bool cpu_has_vmx_invept_global(void)
1638 {
1639         return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
1640 }
1641
1642 static inline bool cpu_has_vmx_invvpid_individual_addr(void)
1643 {
1644         return vmx_capability.vpid & VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT;
1645 }
1646
1647 static inline bool cpu_has_vmx_invvpid_single(void)
1648 {
1649         return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
1650 }
1651
1652 static inline bool cpu_has_vmx_invvpid_global(void)
1653 {
1654         return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
1655 }
1656
1657 static inline bool cpu_has_vmx_invvpid(void)
1658 {
1659         return vmx_capability.vpid & VMX_VPID_INVVPID_BIT;
1660 }
1661
1662 static inline bool cpu_has_vmx_ept(void)
1663 {
1664         return vmcs_config.cpu_based_2nd_exec_ctrl &
1665                 SECONDARY_EXEC_ENABLE_EPT;
1666 }
1667
1668 static inline bool cpu_has_vmx_unrestricted_guest(void)
1669 {
1670         return vmcs_config.cpu_based_2nd_exec_ctrl &
1671                 SECONDARY_EXEC_UNRESTRICTED_GUEST;
1672 }
1673
1674 static inline bool cpu_has_vmx_ple(void)
1675 {
1676         return vmcs_config.cpu_based_2nd_exec_ctrl &
1677                 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1678 }
1679
1680 static inline bool cpu_has_vmx_basic_inout(void)
1681 {
1682         return  (((u64)vmcs_config.basic_cap << 32) & VMX_BASIC_INOUT);
1683 }
1684
1685 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
1686 {
1687         return flexpriority_enabled && lapic_in_kernel(vcpu);
1688 }
1689
1690 static inline bool cpu_has_vmx_vpid(void)
1691 {
1692         return vmcs_config.cpu_based_2nd_exec_ctrl &
1693                 SECONDARY_EXEC_ENABLE_VPID;
1694 }
1695
1696 static inline bool cpu_has_vmx_rdtscp(void)
1697 {
1698         return vmcs_config.cpu_based_2nd_exec_ctrl &
1699                 SECONDARY_EXEC_RDTSCP;
1700 }
1701
1702 static inline bool cpu_has_vmx_invpcid(void)
1703 {
1704         return vmcs_config.cpu_based_2nd_exec_ctrl &
1705                 SECONDARY_EXEC_ENABLE_INVPCID;
1706 }
1707
1708 static inline bool cpu_has_virtual_nmis(void)
1709 {
1710         return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1711 }
1712
1713 static inline bool cpu_has_vmx_wbinvd_exit(void)
1714 {
1715         return vmcs_config.cpu_based_2nd_exec_ctrl &
1716                 SECONDARY_EXEC_WBINVD_EXITING;
1717 }
1718
1719 static inline bool cpu_has_vmx_shadow_vmcs(void)
1720 {
1721         u64 vmx_msr;
1722         rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1723         /* check if the cpu supports writing r/o exit information fields */
1724         if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1725                 return false;
1726
1727         return vmcs_config.cpu_based_2nd_exec_ctrl &
1728                 SECONDARY_EXEC_SHADOW_VMCS;
1729 }
1730
1731 static inline bool cpu_has_vmx_pml(void)
1732 {
1733         return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_PML;
1734 }
1735
1736 static inline bool cpu_has_vmx_tsc_scaling(void)
1737 {
1738         return vmcs_config.cpu_based_2nd_exec_ctrl &
1739                 SECONDARY_EXEC_TSC_SCALING;
1740 }
1741
1742 static inline bool cpu_has_vmx_vmfunc(void)
1743 {
1744         return vmcs_config.cpu_based_2nd_exec_ctrl &
1745                 SECONDARY_EXEC_ENABLE_VMFUNC;
1746 }
1747
1748 static bool vmx_umip_emulated(void)
1749 {
1750         return vmcs_config.cpu_based_2nd_exec_ctrl &
1751                 SECONDARY_EXEC_DESC;
1752 }
1753
1754 static inline bool report_flexpriority(void)
1755 {
1756         return flexpriority_enabled;
1757 }
1758
1759 static inline unsigned nested_cpu_vmx_misc_cr3_count(struct kvm_vcpu *vcpu)
1760 {
1761         return vmx_misc_cr3_count(to_vmx(vcpu)->nested.msrs.misc_low);
1762 }
1763
1764 /*
1765  * Do the virtual VMX capability MSRs specify that L1 can use VMWRITE
1766  * to modify any valid field of the VMCS, or are the VM-exit
1767  * information fields read-only?
1768  */
1769 static inline bool nested_cpu_has_vmwrite_any_field(struct kvm_vcpu *vcpu)
1770 {
1771         return to_vmx(vcpu)->nested.msrs.misc_low &
1772                 MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS;
1773 }
1774
1775 static inline bool nested_cpu_has_zero_length_injection(struct kvm_vcpu *vcpu)
1776 {
1777         return to_vmx(vcpu)->nested.msrs.misc_low & VMX_MISC_ZERO_LEN_INS;
1778 }
1779
1780 static inline bool nested_cpu_supports_monitor_trap_flag(struct kvm_vcpu *vcpu)
1781 {
1782         return to_vmx(vcpu)->nested.msrs.procbased_ctls_high &
1783                         CPU_BASED_MONITOR_TRAP_FLAG;
1784 }
1785
1786 static inline bool nested_cpu_has_vmx_shadow_vmcs(struct kvm_vcpu *vcpu)
1787 {
1788         return to_vmx(vcpu)->nested.msrs.secondary_ctls_high &
1789                 SECONDARY_EXEC_SHADOW_VMCS;
1790 }
1791
1792 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
1793 {
1794         return vmcs12->cpu_based_vm_exec_control & bit;
1795 }
1796
1797 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
1798 {
1799         return (vmcs12->cpu_based_vm_exec_control &
1800                         CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
1801                 (vmcs12->secondary_vm_exec_control & bit);
1802 }
1803
1804 static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
1805 {
1806         return vmcs12->pin_based_vm_exec_control &
1807                 PIN_BASED_VMX_PREEMPTION_TIMER;
1808 }
1809
1810 static inline bool nested_cpu_has_nmi_exiting(struct vmcs12 *vmcs12)
1811 {
1812         return vmcs12->pin_based_vm_exec_control & PIN_BASED_NMI_EXITING;
1813 }
1814
1815 static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12)
1816 {
1817         return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
1818 }
1819
1820 static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
1821 {
1822         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
1823 }
1824
1825 static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
1826 {
1827         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
1828 }
1829
1830 static inline bool nested_cpu_has_pml(struct vmcs12 *vmcs12)
1831 {
1832         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML);
1833 }
1834
1835 static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
1836 {
1837         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
1838 }
1839
1840 static inline bool nested_cpu_has_vpid(struct vmcs12 *vmcs12)
1841 {
1842         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VPID);
1843 }
1844
1845 static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
1846 {
1847         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
1848 }
1849
1850 static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
1851 {
1852         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
1853 }
1854
1855 static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
1856 {
1857         return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
1858 }
1859
1860 static inline bool nested_cpu_has_vmfunc(struct vmcs12 *vmcs12)
1861 {
1862         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VMFUNC);
1863 }
1864
1865 static inline bool nested_cpu_has_eptp_switching(struct vmcs12 *vmcs12)
1866 {
1867         return nested_cpu_has_vmfunc(vmcs12) &&
1868                 (vmcs12->vm_function_control &
1869                  VMX_VMFUNC_EPTP_SWITCHING);
1870 }
1871
1872 static inline bool nested_cpu_has_shadow_vmcs(struct vmcs12 *vmcs12)
1873 {
1874         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_SHADOW_VMCS);
1875 }
1876
1877 static inline bool is_nmi(u32 intr_info)
1878 {
1879         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1880                 == (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK);
1881 }
1882
1883 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
1884                               u32 exit_intr_info,
1885                               unsigned long exit_qualification);
1886 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
1887                         struct vmcs12 *vmcs12,
1888                         u32 reason, unsigned long qualification);
1889
1890 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
1891 {
1892         int i;
1893
1894         for (i = 0; i < vmx->nmsrs; ++i)
1895                 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
1896                         return i;
1897         return -1;
1898 }
1899
1900 static inline void __invvpid(int ext, u16 vpid, gva_t gva)
1901 {
1902     struct {
1903         u64 vpid : 16;
1904         u64 rsvd : 48;
1905         u64 gva;
1906     } operand = { vpid, 0, gva };
1907
1908     asm volatile (__ex(ASM_VMX_INVVPID)
1909                   /* CF==1 or ZF==1 --> rc = -1 */
1910                   "; ja 1f ; ud2 ; 1:"
1911                   : : "a"(&operand), "c"(ext) : "cc", "memory");
1912 }
1913
1914 static inline void __invept(int ext, u64 eptp, gpa_t gpa)
1915 {
1916         struct {
1917                 u64 eptp, gpa;
1918         } operand = {eptp, gpa};
1919
1920         asm volatile (__ex(ASM_VMX_INVEPT)
1921                         /* CF==1 or ZF==1 --> rc = -1 */
1922                         "; ja 1f ; ud2 ; 1:\n"
1923                         : : "a" (&operand), "c" (ext) : "cc", "memory");
1924 }
1925
1926 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
1927 {
1928         int i;
1929
1930         i = __find_msr_index(vmx, msr);
1931         if (i >= 0)
1932                 return &vmx->guest_msrs[i];
1933         return NULL;
1934 }
1935
1936 static void vmcs_clear(struct vmcs *vmcs)
1937 {
1938         u64 phys_addr = __pa(vmcs);
1939         u8 error;
1940
1941         asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
1942                       : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1943                       : "cc", "memory");
1944         if (error)
1945                 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
1946                        vmcs, phys_addr);
1947 }
1948
1949 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
1950 {
1951         vmcs_clear(loaded_vmcs->vmcs);
1952         if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
1953                 vmcs_clear(loaded_vmcs->shadow_vmcs);
1954         loaded_vmcs->cpu = -1;
1955         loaded_vmcs->launched = 0;
1956 }
1957
1958 static void vmcs_load(struct vmcs *vmcs)
1959 {
1960         u64 phys_addr = __pa(vmcs);
1961         u8 error;
1962
1963         if (static_branch_unlikely(&enable_evmcs))
1964                 return evmcs_load(phys_addr);
1965
1966         asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
1967                         : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1968                         : "cc", "memory");
1969         if (error)
1970                 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
1971                        vmcs, phys_addr);
1972 }
1973
1974 #ifdef CONFIG_KEXEC_CORE
1975 /*
1976  * This bitmap is used to indicate whether the vmclear
1977  * operation is enabled on all cpus. All disabled by
1978  * default.
1979  */
1980 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
1981
1982 static inline void crash_enable_local_vmclear(int cpu)
1983 {
1984         cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
1985 }
1986
1987 static inline void crash_disable_local_vmclear(int cpu)
1988 {
1989         cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
1990 }
1991
1992 static inline int crash_local_vmclear_enabled(int cpu)
1993 {
1994         return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
1995 }
1996
1997 static void crash_vmclear_local_loaded_vmcss(void)
1998 {
1999         int cpu = raw_smp_processor_id();
2000         struct loaded_vmcs *v;
2001
2002         if (!crash_local_vmclear_enabled(cpu))
2003                 return;
2004
2005         list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
2006                             loaded_vmcss_on_cpu_link)
2007                 vmcs_clear(v->vmcs);
2008 }
2009 #else
2010 static inline void crash_enable_local_vmclear(int cpu) { }
2011 static inline void crash_disable_local_vmclear(int cpu) { }
2012 #endif /* CONFIG_KEXEC_CORE */
2013
2014 static void __loaded_vmcs_clear(void *arg)
2015 {
2016         struct loaded_vmcs *loaded_vmcs = arg;
2017         int cpu = raw_smp_processor_id();
2018
2019         if (loaded_vmcs->cpu != cpu)
2020                 return; /* vcpu migration can race with cpu offline */
2021         if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
2022                 per_cpu(current_vmcs, cpu) = NULL;
2023         crash_disable_local_vmclear(cpu);
2024         list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
2025
2026         /*
2027          * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
2028          * is before setting loaded_vmcs->vcpu to -1 which is done in
2029          * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
2030          * then adds the vmcs into percpu list before it is deleted.
2031          */
2032         smp_wmb();
2033
2034         loaded_vmcs_init(loaded_vmcs);
2035         crash_enable_local_vmclear(cpu);
2036 }
2037
2038 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
2039 {
2040         int cpu = loaded_vmcs->cpu;
2041
2042         if (cpu != -1)
2043                 smp_call_function_single(cpu,
2044                          __loaded_vmcs_clear, loaded_vmcs, 1);
2045 }
2046
2047 static inline bool vpid_sync_vcpu_addr(int vpid, gva_t addr)
2048 {
2049         if (vpid == 0)
2050                 return true;
2051
2052         if (cpu_has_vmx_invvpid_individual_addr()) {
2053                 __invvpid(VMX_VPID_EXTENT_INDIVIDUAL_ADDR, vpid, addr);
2054                 return true;
2055         }
2056
2057         return false;
2058 }
2059
2060 static inline void vpid_sync_vcpu_single(int vpid)
2061 {
2062         if (vpid == 0)
2063                 return;
2064
2065         if (cpu_has_vmx_invvpid_single())
2066                 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vpid, 0);
2067 }
2068
2069 static inline void vpid_sync_vcpu_global(void)
2070 {
2071         if (cpu_has_vmx_invvpid_global())
2072                 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
2073 }
2074
2075 static inline void vpid_sync_context(int vpid)
2076 {
2077         if (cpu_has_vmx_invvpid_single())
2078                 vpid_sync_vcpu_single(vpid);
2079         else
2080                 vpid_sync_vcpu_global();
2081 }
2082
2083 static inline void ept_sync_global(void)
2084 {
2085         __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
2086 }
2087
2088 static inline void ept_sync_context(u64 eptp)
2089 {
2090         if (cpu_has_vmx_invept_context())
2091                 __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
2092         else
2093                 ept_sync_global();
2094 }
2095
2096 static __always_inline void vmcs_check16(unsigned long field)
2097 {
2098         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
2099                          "16-bit accessor invalid for 64-bit field");
2100         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2101                          "16-bit accessor invalid for 64-bit high field");
2102         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2103                          "16-bit accessor invalid for 32-bit high field");
2104         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2105                          "16-bit accessor invalid for natural width field");
2106 }
2107
2108 static __always_inline void vmcs_check32(unsigned long field)
2109 {
2110         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2111                          "32-bit accessor invalid for 16-bit field");
2112         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2113                          "32-bit accessor invalid for natural width field");
2114 }
2115
2116 static __always_inline void vmcs_check64(unsigned long field)
2117 {
2118         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2119                          "64-bit accessor invalid for 16-bit field");
2120         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2121                          "64-bit accessor invalid for 64-bit high field");
2122         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2123                          "64-bit accessor invalid for 32-bit field");
2124         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2125                          "64-bit accessor invalid for natural width field");
2126 }
2127
2128 static __always_inline void vmcs_checkl(unsigned long field)
2129 {
2130         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2131                          "Natural width accessor invalid for 16-bit field");
2132         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
2133                          "Natural width accessor invalid for 64-bit field");
2134         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2135                          "Natural width accessor invalid for 64-bit high field");
2136         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2137                          "Natural width accessor invalid for 32-bit field");
2138 }
2139
2140 static __always_inline unsigned long __vmcs_readl(unsigned long field)
2141 {
2142         unsigned long value;
2143
2144         asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
2145                       : "=a"(value) : "d"(field) : "cc");
2146         return value;
2147 }
2148
2149 static __always_inline u16 vmcs_read16(unsigned long field)
2150 {
2151         vmcs_check16(field);
2152         if (static_branch_unlikely(&enable_evmcs))
2153                 return evmcs_read16(field);
2154         return __vmcs_readl(field);
2155 }
2156
2157 static __always_inline u32 vmcs_read32(unsigned long field)
2158 {
2159         vmcs_check32(field);
2160         if (static_branch_unlikely(&enable_evmcs))
2161                 return evmcs_read32(field);
2162         return __vmcs_readl(field);
2163 }
2164
2165 static __always_inline u64 vmcs_read64(unsigned long field)
2166 {
2167         vmcs_check64(field);
2168         if (static_branch_unlikely(&enable_evmcs))
2169                 return evmcs_read64(field);
2170 #ifdef CONFIG_X86_64
2171         return __vmcs_readl(field);
2172 #else
2173         return __vmcs_readl(field) | ((u64)__vmcs_readl(field+1) << 32);
2174 #endif
2175 }
2176
2177 static __always_inline unsigned long vmcs_readl(unsigned long field)
2178 {
2179         vmcs_checkl(field);
2180         if (static_branch_unlikely(&enable_evmcs))
2181                 return evmcs_read64(field);
2182         return __vmcs_readl(field);
2183 }
2184
2185 static noinline void vmwrite_error(unsigned long field, unsigned long value)
2186 {
2187         printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
2188                field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
2189         dump_stack();
2190 }
2191
2192 static __always_inline void __vmcs_writel(unsigned long field, unsigned long value)
2193 {
2194         u8 error;
2195
2196         asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
2197                        : "=q"(error) : "a"(value), "d"(field) : "cc");
2198         if (unlikely(error))
2199                 vmwrite_error(field, value);
2200 }
2201
2202 static __always_inline void vmcs_write16(unsigned long field, u16 value)
2203 {
2204         vmcs_check16(field);
2205         if (static_branch_unlikely(&enable_evmcs))
2206                 return evmcs_write16(field, value);
2207
2208         __vmcs_writel(field, value);
2209 }
2210
2211 static __always_inline void vmcs_write32(unsigned long field, u32 value)
2212 {
2213         vmcs_check32(field);
2214         if (static_branch_unlikely(&enable_evmcs))
2215                 return evmcs_write32(field, value);
2216
2217         __vmcs_writel(field, value);
2218 }
2219
2220 static __always_inline void vmcs_write64(unsigned long field, u64 value)
2221 {
2222         vmcs_check64(field);
2223         if (static_branch_unlikely(&enable_evmcs))
2224                 return evmcs_write64(field, value);
2225
2226         __vmcs_writel(field, value);
2227 #ifndef CONFIG_X86_64
2228         asm volatile ("");
2229         __vmcs_writel(field+1, value >> 32);
2230 #endif
2231 }
2232
2233 static __always_inline void vmcs_writel(unsigned long field, unsigned long value)
2234 {
2235         vmcs_checkl(field);
2236         if (static_branch_unlikely(&enable_evmcs))
2237                 return evmcs_write64(field, value);
2238
2239         __vmcs_writel(field, value);
2240 }
2241
2242 static __always_inline void vmcs_clear_bits(unsigned long field, u32 mask)
2243 {
2244         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
2245                          "vmcs_clear_bits does not support 64-bit fields");
2246         if (static_branch_unlikely(&enable_evmcs))
2247                 return evmcs_write32(field, evmcs_read32(field) & ~mask);
2248
2249         __vmcs_writel(field, __vmcs_readl(field) & ~mask);
2250 }
2251
2252 static __always_inline void vmcs_set_bits(unsigned long field, u32 mask)
2253 {
2254         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
2255                          "vmcs_set_bits does not support 64-bit fields");
2256         if (static_branch_unlikely(&enable_evmcs))
2257                 return evmcs_write32(field, evmcs_read32(field) | mask);
2258
2259         __vmcs_writel(field, __vmcs_readl(field) | mask);
2260 }
2261
2262 static inline void vm_entry_controls_reset_shadow(struct vcpu_vmx *vmx)
2263 {
2264         vmx->vm_entry_controls_shadow = vmcs_read32(VM_ENTRY_CONTROLS);
2265 }
2266
2267 static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
2268 {
2269         vmcs_write32(VM_ENTRY_CONTROLS, val);
2270         vmx->vm_entry_controls_shadow = val;
2271 }
2272
2273 static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
2274 {
2275         if (vmx->vm_entry_controls_shadow != val)
2276                 vm_entry_controls_init(vmx, val);
2277 }
2278
2279 static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
2280 {
2281         return vmx->vm_entry_controls_shadow;
2282 }
2283
2284
2285 static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
2286 {
2287         vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
2288 }
2289
2290 static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
2291 {
2292         vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
2293 }
2294
2295 static inline void vm_exit_controls_reset_shadow(struct vcpu_vmx *vmx)
2296 {
2297         vmx->vm_exit_controls_shadow = vmcs_read32(VM_EXIT_CONTROLS);
2298 }
2299
2300 static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
2301 {
2302         vmcs_write32(VM_EXIT_CONTROLS, val);
2303         vmx->vm_exit_controls_shadow = val;
2304 }
2305
2306 static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
2307 {
2308         if (vmx->vm_exit_controls_shadow != val)
2309                 vm_exit_controls_init(vmx, val);
2310 }
2311
2312 static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
2313 {
2314         return vmx->vm_exit_controls_shadow;
2315 }
2316
2317
2318 static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
2319 {
2320         vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
2321 }
2322
2323 static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
2324 {
2325         vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
2326 }
2327
2328 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
2329 {
2330         vmx->segment_cache.bitmask = 0;
2331 }
2332
2333 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
2334                                        unsigned field)
2335 {
2336         bool ret;
2337         u32 mask = 1 << (seg * SEG_FIELD_NR + field);
2338
2339         if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
2340                 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
2341                 vmx->segment_cache.bitmask = 0;
2342         }
2343         ret = vmx->segment_cache.bitmask & mask;
2344         vmx->segment_cache.bitmask |= mask;
2345         return ret;
2346 }
2347
2348 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
2349 {
2350         u16 *p = &vmx->segment_cache.seg[seg].selector;
2351
2352         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
2353                 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
2354         return *p;
2355 }
2356
2357 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
2358 {
2359         ulong *p = &vmx->segment_cache.seg[seg].base;
2360
2361         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
2362                 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
2363         return *p;
2364 }
2365
2366 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
2367 {
2368         u32 *p = &vmx->segment_cache.seg[seg].limit;
2369
2370         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
2371                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
2372         return *p;
2373 }
2374
2375 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
2376 {
2377         u32 *p = &vmx->segment_cache.seg[seg].ar;
2378
2379         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
2380                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
2381         return *p;
2382 }
2383
2384 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
2385 {
2386         u32 eb;
2387
2388         eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
2389              (1u << DB_VECTOR) | (1u << AC_VECTOR);
2390         /*
2391          * Guest access to VMware backdoor ports could legitimately
2392          * trigger #GP because of TSS I/O permission bitmap.
2393          * We intercept those #GP and allow access to them anyway
2394          * as VMware does.
2395          */
2396         if (enable_vmware_backdoor)
2397                 eb |= (1u << GP_VECTOR);
2398         if ((vcpu->guest_debug &
2399              (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
2400             (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
2401                 eb |= 1u << BP_VECTOR;
2402         if (to_vmx(vcpu)->rmode.vm86_active)
2403                 eb = ~0;
2404         if (enable_ept)
2405                 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
2406
2407         /* When we are running a nested L2 guest and L1 specified for it a
2408          * certain exception bitmap, we must trap the same exceptions and pass
2409          * them to L1. When running L2, we will only handle the exceptions
2410          * specified above if L1 did not want them.
2411          */
2412         if (is_guest_mode(vcpu))
2413                 eb |= get_vmcs12(vcpu)->exception_bitmap;
2414
2415         vmcs_write32(EXCEPTION_BITMAP, eb);
2416 }
2417
2418 /*
2419  * Check if MSR is intercepted for currently loaded MSR bitmap.
2420  */
2421 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
2422 {
2423         unsigned long *msr_bitmap;
2424         int f = sizeof(unsigned long);
2425
2426         if (!cpu_has_vmx_msr_bitmap())
2427                 return true;
2428
2429         msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
2430
2431         if (msr <= 0x1fff) {
2432                 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2433         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2434                 msr &= 0x1fff;
2435                 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2436         }
2437
2438         return true;
2439 }
2440
2441 /*
2442  * Check if MSR is intercepted for L01 MSR bitmap.
2443  */
2444 static bool msr_write_intercepted_l01(struct kvm_vcpu *vcpu, u32 msr)
2445 {
2446         unsigned long *msr_bitmap;
2447         int f = sizeof(unsigned long);
2448
2449         if (!cpu_has_vmx_msr_bitmap())
2450                 return true;
2451
2452         msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
2453
2454         if (msr <= 0x1fff) {
2455                 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2456         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2457                 msr &= 0x1fff;
2458                 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2459         }
2460
2461         return true;
2462 }
2463
2464 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2465                 unsigned long entry, unsigned long exit)
2466 {
2467         vm_entry_controls_clearbit(vmx, entry);
2468         vm_exit_controls_clearbit(vmx, exit);
2469 }
2470
2471 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
2472 {
2473         unsigned i;
2474         struct msr_autoload *m = &vmx->msr_autoload;
2475
2476         switch (msr) {
2477         case MSR_EFER:
2478                 if (cpu_has_load_ia32_efer) {
2479                         clear_atomic_switch_msr_special(vmx,
2480                                         VM_ENTRY_LOAD_IA32_EFER,
2481                                         VM_EXIT_LOAD_IA32_EFER);
2482                         return;
2483                 }
2484                 break;
2485         case MSR_CORE_PERF_GLOBAL_CTRL:
2486                 if (cpu_has_load_perf_global_ctrl) {
2487                         clear_atomic_switch_msr_special(vmx,
2488                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2489                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
2490                         return;
2491                 }
2492                 break;
2493         }
2494
2495         for (i = 0; i < m->nr; ++i)
2496                 if (m->guest[i].index == msr)
2497                         break;
2498
2499         if (i == m->nr)
2500                 return;
2501         --m->nr;
2502         m->guest[i] = m->guest[m->nr];
2503         m->host[i] = m->host[m->nr];
2504         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
2505         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
2506 }
2507
2508 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2509                 unsigned long entry, unsigned long exit,
2510                 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
2511                 u64 guest_val, u64 host_val)
2512 {
2513         vmcs_write64(guest_val_vmcs, guest_val);
2514         vmcs_write64(host_val_vmcs, host_val);
2515         vm_entry_controls_setbit(vmx, entry);
2516         vm_exit_controls_setbit(vmx, exit);
2517 }
2518
2519 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
2520                                   u64 guest_val, u64 host_val)
2521 {
2522         unsigned i;
2523         struct msr_autoload *m = &vmx->msr_autoload;
2524
2525         switch (msr) {
2526         case MSR_EFER:
2527                 if (cpu_has_load_ia32_efer) {
2528                         add_atomic_switch_msr_special(vmx,
2529                                         VM_ENTRY_LOAD_IA32_EFER,
2530                                         VM_EXIT_LOAD_IA32_EFER,
2531                                         GUEST_IA32_EFER,
2532                                         HOST_IA32_EFER,
2533                                         guest_val, host_val);
2534                         return;
2535                 }
2536                 break;
2537         case MSR_CORE_PERF_GLOBAL_CTRL:
2538                 if (cpu_has_load_perf_global_ctrl) {
2539                         add_atomic_switch_msr_special(vmx,
2540                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2541                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
2542                                         GUEST_IA32_PERF_GLOBAL_CTRL,
2543                                         HOST_IA32_PERF_GLOBAL_CTRL,
2544                                         guest_val, host_val);
2545                         return;
2546                 }
2547                 break;
2548         case MSR_IA32_PEBS_ENABLE:
2549                 /* PEBS needs a quiescent period after being disabled (to write
2550                  * a record).  Disabling PEBS through VMX MSR swapping doesn't
2551                  * provide that period, so a CPU could write host's record into
2552                  * guest's memory.
2553                  */
2554                 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
2555         }
2556
2557         for (i = 0; i < m->nr; ++i)
2558                 if (m->guest[i].index == msr)
2559                         break;
2560
2561         if (i == NR_AUTOLOAD_MSRS) {
2562                 printk_once(KERN_WARNING "Not enough msr switch entries. "
2563                                 "Can't add msr %x\n", msr);
2564                 return;
2565         } else if (i == m->nr) {
2566                 ++m->nr;
2567                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
2568                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
2569         }
2570
2571         m->guest[i].index = msr;
2572         m->guest[i].value = guest_val;
2573         m->host[i].index = msr;
2574         m->host[i].value = host_val;
2575 }
2576
2577 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
2578 {
2579         u64 guest_efer = vmx->vcpu.arch.efer;
2580         u64 ignore_bits = 0;
2581
2582         if (!enable_ept) {
2583                 /*
2584                  * NX is needed to handle CR0.WP=1, CR4.SMEP=1.  Testing
2585                  * host CPUID is more efficient than testing guest CPUID
2586                  * or CR4.  Host SMEP is anyway a requirement for guest SMEP.
2587                  */
2588                 if (boot_cpu_has(X86_FEATURE_SMEP))
2589                         guest_efer |= EFER_NX;
2590                 else if (!(guest_efer & EFER_NX))
2591                         ignore_bits |= EFER_NX;
2592         }
2593
2594         /*
2595          * LMA and LME handled by hardware; SCE meaningless outside long mode.
2596          */
2597         ignore_bits |= EFER_SCE;
2598 #ifdef CONFIG_X86_64
2599         ignore_bits |= EFER_LMA | EFER_LME;
2600         /* SCE is meaningful only in long mode on Intel */
2601         if (guest_efer & EFER_LMA)
2602                 ignore_bits &= ~(u64)EFER_SCE;
2603 #endif
2604
2605         clear_atomic_switch_msr(vmx, MSR_EFER);
2606
2607         /*
2608          * On EPT, we can't emulate NX, so we must switch EFER atomically.
2609          * On CPUs that support "load IA32_EFER", always switch EFER
2610          * atomically, since it's faster than switching it manually.
2611          */
2612         if (cpu_has_load_ia32_efer ||
2613             (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
2614                 if (!(guest_efer & EFER_LMA))
2615                         guest_efer &= ~EFER_LME;
2616                 if (guest_efer != host_efer)
2617                         add_atomic_switch_msr(vmx, MSR_EFER,
2618                                               guest_efer, host_efer);
2619                 return false;
2620         } else {
2621                 guest_efer &= ~ignore_bits;
2622                 guest_efer |= host_efer & ignore_bits;
2623
2624                 vmx->guest_msrs[efer_offset].data = guest_efer;
2625                 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
2626
2627                 return true;
2628         }
2629 }
2630
2631 #ifdef CONFIG_X86_32
2632 /*
2633  * On 32-bit kernels, VM exits still load the FS and GS bases from the
2634  * VMCS rather than the segment table.  KVM uses this helper to figure
2635  * out the current bases to poke them into the VMCS before entry.
2636  */
2637 static unsigned long segment_base(u16 selector)
2638 {
2639         struct desc_struct *table;
2640         unsigned long v;
2641
2642         if (!(selector & ~SEGMENT_RPL_MASK))
2643                 return 0;
2644
2645         table = get_current_gdt_ro();
2646
2647         if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
2648                 u16 ldt_selector = kvm_read_ldt();
2649
2650                 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
2651                         return 0;
2652
2653                 table = (struct desc_struct *)segment_base(ldt_selector);
2654         }
2655         v = get_desc_base(&table[selector >> 3]);
2656         return v;
2657 }
2658 #endif
2659
2660 static void vmx_save_host_state(struct kvm_vcpu *vcpu)
2661 {
2662         struct vcpu_vmx *vmx = to_vmx(vcpu);
2663 #ifdef CONFIG_X86_64
2664         int cpu = raw_smp_processor_id();
2665         unsigned long fs_base, kernel_gs_base;
2666 #endif
2667         int i;
2668
2669         if (vmx->host_state.loaded)
2670                 return;
2671
2672         vmx->host_state.loaded = 1;
2673         /*
2674          * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
2675          * allow segment selectors with cpl > 0 or ti == 1.
2676          */
2677         vmx->host_state.ldt_sel = kvm_read_ldt();
2678         vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
2679
2680 #ifdef CONFIG_X86_64
2681         if (likely(is_64bit_mm(current->mm))) {
2682                 save_fsgs_for_kvm();
2683                 vmx->host_state.fs_sel = current->thread.fsindex;
2684                 vmx->host_state.gs_sel = current->thread.gsindex;
2685                 fs_base = current->thread.fsbase;
2686                 kernel_gs_base = current->thread.gsbase;
2687         } else {
2688 #endif
2689                 savesegment(fs, vmx->host_state.fs_sel);
2690                 savesegment(gs, vmx->host_state.gs_sel);
2691 #ifdef CONFIG_X86_64
2692                 fs_base = read_msr(MSR_FS_BASE);
2693                 kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
2694         }
2695 #endif
2696         if (!(vmx->host_state.fs_sel & 7)) {
2697                 vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
2698                 vmx->host_state.fs_reload_needed = 0;
2699         } else {
2700                 vmcs_write16(HOST_FS_SELECTOR, 0);
2701                 vmx->host_state.fs_reload_needed = 1;
2702         }
2703         if (!(vmx->host_state.gs_sel & 7))
2704                 vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
2705         else {
2706                 vmcs_write16(HOST_GS_SELECTOR, 0);
2707                 vmx->host_state.gs_ldt_reload_needed = 1;
2708         }
2709
2710 #ifdef CONFIG_X86_64
2711         savesegment(ds, vmx->host_state.ds_sel);
2712         savesegment(es, vmx->host_state.es_sel);
2713
2714         vmcs_writel(HOST_FS_BASE, fs_base);
2715         vmcs_writel(HOST_GS_BASE, cpu_kernelmode_gs_base(cpu));
2716
2717         vmx->msr_host_kernel_gs_base = kernel_gs_base;
2718         if (is_long_mode(&vmx->vcpu))
2719                 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2720 #else
2721         vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
2722         vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
2723 #endif
2724         for (i = 0; i < vmx->save_nmsrs; ++i)
2725                 kvm_set_shared_msr(vmx->guest_msrs[i].index,
2726                                    vmx->guest_msrs[i].data,
2727                                    vmx->guest_msrs[i].mask);
2728 }
2729
2730 static void __vmx_load_host_state(struct vcpu_vmx *vmx)
2731 {
2732         if (!vmx->host_state.loaded)
2733                 return;
2734
2735         ++vmx->vcpu.stat.host_state_reload;
2736         vmx->host_state.loaded = 0;
2737 #ifdef CONFIG_X86_64
2738         if (is_long_mode(&vmx->vcpu))
2739                 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2740 #endif
2741         if (vmx->host_state.gs_ldt_reload_needed) {
2742                 kvm_load_ldt(vmx->host_state.ldt_sel);
2743 #ifdef CONFIG_X86_64
2744                 load_gs_index(vmx->host_state.gs_sel);
2745 #else
2746                 loadsegment(gs, vmx->host_state.gs_sel);
2747 #endif
2748         }
2749         if (vmx->host_state.fs_reload_needed)
2750                 loadsegment(fs, vmx->host_state.fs_sel);
2751 #ifdef CONFIG_X86_64
2752         if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
2753                 loadsegment(ds, vmx->host_state.ds_sel);
2754                 loadsegment(es, vmx->host_state.es_sel);
2755         }
2756 #endif
2757         invalidate_tss_limit();
2758 #ifdef CONFIG_X86_64
2759         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2760 #endif
2761         load_fixmap_gdt(raw_smp_processor_id());
2762 }
2763
2764 static void vmx_load_host_state(struct vcpu_vmx *vmx)
2765 {
2766         preempt_disable();
2767         __vmx_load_host_state(vmx);
2768         preempt_enable();
2769 }
2770
2771 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
2772 {
2773         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2774         struct pi_desc old, new;
2775         unsigned int dest;
2776
2777         /*
2778          * In case of hot-plug or hot-unplug, we may have to undo
2779          * vmx_vcpu_pi_put even if there is no assigned device.  And we
2780          * always keep PI.NDST up to date for simplicity: it makes the
2781          * code easier, and CPU migration is not a fast path.
2782          */
2783         if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
2784                 return;
2785
2786         /*
2787          * First handle the simple case where no cmpxchg is necessary; just
2788          * allow posting non-urgent interrupts.
2789          *
2790          * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
2791          * PI.NDST: pi_post_block will do it for us and the wakeup_handler
2792          * expects the VCPU to be on the blocked_vcpu_list that matches
2793          * PI.NDST.
2794          */
2795         if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR ||
2796             vcpu->cpu == cpu) {
2797                 pi_clear_sn(pi_desc);
2798                 return;
2799         }
2800
2801         /* The full case.  */
2802         do {
2803                 old.control = new.control = pi_desc->control;
2804
2805                 dest = cpu_physical_id(cpu);
2806
2807                 if (x2apic_enabled())
2808                         new.ndst = dest;
2809                 else
2810                         new.ndst = (dest << 8) & 0xFF00;
2811
2812                 new.sn = 0;
2813         } while (cmpxchg64(&pi_desc->control, old.control,
2814                            new.control) != old.control);
2815 }
2816
2817 static void decache_tsc_multiplier(struct vcpu_vmx *vmx)
2818 {
2819         vmx->current_tsc_ratio = vmx->vcpu.arch.tsc_scaling_ratio;
2820         vmcs_write64(TSC_MULTIPLIER, vmx->current_tsc_ratio);
2821 }
2822
2823 /*
2824  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
2825  * vcpu mutex is already taken.
2826  */
2827 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2828 {
2829         struct vcpu_vmx *vmx = to_vmx(vcpu);
2830         bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
2831
2832         if (!already_loaded) {
2833                 loaded_vmcs_clear(vmx->loaded_vmcs);
2834                 local_irq_disable();
2835                 crash_disable_local_vmclear(cpu);
2836
2837                 /*
2838                  * Read loaded_vmcs->cpu should be before fetching
2839                  * loaded_vmcs->loaded_vmcss_on_cpu_link.
2840                  * See the comments in __loaded_vmcs_clear().
2841                  */
2842                 smp_rmb();
2843
2844                 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
2845                          &per_cpu(loaded_vmcss_on_cpu, cpu));
2846                 crash_enable_local_vmclear(cpu);
2847                 local_irq_enable();
2848         }
2849
2850         if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
2851                 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
2852                 vmcs_load(vmx->loaded_vmcs->vmcs);
2853                 indirect_branch_prediction_barrier();
2854         }
2855
2856         if (!already_loaded) {
2857                 void *gdt = get_current_gdt_ro();
2858                 unsigned long sysenter_esp;
2859
2860                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2861
2862                 /*
2863                  * Linux uses per-cpu TSS and GDT, so set these when switching
2864                  * processors.  See 22.2.4.
2865                  */
2866                 vmcs_writel(HOST_TR_BASE,
2867                             (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
2868                 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt);   /* 22.2.4 */
2869
2870                 /*
2871                  * VM exits change the host TR limit to 0x67 after a VM
2872                  * exit.  This is okay, since 0x67 covers everything except
2873                  * the IO bitmap and have have code to handle the IO bitmap
2874                  * being lost after a VM exit.
2875                  */
2876                 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
2877
2878                 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
2879                 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
2880
2881                 vmx->loaded_vmcs->cpu = cpu;
2882         }
2883
2884         /* Setup TSC multiplier */
2885         if (kvm_has_tsc_control &&
2886             vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
2887                 decache_tsc_multiplier(vmx);
2888
2889         vmx_vcpu_pi_load(vcpu, cpu);
2890         vmx->host_pkru = read_pkru();
2891         vmx->host_debugctlmsr = get_debugctlmsr();
2892 }
2893
2894 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
2895 {
2896         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2897
2898         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
2899                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
2900                 !kvm_vcpu_apicv_active(vcpu))
2901                 return;
2902
2903         /* Set SN when the vCPU is preempted */
2904         if (vcpu->preempted)
2905                 pi_set_sn(pi_desc);
2906 }
2907
2908 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
2909 {
2910         vmx_vcpu_pi_put(vcpu);
2911
2912         __vmx_load_host_state(to_vmx(vcpu));
2913 }
2914
2915 static bool emulation_required(struct kvm_vcpu *vcpu)
2916 {
2917         return emulate_invalid_guest_state && !guest_state_valid(vcpu);
2918 }
2919
2920 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
2921
2922 /*
2923  * Return the cr0 value that a nested guest would read. This is a combination
2924  * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
2925  * its hypervisor (cr0_read_shadow).
2926  */
2927 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
2928 {
2929         return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
2930                 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
2931 }
2932 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
2933 {
2934         return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
2935                 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
2936 }
2937
2938 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
2939 {
2940         unsigned long rflags, save_rflags;
2941
2942         if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
2943                 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2944                 rflags = vmcs_readl(GUEST_RFLAGS);
2945                 if (to_vmx(vcpu)->rmode.vm86_active) {
2946                         rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2947                         save_rflags = to_vmx(vcpu)->rmode.save_rflags;
2948                         rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2949                 }
2950                 to_vmx(vcpu)->rflags = rflags;
2951         }
2952         return to_vmx(vcpu)->rflags;
2953 }
2954
2955 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2956 {
2957         unsigned long old_rflags = vmx_get_rflags(vcpu);
2958
2959         __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2960         to_vmx(vcpu)->rflags = rflags;
2961         if (to_vmx(vcpu)->rmode.vm86_active) {
2962                 to_vmx(vcpu)->rmode.save_rflags = rflags;
2963                 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2964         }
2965         vmcs_writel(GUEST_RFLAGS, rflags);
2966
2967         if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
2968                 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
2969 }
2970
2971 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
2972 {
2973         u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2974         int ret = 0;
2975
2976         if (interruptibility & GUEST_INTR_STATE_STI)
2977                 ret |= KVM_X86_SHADOW_INT_STI;
2978         if (interruptibility & GUEST_INTR_STATE_MOV_SS)
2979                 ret |= KVM_X86_SHADOW_INT_MOV_SS;
2980
2981         return ret;
2982 }
2983
2984 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
2985 {
2986         u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2987         u32 interruptibility = interruptibility_old;
2988
2989         interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
2990
2991         if (mask & KVM_X86_SHADOW_INT_MOV_SS)
2992                 interruptibility |= GUEST_INTR_STATE_MOV_SS;
2993         else if (mask & KVM_X86_SHADOW_INT_STI)
2994                 interruptibility |= GUEST_INTR_STATE_STI;
2995
2996         if ((interruptibility != interruptibility_old))
2997                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
2998 }
2999
3000 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
3001 {
3002         unsigned long rip;
3003
3004         rip = kvm_rip_read(vcpu);
3005         rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
3006         kvm_rip_write(vcpu, rip);
3007
3008         /* skipping an emulated instruction also counts */
3009         vmx_set_interrupt_shadow(vcpu, 0);
3010 }
3011
3012 static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
3013                                                unsigned long exit_qual)
3014 {
3015         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3016         unsigned int nr = vcpu->arch.exception.nr;
3017         u32 intr_info = nr | INTR_INFO_VALID_MASK;
3018
3019         if (vcpu->arch.exception.has_error_code) {
3020                 vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code;
3021                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
3022         }
3023
3024         if (kvm_exception_is_soft(nr))
3025                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
3026         else
3027                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
3028
3029         if (!(vmcs12->idt_vectoring_info_field & VECTORING_INFO_VALID_MASK) &&
3030             vmx_get_nmi_mask(vcpu))
3031                 intr_info |= INTR_INFO_UNBLOCK_NMI;
3032
3033         nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI, intr_info, exit_qual);
3034 }
3035
3036 /*
3037  * KVM wants to inject page-faults which it got to the guest. This function
3038  * checks whether in a nested guest, we need to inject them to L1 or L2.
3039  */
3040 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned long *exit_qual)
3041 {
3042         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3043         unsigned int nr = vcpu->arch.exception.nr;
3044
3045         if (nr == PF_VECTOR) {
3046                 if (vcpu->arch.exception.nested_apf) {
3047                         *exit_qual = vcpu->arch.apf.nested_apf_token;
3048                         return 1;
3049                 }
3050                 /*
3051                  * FIXME: we must not write CR2 when L1 intercepts an L2 #PF exception.
3052                  * The fix is to add the ancillary datum (CR2 or DR6) to structs
3053                  * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6
3054                  * can be written only when inject_pending_event runs.  This should be
3055                  * conditional on a new capability---if the capability is disabled,
3056                  * kvm_multiple_exception would write the ancillary information to
3057                  * CR2 or DR6, for backwards ABI-compatibility.
3058                  */
3059                 if (nested_vmx_is_page_fault_vmexit(vmcs12,
3060                                                     vcpu->arch.exception.error_code)) {
3061                         *exit_qual = vcpu->arch.cr2;
3062                         return 1;
3063                 }
3064         } else {
3065                 if (vmcs12->exception_bitmap & (1u << nr)) {
3066                         if (nr == DB_VECTOR)
3067                                 *exit_qual = vcpu->arch.dr6;
3068                         else
3069                                 *exit_qual = 0;
3070                         return 1;
3071                 }
3072         }
3073
3074         return 0;
3075 }
3076
3077 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
3078 {
3079         /*
3080          * Ensure that we clear the HLT state in the VMCS.  We don't need to
3081          * explicitly skip the instruction because if the HLT state is set,
3082          * then the instruction is already executing and RIP has already been
3083          * advanced.
3084          */
3085         if (kvm_hlt_in_guest(vcpu->kvm) &&
3086                         vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
3087                 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
3088 }
3089
3090 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
3091 {
3092         struct vcpu_vmx *vmx = to_vmx(vcpu);
3093         unsigned nr = vcpu->arch.exception.nr;
3094         bool has_error_code = vcpu->arch.exception.has_error_code;
3095         u32 error_code = vcpu->arch.exception.error_code;
3096         u32 intr_info = nr | INTR_INFO_VALID_MASK;
3097
3098         if (has_error_code) {
3099                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
3100                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
3101         }
3102
3103         if (vmx->rmode.vm86_active) {
3104                 int inc_eip = 0;
3105                 if (kvm_exception_is_soft(nr))
3106                         inc_eip = vcpu->arch.event_exit_inst_len;
3107                 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
3108                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3109                 return;
3110         }
3111
3112         WARN_ON_ONCE(vmx->emulation_required);
3113
3114         if (kvm_exception_is_soft(nr)) {
3115                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
3116                              vmx->vcpu.arch.event_exit_inst_len);
3117                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
3118         } else
3119                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
3120
3121         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
3122
3123         vmx_clear_hlt(vcpu);
3124 }
3125
3126 static bool vmx_rdtscp_supported(void)
3127 {
3128         return cpu_has_vmx_rdtscp();
3129 }
3130
3131 static bool vmx_invpcid_supported(void)
3132 {
3133         return cpu_has_vmx_invpcid();
3134 }
3135
3136 /*
3137  * Swap MSR entry in host/guest MSR entry array.
3138  */
3139 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
3140 {
3141         struct shared_msr_entry tmp;
3142
3143         tmp = vmx->guest_msrs[to];
3144         vmx->guest_msrs[to] = vmx->guest_msrs[from];
3145         vmx->guest_msrs[from] = tmp;
3146 }
3147
3148 /*
3149  * Set up the vmcs to automatically save and restore system
3150  * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
3151  * mode, as fiddling with msrs is very expensive.
3152  */
3153 static void setup_msrs(struct vcpu_vmx *vmx)
3154 {
3155         int save_nmsrs, index;
3156
3157         save_nmsrs = 0;
3158 #ifdef CONFIG_X86_64
3159         if (is_long_mode(&vmx->vcpu)) {
3160                 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
3161                 if (index >= 0)
3162                         move_msr_up(vmx, index, save_nmsrs++);
3163                 index = __find_msr_index(vmx, MSR_LSTAR);
3164                 if (index >= 0)
3165                         move_msr_up(vmx, index, save_nmsrs++);
3166                 index = __find_msr_index(vmx, MSR_CSTAR);
3167                 if (index >= 0)
3168                         move_msr_up(vmx, index, save_nmsrs++);
3169                 index = __find_msr_index(vmx, MSR_TSC_AUX);
3170                 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
3171                         move_msr_up(vmx, index, save_nmsrs++);
3172                 /*
3173                  * MSR_STAR is only needed on long mode guests, and only
3174                  * if efer.sce is enabled.
3175                  */
3176                 index = __find_msr_index(vmx, MSR_STAR);
3177                 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
3178                         move_msr_up(vmx, index, save_nmsrs++);
3179         }
3180 #endif
3181         index = __find_msr_index(vmx, MSR_EFER);
3182         if (index >= 0 && update_transition_efer(vmx, index))
3183                 move_msr_up(vmx, index, save_nmsrs++);
3184
3185         vmx->save_nmsrs = save_nmsrs;
3186
3187         if (cpu_has_vmx_msr_bitmap())
3188                 vmx_update_msr_bitmap(&vmx->vcpu);
3189 }
3190
3191 static u64 vmx_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
3192 {
3193         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3194
3195         if (is_guest_mode(vcpu) &&
3196             (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
3197                 return vcpu->arch.tsc_offset - vmcs12->tsc_offset;
3198
3199         return vcpu->arch.tsc_offset;
3200 }
3201
3202 /*
3203  * writes 'offset' into guest's timestamp counter offset register
3204  */
3205 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
3206 {
3207         if (is_guest_mode(vcpu)) {
3208                 /*
3209                  * We're here if L1 chose not to trap WRMSR to TSC. According
3210                  * to the spec, this should set L1's TSC; The offset that L1
3211                  * set for L2 remains unchanged, and still needs to be added
3212                  * to the newly set TSC to get L2's TSC.
3213                  */
3214                 struct vmcs12 *vmcs12;
3215                 /* recalculate vmcs02.TSC_OFFSET: */
3216                 vmcs12 = get_vmcs12(vcpu);
3217                 vmcs_write64(TSC_OFFSET, offset +
3218                         (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
3219                          vmcs12->tsc_offset : 0));
3220         } else {
3221                 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
3222                                            vmcs_read64(TSC_OFFSET), offset);
3223                 vmcs_write64(TSC_OFFSET, offset);
3224         }
3225 }
3226
3227 /*
3228  * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
3229  * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
3230  * all guests if the "nested" module option is off, and can also be disabled
3231  * for a single guest by disabling its VMX cpuid bit.
3232  */
3233 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
3234 {
3235         return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
3236 }
3237
3238 /*
3239  * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
3240  * returned for the various VMX controls MSRs when nested VMX is enabled.
3241  * The same values should also be used to verify that vmcs12 control fields are
3242  * valid during nested entry from L1 to L2.
3243  * Each of these control msrs has a low and high 32-bit half: A low bit is on
3244  * if the corresponding bit in the (32-bit) control field *must* be on, and a
3245  * bit in the high half is on if the corresponding bit in the control field
3246  * may be on. See also vmx_control_verify().
3247  */
3248 static void nested_vmx_setup_ctls_msrs(struct nested_vmx_msrs *msrs, bool apicv)
3249 {
3250         if (!nested) {
3251                 memset(msrs, 0, sizeof(*msrs));
3252                 return;
3253         }
3254
3255         /*
3256          * Note that as a general rule, the high half of the MSRs (bits in
3257          * the control fields which may be 1) should be initialized by the
3258          * intersection of the underlying hardware's MSR (i.e., features which
3259          * can be supported) and the list of features we want to expose -
3260          * because they are known to be properly supported in our code.
3261          * Also, usually, the low half of the MSRs (bits which must be 1) can
3262          * be set to 0, meaning that L1 may turn off any of these bits. The
3263          * reason is that if one of these bits is necessary, it will appear
3264          * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
3265          * fields of vmcs01 and vmcs02, will turn these bits off - and
3266          * nested_vmx_exit_reflected() will not pass related exits to L1.
3267          * These rules have exceptions below.
3268          */
3269
3270         /* pin-based controls */
3271         rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
3272                 msrs->pinbased_ctls_low,
3273                 msrs->pinbased_ctls_high);
3274         msrs->pinbased_ctls_low |=
3275                 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3276         msrs->pinbased_ctls_high &=
3277                 PIN_BASED_EXT_INTR_MASK |
3278                 PIN_BASED_NMI_EXITING |
3279                 PIN_BASED_VIRTUAL_NMIS |
3280                 (apicv ? PIN_BASED_POSTED_INTR : 0);
3281         msrs->pinbased_ctls_high |=
3282                 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
3283                 PIN_BASED_VMX_PREEMPTION_TIMER;
3284
3285         /* exit controls */
3286         rdmsr(MSR_IA32_VMX_EXIT_CTLS,
3287                 msrs->exit_ctls_low,
3288                 msrs->exit_ctls_high);
3289         msrs->exit_ctls_low =
3290                 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
3291
3292         msrs->exit_ctls_high &=
3293 #ifdef CONFIG_X86_64
3294                 VM_EXIT_HOST_ADDR_SPACE_SIZE |
3295 #endif
3296                 VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
3297         msrs->exit_ctls_high |=
3298                 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
3299                 VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
3300                 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
3301
3302         if (kvm_mpx_supported())
3303                 msrs->exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
3304
3305         /* We support free control of debug control saving. */
3306         msrs->exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
3307
3308         /* entry controls */
3309         rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
3310                 msrs->entry_ctls_low,
3311                 msrs->entry_ctls_high);
3312         msrs->entry_ctls_low =
3313                 VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
3314         msrs->entry_ctls_high &=
3315 #ifdef CONFIG_X86_64
3316                 VM_ENTRY_IA32E_MODE |
3317 #endif
3318                 VM_ENTRY_LOAD_IA32_PAT;
3319         msrs->entry_ctls_high |=
3320                 (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
3321         if (kvm_mpx_supported())
3322                 msrs->entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
3323
3324         /* We support free control of debug control loading. */
3325         msrs->entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
3326
3327         /* cpu-based controls */
3328         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
3329                 msrs->procbased_ctls_low,
3330                 msrs->procbased_ctls_high);
3331         msrs->procbased_ctls_low =
3332                 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3333         msrs->procbased_ctls_high &=
3334                 CPU_BASED_VIRTUAL_INTR_PENDING |
3335                 CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
3336                 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
3337                 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
3338                 CPU_BASED_CR3_STORE_EXITING |
3339 #ifdef CONFIG_X86_64
3340                 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
3341 #endif
3342                 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
3343                 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
3344                 CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
3345                 CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
3346                 CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
3347         /*
3348          * We can allow some features even when not supported by the
3349          * hardware. For example, L1 can specify an MSR bitmap - and we
3350          * can use it to avoid exits to L1 - even when L0 runs L2
3351          * without MSR bitmaps.
3352          */
3353         msrs->procbased_ctls_high |=
3354                 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
3355                 CPU_BASED_USE_MSR_BITMAPS;
3356
3357         /* We support free control of CR3 access interception. */
3358         msrs->procbased_ctls_low &=
3359                 ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
3360
3361         /*
3362          * secondary cpu-based controls.  Do not include those that
3363          * depend on CPUID bits, they are added later by vmx_cpuid_update.
3364          */
3365         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
3366                 msrs->secondary_ctls_low,
3367                 msrs->secondary_ctls_high);
3368         msrs->secondary_ctls_low = 0;
3369         msrs->secondary_ctls_high &=
3370                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
3371                 SECONDARY_EXEC_DESC |
3372                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3373                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3374                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
3375                 SECONDARY_EXEC_WBINVD_EXITING;
3376         /*
3377          * We can emulate "VMCS shadowing," even if the hardware
3378          * doesn't support it.
3379          */
3380         msrs->secondary_ctls_high |=
3381                 SECONDARY_EXEC_SHADOW_VMCS;
3382
3383         if (enable_ept) {
3384                 /* nested EPT: emulate EPT also to L1 */
3385                 msrs->secondary_ctls_high |=
3386                         SECONDARY_EXEC_ENABLE_EPT;
3387                 msrs->ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
3388                          VMX_EPTP_WB_BIT | VMX_EPT_INVEPT_BIT;
3389                 if (cpu_has_vmx_ept_execute_only())
3390                         msrs->ept_caps |=
3391                                 VMX_EPT_EXECUTE_ONLY_BIT;
3392                 msrs->ept_caps &= vmx_capability.ept;
3393                 msrs->ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
3394                         VMX_EPT_EXTENT_CONTEXT_BIT | VMX_EPT_2MB_PAGE_BIT |
3395                         VMX_EPT_1GB_PAGE_BIT;
3396                 if (enable_ept_ad_bits) {
3397                         msrs->secondary_ctls_high |=
3398                                 SECONDARY_EXEC_ENABLE_PML;
3399                         msrs->ept_caps |= VMX_EPT_AD_BIT;
3400                 }
3401         }
3402
3403         if (cpu_has_vmx_vmfunc()) {
3404                 msrs->secondary_ctls_high |=
3405                         SECONDARY_EXEC_ENABLE_VMFUNC;
3406                 /*
3407                  * Advertise EPTP switching unconditionally
3408                  * since we emulate it
3409                  */
3410                 if (enable_ept)
3411                         msrs->vmfunc_controls =
3412                                 VMX_VMFUNC_EPTP_SWITCHING;
3413         }
3414
3415         /*
3416          * Old versions of KVM use the single-context version without
3417          * checking for support, so declare that it is supported even
3418          * though it is treated as global context.  The alternative is
3419          * not failing the single-context invvpid, and it is worse.
3420          */
3421         if (enable_vpid) {
3422                 msrs->secondary_ctls_high |=
3423                         SECONDARY_EXEC_ENABLE_VPID;
3424                 msrs->vpid_caps = VMX_VPID_INVVPID_BIT |
3425                         VMX_VPID_EXTENT_SUPPORTED_MASK;
3426         }
3427
3428         if (enable_unrestricted_guest)
3429                 msrs->secondary_ctls_high |=
3430                         SECONDARY_EXEC_UNRESTRICTED_GUEST;
3431
3432         /* miscellaneous data */
3433         rdmsr(MSR_IA32_VMX_MISC,
3434                 msrs->misc_low,
3435                 msrs->misc_high);
3436         msrs->misc_low &= VMX_MISC_SAVE_EFER_LMA;
3437         msrs->misc_low |=
3438                 MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS |
3439                 VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
3440                 VMX_MISC_ACTIVITY_HLT;
3441         msrs->misc_high = 0;
3442
3443         /*
3444          * This MSR reports some information about VMX support. We
3445          * should return information about the VMX we emulate for the
3446          * guest, and the VMCS structure we give it - not about the
3447          * VMX support of the underlying hardware.
3448          */
3449         msrs->basic =
3450                 VMCS12_REVISION |
3451                 VMX_BASIC_TRUE_CTLS |
3452                 ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
3453                 (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
3454
3455         if (cpu_has_vmx_basic_inout())
3456                 msrs->basic |= VMX_BASIC_INOUT;
3457
3458         /*
3459          * These MSRs specify bits which the guest must keep fixed on
3460          * while L1 is in VMXON mode (in L1's root mode, or running an L2).
3461          * We picked the standard core2 setting.
3462          */
3463 #define VMXON_CR0_ALWAYSON     (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
3464 #define VMXON_CR4_ALWAYSON     X86_CR4_VMXE
3465         msrs->cr0_fixed0 = VMXON_CR0_ALWAYSON;
3466         msrs->cr4_fixed0 = VMXON_CR4_ALWAYSON;
3467
3468         /* These MSRs specify bits which the guest must keep fixed off. */
3469         rdmsrl(MSR_IA32_VMX_CR0_FIXED1, msrs->cr0_fixed1);
3470         rdmsrl(MSR_IA32_VMX_CR4_FIXED1, msrs->cr4_fixed1);
3471
3472         /* highest index: VMX_PREEMPTION_TIMER_VALUE */
3473         msrs->vmcs_enum = VMCS12_MAX_FIELD_INDEX << 1;
3474 }
3475
3476 /*
3477  * if fixed0[i] == 1: val[i] must be 1
3478  * if fixed1[i] == 0: val[i] must be 0
3479  */
3480 static inline bool fixed_bits_valid(u64 val, u64 fixed0, u64 fixed1)
3481 {
3482         return ((val & fixed1) | fixed0) == val;
3483 }
3484
3485 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
3486 {
3487         return fixed_bits_valid(control, low, high);
3488 }
3489
3490 static inline u64 vmx_control_msr(u32 low, u32 high)
3491 {
3492         return low | ((u64)high << 32);
3493 }
3494
3495 static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
3496 {
3497         superset &= mask;
3498         subset &= mask;
3499
3500         return (superset | subset) == superset;
3501 }
3502
3503 static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
3504 {
3505         const u64 feature_and_reserved =
3506                 /* feature (except bit 48; see below) */
3507                 BIT_ULL(49) | BIT_ULL(54) | BIT_ULL(55) |
3508                 /* reserved */
3509                 BIT_ULL(31) | GENMASK_ULL(47, 45) | GENMASK_ULL(63, 56);
3510         u64 vmx_basic = vmx->nested.msrs.basic;
3511
3512         if (!is_bitwise_subset(vmx_basic, data, feature_and_reserved))
3513                 return -EINVAL;
3514
3515         /*
3516          * KVM does not emulate a version of VMX that constrains physical
3517          * addresses of VMX structures (e.g. VMCS) to 32-bits.
3518          */
3519         if (data & BIT_ULL(48))
3520                 return -EINVAL;
3521
3522         if (vmx_basic_vmcs_revision_id(vmx_basic) !=
3523             vmx_basic_vmcs_revision_id(data))
3524                 return -EINVAL;
3525
3526         if (vmx_basic_vmcs_size(vmx_basic) > vmx_basic_vmcs_size(data))
3527                 return -EINVAL;
3528
3529         vmx->nested.msrs.basic = data;
3530         return 0;
3531 }
3532
3533 static int
3534 vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3535 {
3536         u64 supported;
3537         u32 *lowp, *highp;
3538
3539         switch (msr_index) {
3540         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3541                 lowp = &vmx->nested.msrs.pinbased_ctls_low;
3542                 highp = &vmx->nested.msrs.pinbased_ctls_high;
3543                 break;
3544         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3545                 lowp = &vmx->nested.msrs.procbased_ctls_low;
3546                 highp = &vmx->nested.msrs.procbased_ctls_high;
3547                 break;
3548         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3549                 lowp = &vmx->nested.msrs.exit_ctls_low;
3550                 highp = &vmx->nested.msrs.exit_ctls_high;
3551                 break;
3552         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3553                 lowp = &vmx->nested.msrs.entry_ctls_low;
3554                 highp = &vmx->nested.msrs.entry_ctls_high;
3555                 break;
3556         case MSR_IA32_VMX_PROCBASED_CTLS2:
3557                 lowp = &vmx->nested.msrs.secondary_ctls_low;
3558                 highp = &vmx->nested.msrs.secondary_ctls_high;
3559                 break;
3560         default:
3561                 BUG();
3562         }
3563
3564         supported = vmx_control_msr(*lowp, *highp);
3565
3566         /* Check must-be-1 bits are still 1. */
3567         if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0)))
3568                 return -EINVAL;
3569
3570         /* Check must-be-0 bits are still 0. */
3571         if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32)))
3572                 return -EINVAL;
3573
3574         *lowp = data;
3575         *highp = data >> 32;
3576         return 0;
3577 }
3578
3579 static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
3580 {
3581         const u64 feature_and_reserved_bits =
3582                 /* feature */
3583                 BIT_ULL(5) | GENMASK_ULL(8, 6) | BIT_ULL(14) | BIT_ULL(15) |
3584                 BIT_ULL(28) | BIT_ULL(29) | BIT_ULL(30) |
3585                 /* reserved */
3586                 GENMASK_ULL(13, 9) | BIT_ULL(31);
3587         u64 vmx_misc;
3588
3589         vmx_misc = vmx_control_msr(vmx->nested.msrs.misc_low,
3590                                    vmx->nested.msrs.misc_high);
3591
3592         if (!is_bitwise_subset(vmx_misc, data, feature_and_reserved_bits))
3593                 return -EINVAL;
3594
3595         if ((vmx->nested.msrs.pinbased_ctls_high &
3596              PIN_BASED_VMX_PREEMPTION_TIMER) &&
3597             vmx_misc_preemption_timer_rate(data) !=
3598             vmx_misc_preemption_timer_rate(vmx_misc))
3599                 return -EINVAL;
3600
3601         if (vmx_misc_cr3_count(data) > vmx_misc_cr3_count(vmx_misc))
3602                 return -EINVAL;
3603
3604         if (vmx_misc_max_msr(data) > vmx_misc_max_msr(vmx_misc))
3605                 return -EINVAL;
3606
3607         if (vmx_misc_mseg_revid(data) != vmx_misc_mseg_revid(vmx_misc))
3608                 return -EINVAL;
3609
3610         vmx->nested.msrs.misc_low = data;
3611         vmx->nested.msrs.misc_high = data >> 32;
3612
3613         /*
3614          * If L1 has read-only VM-exit information fields, use the
3615          * less permissive vmx_vmwrite_bitmap to specify write
3616          * permissions for the shadow VMCS.
3617          */
3618         if (enable_shadow_vmcs && !nested_cpu_has_vmwrite_any_field(&vmx->vcpu))
3619                 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
3620
3621         return 0;
3622 }
3623
3624 static int vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx *vmx, u64 data)
3625 {
3626         u64 vmx_ept_vpid_cap;
3627
3628         vmx_ept_vpid_cap = vmx_control_msr(vmx->nested.msrs.ept_caps,
3629                                            vmx->nested.msrs.vpid_caps);
3630
3631         /* Every bit is either reserved or a feature bit. */
3632         if (!is_bitwise_subset(vmx_ept_vpid_cap, data, -1ULL))
3633                 return -EINVAL;
3634
3635         vmx->nested.msrs.ept_caps = data;
3636         vmx->nested.msrs.vpid_caps = data >> 32;
3637         return 0;
3638 }
3639
3640 static int vmx_restore_fixed0_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3641 {
3642         u64 *msr;
3643
3644         switch (msr_index) {
3645         case MSR_IA32_VMX_CR0_FIXED0:
3646                 msr = &vmx->nested.msrs.cr0_fixed0;
3647                 break;
3648         case MSR_IA32_VMX_CR4_FIXED0:
3649                 msr = &vmx->nested.msrs.cr4_fixed0;
3650                 break;
3651         default:
3652                 BUG();
3653         }
3654
3655         /*
3656          * 1 bits (which indicates bits which "must-be-1" during VMX operation)
3657          * must be 1 in the restored value.
3658          */
3659         if (!is_bitwise_subset(data, *msr, -1ULL))
3660                 return -EINVAL;
3661
3662         *msr = data;
3663         return 0;
3664 }
3665
3666 /*
3667  * Called when userspace is restoring VMX MSRs.
3668  *
3669  * Returns 0 on success, non-0 otherwise.
3670  */
3671 static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
3672 {
3673         struct vcpu_vmx *vmx = to_vmx(vcpu);
3674
3675         /*
3676          * Don't allow changes to the VMX capability MSRs while the vCPU
3677          * is in VMX operation.
3678          */
3679         if (vmx->nested.vmxon)
3680                 return -EBUSY;
3681
3682         switch (msr_index) {
3683         case MSR_IA32_VMX_BASIC:
3684                 return vmx_restore_vmx_basic(vmx, data);
3685         case MSR_IA32_VMX_PINBASED_CTLS:
3686         case MSR_IA32_VMX_PROCBASED_CTLS:
3687         case MSR_IA32_VMX_EXIT_CTLS:
3688         case MSR_IA32_VMX_ENTRY_CTLS:
3689                 /*
3690                  * The "non-true" VMX capability MSRs are generated from the
3691                  * "true" MSRs, so we do not support restoring them directly.
3692                  *
3693                  * If userspace wants to emulate VMX_BASIC[55]=0, userspace
3694                  * should restore the "true" MSRs with the must-be-1 bits
3695                  * set according to the SDM Vol 3. A.2 "RESERVED CONTROLS AND
3696                  * DEFAULT SETTINGS".
3697                  */
3698                 return -EINVAL;
3699         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3700         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3701         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3702         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3703         case MSR_IA32_VMX_PROCBASED_CTLS2:
3704                 return vmx_restore_control_msr(vmx, msr_index, data);
3705         case MSR_IA32_VMX_MISC:
3706                 return vmx_restore_vmx_misc(vmx, data);
3707         case MSR_IA32_VMX_CR0_FIXED0:
3708         case MSR_IA32_VMX_CR4_FIXED0:
3709                 return vmx_restore_fixed0_msr(vmx, msr_index, data);
3710         case MSR_IA32_VMX_CR0_FIXED1:
3711         case MSR_IA32_VMX_CR4_FIXED1:
3712                 /*
3713                  * These MSRs are generated based on the vCPU's CPUID, so we
3714                  * do not support restoring them directly.
3715                  */
3716                 return -EINVAL;
3717         case MSR_IA32_VMX_EPT_VPID_CAP:
3718                 return vmx_restore_vmx_ept_vpid_cap(vmx, data);
3719         case MSR_IA32_VMX_VMCS_ENUM:
3720                 vmx->nested.msrs.vmcs_enum = data;
3721                 return 0;
3722         default:
3723                 /*
3724                  * The rest of the VMX capability MSRs do not support restore.
3725                  */
3726                 return -EINVAL;
3727         }
3728 }
3729
3730 /* Returns 0 on success, non-0 otherwise. */
3731 static int vmx_get_vmx_msr(struct nested_vmx_msrs *msrs, u32 msr_index, u64 *pdata)
3732 {
3733         switch (msr_index) {
3734         case MSR_IA32_VMX_BASIC:
3735                 *pdata = msrs->basic;
3736                 break;
3737         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3738         case MSR_IA32_VMX_PINBASED_CTLS:
3739                 *pdata = vmx_control_msr(
3740                         msrs->pinbased_ctls_low,
3741                         msrs->pinbased_ctls_high);
3742                 if (msr_index == MSR_IA32_VMX_PINBASED_CTLS)
3743                         *pdata |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3744                 break;
3745         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3746         case MSR_IA32_VMX_PROCBASED_CTLS:
3747                 *pdata = vmx_control_msr(
3748                         msrs->procbased_ctls_low,
3749                         msrs->procbased_ctls_high);
3750                 if (msr_index == MSR_IA32_VMX_PROCBASED_CTLS)
3751                         *pdata |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3752                 break;
3753         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3754         case MSR_IA32_VMX_EXIT_CTLS:
3755                 *pdata = vmx_control_msr(
3756                         msrs->exit_ctls_low,
3757                         msrs->exit_ctls_high);
3758                 if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
3759                         *pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
3760                 break;
3761         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3762         case MSR_IA32_VMX_ENTRY_CTLS:
3763                 *pdata = vmx_control_msr(
3764                         msrs->entry_ctls_low,
3765                         msrs->entry_ctls_high);
3766                 if (msr_index == MSR_IA32_VMX_ENTRY_CTLS)
3767                         *pdata |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
3768                 break;
3769         case MSR_IA32_VMX_MISC:
3770                 *pdata = vmx_control_msr(
3771                         msrs->misc_low,
3772                         msrs->misc_high);
3773                 break;
3774         case MSR_IA32_VMX_CR0_FIXED0:
3775                 *pdata = msrs->cr0_fixed0;
3776                 break;
3777         case MSR_IA32_VMX_CR0_FIXED1:
3778                 *pdata = msrs->cr0_fixed1;
3779                 break;
3780         case MSR_IA32_VMX_CR4_FIXED0:
3781                 *pdata = msrs->cr4_fixed0;
3782                 break;
3783         case MSR_IA32_VMX_CR4_FIXED1:
3784                 *pdata = msrs->cr4_fixed1;
3785                 break;
3786         case MSR_IA32_VMX_VMCS_ENUM:
3787                 *pdata = msrs->vmcs_enum;
3788                 break;
3789         case MSR_IA32_VMX_PROCBASED_CTLS2:
3790                 *pdata = vmx_control_msr(
3791                         msrs->secondary_ctls_low,
3792                         msrs->secondary_ctls_high);
3793                 break;
3794         case MSR_IA32_VMX_EPT_VPID_CAP:
3795                 *pdata = msrs->ept_caps |
3796                         ((u64)msrs->vpid_caps << 32);
3797                 break;
3798         case MSR_IA32_VMX_VMFUNC:
3799                 *pdata = msrs->vmfunc_controls;
3800                 break;
3801         default:
3802                 return 1;
3803         }
3804
3805         return 0;
3806 }
3807
3808 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
3809                                                  uint64_t val)
3810 {
3811         uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
3812
3813         return !(val & ~valid_bits);
3814 }
3815
3816 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
3817 {
3818         switch (msr->index) {
3819         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3820                 if (!nested)
3821                         return 1;
3822                 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
3823         default:
3824                 return 1;
3825         }
3826
3827         return 0;
3828 }
3829
3830 /*
3831  * Reads an msr value (of 'msr_index') into 'pdata'.
3832  * Returns 0 on success, non-0 otherwise.
3833  * Assumes vcpu_load() was already called.
3834  */
3835 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3836 {
3837         struct vcpu_vmx *vmx = to_vmx(vcpu);
3838         struct shared_msr_entry *msr;
3839
3840         switch (msr_info->index) {
3841 #ifdef CONFIG_X86_64
3842         case MSR_FS_BASE:
3843                 msr_info->data = vmcs_readl(GUEST_FS_BASE);
3844                 break;
3845         case MSR_GS_BASE:
3846                 msr_info->data = vmcs_readl(GUEST_GS_BASE);
3847                 break;
3848         case MSR_KERNEL_GS_BASE:
3849                 vmx_load_host_state(vmx);
3850                 msr_info->data = vmx->msr_guest_kernel_gs_base;
3851                 break;
3852 #endif
3853         case MSR_EFER:
3854                 return kvm_get_msr_common(vcpu, msr_info);
3855         case MSR_IA32_SPEC_CTRL:
3856                 if (!msr_info->host_initiated &&
3857                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
3858                         return 1;
3859
3860                 msr_info->data = to_vmx(vcpu)->spec_ctrl;
3861                 break;
3862         case MSR_IA32_ARCH_CAPABILITIES:
3863                 if (!msr_info->host_initiated &&
3864                     !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3865                         return 1;
3866                 msr_info->data = to_vmx(vcpu)->arch_capabilities;
3867                 break;
3868         case MSR_IA32_SYSENTER_CS:
3869                 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
3870                 break;
3871         case MSR_IA32_SYSENTER_EIP:
3872                 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
3873                 break;
3874         case MSR_IA32_SYSENTER_ESP:
3875                 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
3876                 break;
3877         case MSR_IA32_BNDCFGS:
3878                 if (!kvm_mpx_supported() ||
3879                     (!msr_info->host_initiated &&
3880                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
3881                         return 1;
3882                 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
3883                 break;
3884         case MSR_IA32_MCG_EXT_CTL:
3885                 if (!msr_info->host_initiated &&
3886                     !(vmx->msr_ia32_feature_control &
3887                       FEATURE_CONTROL_LMCE))
3888                         return 1;
3889                 msr_info->data = vcpu->arch.mcg_ext_ctl;
3890                 break;
3891         case MSR_IA32_FEATURE_CONTROL:
3892                 msr_info->data = vmx->msr_ia32_feature_control;
3893                 break;
3894         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3895                 if (!nested_vmx_allowed(vcpu))
3896                         return 1;
3897                 return vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
3898                                        &msr_info->data);
3899         case MSR_IA32_XSS:
3900                 if (!vmx_xsaves_supported())
3901                         return 1;
3902                 msr_info->data = vcpu->arch.ia32_xss;
3903                 break;
3904         case MSR_TSC_AUX:
3905                 if (!msr_info->host_initiated &&
3906                     !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
3907                         return 1;
3908                 /* Otherwise falls through */
3909         default:
3910                 msr = find_msr_entry(vmx, msr_info->index);
3911                 if (msr) {
3912                         msr_info->data = msr->data;
3913                         break;
3914                 }
3915                 return kvm_get_msr_common(vcpu, msr_info);
3916         }
3917
3918         return 0;
3919 }
3920
3921 static void vmx_leave_nested(struct kvm_vcpu *vcpu);
3922
3923 /*
3924  * Writes msr value into into the appropriate "register".
3925  * Returns 0 on success, non-0 otherwise.
3926  * Assumes vcpu_load() was already called.
3927  */
3928 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3929 {
3930         struct vcpu_vmx *vmx = to_vmx(vcpu);
3931         struct shared_msr_entry *msr;
3932         int ret = 0;
3933         u32 msr_index = msr_info->index;
3934         u64 data = msr_info->data;
3935
3936         switch (msr_index) {
3937         case MSR_EFER:
3938                 ret = kvm_set_msr_common(vcpu, msr_info);
3939                 break;
3940 #ifdef CONFIG_X86_64
3941         case MSR_FS_BASE:
3942                 vmx_segment_cache_clear(vmx);
3943                 vmcs_writel(GUEST_FS_BASE, data);
3944                 break;
3945         case MSR_GS_BASE:
3946                 vmx_segment_cache_clear(vmx);
3947                 vmcs_writel(GUEST_GS_BASE, data);
3948                 break;
3949         case MSR_KERNEL_GS_BASE:
3950                 vmx_load_host_state(vmx);
3951                 vmx->msr_guest_kernel_gs_base = data;
3952                 break;
3953 #endif
3954         case MSR_IA32_SYSENTER_CS:
3955                 vmcs_write32(GUEST_SYSENTER_CS, data);
3956                 break;
3957         case MSR_IA32_SYSENTER_EIP:
3958                 vmcs_writel(GUEST_SYSENTER_EIP, data);
3959                 break;
3960         case MSR_IA32_SYSENTER_ESP:
3961                 vmcs_writel(GUEST_SYSENTER_ESP, data);
3962                 break;
3963         case MSR_IA32_BNDCFGS:
3964                 if (!kvm_mpx_supported() ||
3965                     (!msr_info->host_initiated &&
3966                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
3967                         return 1;
3968                 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
3969                     (data & MSR_IA32_BNDCFGS_RSVD))
3970                         return 1;
3971                 vmcs_write64(GUEST_BNDCFGS, data);
3972                 break;
3973         case MSR_IA32_SPEC_CTRL:
3974                 if (!msr_info->host_initiated &&
3975                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
3976                         return 1;
3977
3978                 /* The STIBP bit doesn't fault even if it's not advertised */
3979                 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
3980                         return 1;
3981
3982                 vmx->spec_ctrl = data;
3983
3984                 if (!data)
3985                         break;
3986
3987                 /*
3988                  * For non-nested:
3989                  * When it's written (to non-zero) for the first time, pass
3990                  * it through.
3991                  *
3992                  * For nested:
3993                  * The handling of the MSR bitmap for L2 guests is done in
3994                  * nested_vmx_merge_msr_bitmap. We should not touch the
3995                  * vmcs02.msr_bitmap here since it gets completely overwritten
3996                  * in the merging. We update the vmcs01 here for L1 as well
3997                  * since it will end up touching the MSR anyway now.
3998                  */
3999                 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
4000                                               MSR_IA32_SPEC_CTRL,
4001                                               MSR_TYPE_RW);
4002                 break;
4003         case MSR_IA32_PRED_CMD:
4004                 if (!msr_info->host_initiated &&
4005                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
4006                         return 1;
4007
4008                 if (data & ~PRED_CMD_IBPB)
4009                         return 1;
4010
4011                 if (!data)
4012                         break;
4013
4014                 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
4015
4016                 /*
4017                  * For non-nested:
4018                  * When it's written (to non-zero) for the first time, pass
4019                  * it through.
4020                  *
4021                  * For nested:
4022                  * The handling of the MSR bitmap for L2 guests is done in
4023                  * nested_vmx_merge_msr_bitmap. We should not touch the
4024                  * vmcs02.msr_bitmap here since it gets completely overwritten
4025                  * in the merging.
4026                  */
4027                 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
4028                                               MSR_TYPE_W);
4029                 break;
4030         case MSR_IA32_ARCH_CAPABILITIES:
4031                 if (!msr_info->host_initiated)
4032                         return 1;
4033                 vmx->arch_capabilities = data;
4034                 break;
4035         case MSR_IA32_CR_PAT:
4036                 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
4037                         if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
4038                                 return 1;
4039                         vmcs_write64(GUEST_IA32_PAT, data);
4040                         vcpu->arch.pat = data;
4041                         break;
4042                 }
4043                 ret = kvm_set_msr_common(vcpu, msr_info);
4044                 break;
4045         case MSR_IA32_TSC_ADJUST:
4046                 ret = kvm_set_msr_common(vcpu, msr_info);
4047                 break;
4048         case MSR_IA32_MCG_EXT_CTL:
4049                 if ((!msr_info->host_initiated &&
4050                      !(to_vmx(vcpu)->msr_ia32_feature_control &
4051                        FEATURE_CONTROL_LMCE)) ||
4052                     (data & ~MCG_EXT_CTL_LMCE_EN))
4053                         return 1;
4054                 vcpu->arch.mcg_ext_ctl = data;
4055                 break;
4056         case MSR_IA32_FEATURE_CONTROL:
4057                 if (!vmx_feature_control_msr_valid(vcpu, data) ||
4058                     (to_vmx(vcpu)->msr_ia32_feature_control &
4059                      FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
4060                         return 1;
4061                 vmx->msr_ia32_feature_control = data;
4062                 if (msr_info->host_initiated && data == 0)
4063                         vmx_leave_nested(vcpu);
4064                 break;
4065         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4066                 if (!msr_info->host_initiated)
4067                         return 1; /* they are read-only */
4068                 if (!nested_vmx_allowed(vcpu))
4069                         return 1;
4070                 return vmx_set_vmx_msr(vcpu, msr_index, data);
4071         case MSR_IA32_XSS:
4072                 if (!vmx_xsaves_supported())
4073                         return 1;
4074                 /*
4075                  * The only supported bit as of Skylake is bit 8, but
4076                  * it is not supported on KVM.
4077                  */
4078                 if (data != 0)
4079                         return 1;
4080                 vcpu->arch.ia32_xss = data;
4081                 if (vcpu->arch.ia32_xss != host_xss)
4082                         add_atomic_switch_msr(vmx, MSR_IA32_XSS,
4083                                 vcpu->arch.ia32_xss, host_xss);
4084                 else
4085                         clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
4086                 break;
4087         case MSR_TSC_AUX:
4088                 if (!msr_info->host_initiated &&
4089                     !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
4090                         return 1;
4091                 /* Check reserved bit, higher 32 bits should be zero */
4092                 if ((data >> 32) != 0)
4093                         return 1;
4094                 /* Otherwise falls through */
4095         default:
4096                 msr = find_msr_entry(vmx, msr_index);
4097                 if (msr) {
4098                         u64 old_msr_data = msr->data;
4099                         msr->data = data;
4100                         if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
4101                                 preempt_disable();
4102                                 ret = kvm_set_shared_msr(msr->index, msr->data,
4103                                                          msr->mask);
4104                                 preempt_enable();
4105                                 if (ret)
4106                                         msr->data = old_msr_data;
4107                         }
4108                         break;
4109                 }
4110                 ret = kvm_set_msr_common(vcpu, msr_info);
4111         }
4112
4113         return ret;
4114 }
4115
4116 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
4117 {
4118         __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
4119         switch (reg) {
4120         case VCPU_REGS_RSP:
4121                 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
4122                 break;
4123         case VCPU_REGS_RIP:
4124                 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
4125                 break;
4126         case VCPU_EXREG_PDPTR:
4127                 if (enable_ept)
4128                         ept_save_pdptrs(vcpu);
4129                 break;
4130         default:
4131                 break;
4132         }
4133 }
4134
4135 static __init int cpu_has_kvm_support(void)
4136 {
4137         return cpu_has_vmx();
4138 }
4139
4140 static __init int vmx_disabled_by_bios(void)
4141 {
4142         u64 msr;
4143
4144         rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
4145         if (msr & FEATURE_CONTROL_LOCKED) {
4146                 /* launched w/ TXT and VMX disabled */
4147                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
4148                         && tboot_enabled())
4149                         return 1;
4150                 /* launched w/o TXT and VMX only enabled w/ TXT */
4151                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
4152                         && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
4153                         && !tboot_enabled()) {
4154                         printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
4155                                 "activate TXT before enabling KVM\n");
4156                         return 1;
4157                 }
4158                 /* launched w/o TXT and VMX disabled */
4159                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
4160                         && !tboot_enabled())
4161                         return 1;
4162         }
4163
4164         return 0;
4165 }
4166
4167 static void kvm_cpu_vmxon(u64 addr)
4168 {
4169         cr4_set_bits(X86_CR4_VMXE);
4170         intel_pt_handle_vmx(1);
4171
4172         asm volatile (ASM_VMX_VMXON_RAX
4173                         : : "a"(&addr), "m"(addr)
4174                         : "memory", "cc");
4175 }
4176
4177 static int hardware_enable(void)
4178 {
4179         int cpu = raw_smp_processor_id();
4180         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
4181         u64 old, test_bits;
4182
4183         if (cr4_read_shadow() & X86_CR4_VMXE)
4184                 return -EBUSY;
4185
4186         /*
4187          * This can happen if we hot-added a CPU but failed to allocate
4188          * VP assist page for it.
4189          */
4190         if (static_branch_unlikely(&enable_evmcs) &&
4191             !hv_get_vp_assist_page(cpu))
4192                 return -EFAULT;
4193
4194         INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
4195         INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
4196         spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
4197
4198         /*
4199          * Now we can enable the vmclear operation in kdump
4200          * since the loaded_vmcss_on_cpu list on this cpu
4201          * has been initialized.
4202          *
4203          * Though the cpu is not in VMX operation now, there
4204          * is no problem to enable the vmclear operation
4205          * for the loaded_vmcss_on_cpu list is empty!
4206          */
4207         crash_enable_local_vmclear(cpu);
4208
4209         rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
4210
4211         test_bits = FEATURE_CONTROL_LOCKED;
4212         test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
4213         if (tboot_enabled())
4214                 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
4215
4216         if ((old & test_bits) != test_bits) {
4217                 /* enable and lock */
4218                 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
4219         }
4220         kvm_cpu_vmxon(phys_addr);
4221         if (enable_ept)
4222                 ept_sync_global();
4223
4224         return 0;
4225 }
4226
4227 static void vmclear_local_loaded_vmcss(void)
4228 {
4229         int cpu = raw_smp_processor_id();
4230         struct loaded_vmcs *v, *n;
4231
4232         list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
4233                                  loaded_vmcss_on_cpu_link)
4234                 __loaded_vmcs_clear(v);
4235 }
4236
4237
4238 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
4239  * tricks.
4240  */
4241 static void kvm_cpu_vmxoff(void)
4242 {
4243         asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
4244
4245         intel_pt_handle_vmx(0);
4246         cr4_clear_bits(X86_CR4_VMXE);
4247 }
4248
4249 static void hardware_disable(void)
4250 {
4251         vmclear_local_loaded_vmcss();
4252         kvm_cpu_vmxoff();
4253 }
4254
4255 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
4256                                       u32 msr, u32 *result)
4257 {
4258         u32 vmx_msr_low, vmx_msr_high;
4259         u32 ctl = ctl_min | ctl_opt;
4260
4261         rdmsr(msr, vmx_msr_low, vmx_msr_high);
4262
4263         ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
4264         ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
4265
4266         /* Ensure minimum (required) set of control bits are supported. */
4267         if (ctl_min & ~ctl)
4268                 return -EIO;
4269
4270         *result = ctl;
4271         return 0;
4272 }
4273
4274 static __init bool allow_1_setting(u32 msr, u32 ctl)
4275 {
4276         u32 vmx_msr_low, vmx_msr_high;
4277
4278         rdmsr(msr, vmx_msr_low, vmx_msr_high);
4279         return vmx_msr_high & ctl;
4280 }
4281
4282 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
4283 {
4284         u32 vmx_msr_low, vmx_msr_high;
4285         u32 min, opt, min2, opt2;
4286         u32 _pin_based_exec_control = 0;
4287         u32 _cpu_based_exec_control = 0;
4288         u32 _cpu_based_2nd_exec_control = 0;
4289         u32 _vmexit_control = 0;
4290         u32 _vmentry_control = 0;
4291
4292         memset(vmcs_conf, 0, sizeof(*vmcs_conf));
4293         min = CPU_BASED_HLT_EXITING |
4294 #ifdef CONFIG_X86_64
4295               CPU_BASED_CR8_LOAD_EXITING |
4296               CPU_BASED_CR8_STORE_EXITING |
4297 #endif
4298               CPU_BASED_CR3_LOAD_EXITING |
4299               CPU_BASED_CR3_STORE_EXITING |
4300               CPU_BASED_UNCOND_IO_EXITING |
4301               CPU_BASED_MOV_DR_EXITING |
4302               CPU_BASED_USE_TSC_OFFSETING |
4303               CPU_BASED_MWAIT_EXITING |
4304               CPU_BASED_MONITOR_EXITING |
4305               CPU_BASED_INVLPG_EXITING |
4306               CPU_BASED_RDPMC_EXITING;
4307
4308         opt = CPU_BASED_TPR_SHADOW |
4309               CPU_BASED_USE_MSR_BITMAPS |
4310               CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
4311         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
4312                                 &_cpu_based_exec_control) < 0)
4313                 return -EIO;
4314 #ifdef CONFIG_X86_64
4315         if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
4316                 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
4317                                            ~CPU_BASED_CR8_STORE_EXITING;
4318 #endif
4319         if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
4320                 min2 = 0;
4321                 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
4322                         SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
4323                         SECONDARY_EXEC_WBINVD_EXITING |
4324                         SECONDARY_EXEC_ENABLE_VPID |
4325                         SECONDARY_EXEC_ENABLE_EPT |
4326                         SECONDARY_EXEC_UNRESTRICTED_GUEST |
4327                         SECONDARY_EXEC_PAUSE_LOOP_EXITING |
4328                         SECONDARY_EXEC_DESC |
4329                         SECONDARY_EXEC_RDTSCP |
4330                         SECONDARY_EXEC_ENABLE_INVPCID |
4331                         SECONDARY_EXEC_APIC_REGISTER_VIRT |
4332                         SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
4333                         SECONDARY_EXEC_SHADOW_VMCS |
4334                         SECONDARY_EXEC_XSAVES |
4335                         SECONDARY_EXEC_RDSEED_EXITING |
4336                         SECONDARY_EXEC_RDRAND_EXITING |
4337                         SECONDARY_EXEC_ENABLE_PML |
4338                         SECONDARY_EXEC_TSC_SCALING |
4339                         SECONDARY_EXEC_ENABLE_VMFUNC;
4340                 if (adjust_vmx_controls(min2, opt2,
4341                                         MSR_IA32_VMX_PROCBASED_CTLS2,
4342                                         &_cpu_based_2nd_exec_control) < 0)
4343                         return -EIO;
4344         }
4345 #ifndef CONFIG_X86_64
4346         if (!(_cpu_based_2nd_exec_control &
4347                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
4348                 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
4349 #endif
4350
4351         if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
4352                 _cpu_based_2nd_exec_control &= ~(
4353                                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4354                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
4355                                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4356
4357         rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
4358                 &vmx_capability.ept, &vmx_capability.vpid);
4359
4360         if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
4361                 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
4362                    enabled */
4363                 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
4364                                              CPU_BASED_CR3_STORE_EXITING |
4365                                              CPU_BASED_INVLPG_EXITING);
4366         } else if (vmx_capability.ept) {
4367                 vmx_capability.ept = 0;
4368                 pr_warn_once("EPT CAP should not exist if not support "
4369                                 "1-setting enable EPT VM-execution control\n");
4370         }
4371         if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
4372                 vmx_capability.vpid) {
4373                 vmx_capability.vpid = 0;
4374                 pr_warn_once("VPID CAP should not exist if not support "
4375                                 "1-setting enable VPID VM-execution control\n");
4376         }
4377
4378         min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
4379 #ifdef CONFIG_X86_64
4380         min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
4381 #endif
4382         opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
4383                 VM_EXIT_CLEAR_BNDCFGS;
4384         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
4385                                 &_vmexit_control) < 0)
4386                 return -EIO;
4387
4388         min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
4389         opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
4390                  PIN_BASED_VMX_PREEMPTION_TIMER;
4391         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
4392                                 &_pin_based_exec_control) < 0)
4393                 return -EIO;
4394
4395         if (cpu_has_broken_vmx_preemption_timer())
4396                 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4397         if (!(_cpu_based_2nd_exec_control &
4398                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
4399                 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
4400
4401         min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
4402         opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
4403         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
4404                                 &_vmentry_control) < 0)
4405                 return -EIO;
4406
4407         rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
4408
4409         /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
4410         if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
4411                 return -EIO;
4412
4413 #ifdef CONFIG_X86_64
4414         /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
4415         if (vmx_msr_high & (1u<<16))
4416                 return -EIO;
4417 #endif
4418
4419         /* Require Write-Back (WB) memory type for VMCS accesses. */
4420         if (((vmx_msr_high >> 18) & 15) != 6)
4421                 return -EIO;
4422
4423         vmcs_conf->size = vmx_msr_high & 0x1fff;
4424         vmcs_conf->order = get_order(vmcs_conf->size);
4425         vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
4426
4427         vmcs_conf->revision_id = vmx_msr_low;
4428
4429         vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
4430         vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
4431         vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
4432         vmcs_conf->vmexit_ctrl         = _vmexit_control;
4433         vmcs_conf->vmentry_ctrl        = _vmentry_control;
4434
4435         if (static_branch_unlikely(&enable_evmcs))
4436                 evmcs_sanitize_exec_ctrls(vmcs_conf);
4437
4438         cpu_has_load_ia32_efer =
4439                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
4440                                 VM_ENTRY_LOAD_IA32_EFER)
4441                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
4442                                    VM_EXIT_LOAD_IA32_EFER);
4443
4444         cpu_has_load_perf_global_ctrl =
4445                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
4446                                 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
4447                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
4448                                    VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
4449
4450         /*
4451          * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
4452          * but due to errata below it can't be used. Workaround is to use
4453          * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
4454          *
4455          * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
4456          *
4457          * AAK155             (model 26)
4458          * AAP115             (model 30)
4459          * AAT100             (model 37)
4460          * BC86,AAY89,BD102   (model 44)
4461          * BA97               (model 46)
4462          *
4463          */
4464         if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
4465                 switch (boot_cpu_data.x86_model) {
4466                 case 26:
4467                 case 30:
4468                 case 37:
4469                 case 44:
4470                 case 46:
4471                         cpu_has_load_perf_global_ctrl = false;
4472                         printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
4473                                         "does not work properly. Using workaround\n");
4474                         break;
4475                 default:
4476                         break;
4477                 }
4478         }
4479
4480         if (boot_cpu_has(X86_FEATURE_XSAVES))
4481                 rdmsrl(MSR_IA32_XSS, host_xss);
4482
4483         return 0;
4484 }
4485
4486 static struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu)
4487 {
4488         int node = cpu_to_node(cpu);
4489         struct page *pages;
4490         struct vmcs *vmcs;
4491
4492         pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
4493         if (!pages)
4494                 return NULL;
4495         vmcs = page_address(pages);
4496         memset(vmcs, 0, vmcs_config.size);
4497
4498         /* KVM supports Enlightened VMCS v1 only */
4499         if (static_branch_unlikely(&enable_evmcs))
4500                 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
4501         else
4502                 vmcs->hdr.revision_id = vmcs_config.revision_id;
4503
4504         if (shadow)
4505                 vmcs->hdr.shadow_vmcs = 1;
4506         return vmcs;
4507 }
4508
4509 static void free_vmcs(struct vmcs *vmcs)
4510 {
4511         free_pages((unsigned long)vmcs, vmcs_config.order);
4512 }
4513
4514 /*
4515  * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
4516  */
4517 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
4518 {
4519         if (!loaded_vmcs->vmcs)
4520                 return;
4521         loaded_vmcs_clear(loaded_vmcs);
4522         free_vmcs(loaded_vmcs->vmcs);
4523         loaded_vmcs->vmcs = NULL;
4524         if (loaded_vmcs->msr_bitmap)
4525                 free_page((unsigned long)loaded_vmcs->msr_bitmap);
4526         WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
4527 }
4528
4529 static struct vmcs *alloc_vmcs(bool shadow)
4530 {
4531         return alloc_vmcs_cpu(shadow, raw_smp_processor_id());
4532 }
4533
4534 static int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
4535 {
4536         loaded_vmcs->vmcs = alloc_vmcs(false);
4537         if (!loaded_vmcs->vmcs)
4538                 return -ENOMEM;
4539
4540         loaded_vmcs->shadow_vmcs = NULL;
4541         loaded_vmcs_init(loaded_vmcs);
4542
4543         if (cpu_has_vmx_msr_bitmap()) {
4544                 loaded_vmcs->msr_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
4545                 if (!loaded_vmcs->msr_bitmap)
4546                         goto out_vmcs;
4547                 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
4548
4549                 if (IS_ENABLED(CONFIG_HYPERV) &&
4550                     static_branch_unlikely(&enable_evmcs) &&
4551                     (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
4552                         struct hv_enlightened_vmcs *evmcs =
4553                                 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
4554
4555                         evmcs->hv_enlightenments_control.msr_bitmap = 1;
4556                 }
4557         }
4558         return 0;
4559
4560 out_vmcs:
4561         free_loaded_vmcs(loaded_vmcs);
4562         return -ENOMEM;
4563 }
4564
4565 static void free_kvm_area(void)
4566 {
4567         int cpu;
4568
4569         for_each_possible_cpu(cpu) {
4570                 free_vmcs(per_cpu(vmxarea, cpu));
4571                 per_cpu(vmxarea, cpu) = NULL;
4572         }
4573 }
4574
4575 enum vmcs_field_width {
4576         VMCS_FIELD_WIDTH_U16 = 0,
4577         VMCS_FIELD_WIDTH_U64 = 1,
4578         VMCS_FIELD_WIDTH_U32 = 2,
4579         VMCS_FIELD_WIDTH_NATURAL_WIDTH = 3
4580 };
4581
4582 static inline int vmcs_field_width(unsigned long field)
4583 {
4584         if (0x1 & field)        /* the *_HIGH fields are all 32 bit */
4585                 return VMCS_FIELD_WIDTH_U32;
4586         return (field >> 13) & 0x3 ;
4587 }
4588
4589 static inline int vmcs_field_readonly(unsigned long field)
4590 {
4591         return (((field >> 10) & 0x3) == 1);
4592 }
4593
4594 static void init_vmcs_shadow_fields(void)
4595 {
4596         int i, j;
4597
4598         for (i = j = 0; i < max_shadow_read_only_fields; i++) {
4599                 u16 field = shadow_read_only_fields[i];
4600                 if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
4601                     (i + 1 == max_shadow_read_only_fields ||
4602                      shadow_read_only_fields[i + 1] != field + 1))
4603                         pr_err("Missing field from shadow_read_only_field %x\n",
4604                                field + 1);
4605
4606                 clear_bit(field, vmx_vmread_bitmap);
4607 #ifdef CONFIG_X86_64
4608                 if (field & 1)
4609                         continue;
4610 #endif
4611                 if (j < i)
4612                         shadow_read_only_fields[j] = field;
4613                 j++;
4614         }
4615         max_shadow_read_only_fields = j;
4616
4617         for (i = j = 0; i < max_shadow_read_write_fields; i++) {
4618                 u16 field = shadow_read_write_fields[i];
4619                 if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
4620                     (i + 1 == max_shadow_read_write_fields ||
4621                      shadow_read_write_fields[i + 1] != field + 1))
4622                         pr_err("Missing field from shadow_read_write_field %x\n",
4623                                field + 1);
4624
4625                 /*
4626                  * PML and the preemption timer can be emulated, but the
4627                  * processor cannot vmwrite to fields that don't exist
4628                  * on bare metal.
4629                  */
4630                 switch (field) {
4631                 case GUEST_PML_INDEX:
4632                         if (!cpu_has_vmx_pml())
4633                                 continue;
4634                         break;
4635                 case VMX_PREEMPTION_TIMER_VALUE:
4636                         if (!cpu_has_vmx_preemption_timer())
4637                                 continue;
4638                         break;
4639                 case GUEST_INTR_STATUS:
4640                         if (!cpu_has_vmx_apicv())
4641                                 continue;
4642                         break;
4643                 default:
4644                         break;
4645                 }
4646
4647                 clear_bit(field, vmx_vmwrite_bitmap);
4648                 clear_bit(field, vmx_vmread_bitmap);
4649 #ifdef CONFIG_X86_64
4650                 if (field & 1)
4651                         continue;
4652 #endif
4653                 if (j < i)
4654                         shadow_read_write_fields[j] = field;
4655                 j++;
4656         }
4657         max_shadow_read_write_fields = j;
4658 }
4659
4660 static __init int alloc_kvm_area(void)
4661 {
4662         int cpu;
4663
4664         for_each_possible_cpu(cpu) {
4665                 struct vmcs *vmcs;
4666
4667                 vmcs = alloc_vmcs_cpu(false, cpu);
4668                 if (!vmcs) {
4669                         free_kvm_area();
4670                         return -ENOMEM;
4671                 }
4672
4673                 /*
4674                  * When eVMCS is enabled, alloc_vmcs_cpu() sets
4675                  * vmcs->revision_id to KVM_EVMCS_VERSION instead of
4676                  * revision_id reported by MSR_IA32_VMX_BASIC.
4677                  *
4678                  * However, even though not explictly documented by
4679                  * TLFS, VMXArea passed as VMXON argument should
4680                  * still be marked with revision_id reported by
4681                  * physical CPU.
4682                  */
4683                 if (static_branch_unlikely(&enable_evmcs))
4684                         vmcs->hdr.revision_id = vmcs_config.revision_id;
4685
4686                 per_cpu(vmxarea, cpu) = vmcs;
4687         }
4688         return 0;
4689 }
4690
4691 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
4692                 struct kvm_segment *save)
4693 {
4694         if (!emulate_invalid_guest_state) {
4695                 /*
4696                  * CS and SS RPL should be equal during guest entry according
4697                  * to VMX spec, but in reality it is not always so. Since vcpu
4698                  * is in the middle of the transition from real mode to
4699                  * protected mode it is safe to assume that RPL 0 is a good
4700                  * default value.
4701                  */
4702                 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
4703                         save->selector &= ~SEGMENT_RPL_MASK;
4704                 save->dpl = save->selector & SEGMENT_RPL_MASK;
4705                 save->s = 1;
4706         }
4707         vmx_set_segment(vcpu, save, seg);
4708 }
4709
4710 static void enter_pmode(struct kvm_vcpu *vcpu)
4711 {
4712         unsigned long flags;
4713         struct vcpu_vmx *vmx = to_vmx(vcpu);
4714
4715         /*
4716          * Update real mode segment cache. It may be not up-to-date if sement
4717          * register was written while vcpu was in a guest mode.
4718          */
4719         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4720         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4721         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4722         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4723         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4724         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4725
4726         vmx->rmode.vm86_active = 0;
4727
4728         vmx_segment_cache_clear(vmx);
4729
4730         vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4731
4732         flags = vmcs_readl(GUEST_RFLAGS);
4733         flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
4734         flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
4735         vmcs_writel(GUEST_RFLAGS, flags);
4736
4737         vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
4738                         (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
4739
4740         update_exception_bitmap(vcpu);
4741
4742         fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4743         fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4744         fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4745         fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4746         fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4747         fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4748 }
4749
4750 static void fix_rmode_seg(int seg, struct kvm_segment *save)
4751 {
4752         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4753         struct kvm_segment var = *save;
4754
4755         var.dpl = 0x3;
4756         if (seg == VCPU_SREG_CS)
4757                 var.type = 0x3;
4758
4759         if (!emulate_invalid_guest_state) {
4760                 var.selector = var.base >> 4;
4761                 var.base = var.base & 0xffff0;
4762                 var.limit = 0xffff;
4763                 var.g = 0;
4764                 var.db = 0;
4765                 var.present = 1;
4766                 var.s = 1;
4767                 var.l = 0;
4768                 var.unusable = 0;
4769                 var.type = 0x3;
4770                 var.avl = 0;
4771                 if (save->base & 0xf)
4772                         printk_once(KERN_WARNING "kvm: segment base is not "
4773                                         "paragraph aligned when entering "
4774                                         "protected mode (seg=%d)", seg);
4775         }
4776
4777         vmcs_write16(sf->selector, var.selector);
4778         vmcs_writel(sf->base, var.base);
4779         vmcs_write32(sf->limit, var.limit);
4780         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
4781 }
4782
4783 static void enter_rmode(struct kvm_vcpu *vcpu)
4784 {
4785         unsigned long flags;
4786         struct vcpu_vmx *vmx = to_vmx(vcpu);
4787         struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
4788
4789         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4790         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4791         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4792         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4793         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4794         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4795         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4796
4797         vmx->rmode.vm86_active = 1;
4798
4799         /*
4800          * Very old userspace does not call KVM_SET_TSS_ADDR before entering
4801          * vcpu. Warn the user that an update is overdue.
4802          */
4803         if (!kvm_vmx->tss_addr)
4804                 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
4805                              "called before entering vcpu\n");
4806
4807         vmx_segment_cache_clear(vmx);
4808
4809         vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
4810         vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
4811         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4812
4813         flags = vmcs_readl(GUEST_RFLAGS);
4814         vmx->rmode.save_rflags = flags;
4815
4816         flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
4817
4818         vmcs_writel(GUEST_RFLAGS, flags);
4819         vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
4820         update_exception_bitmap(vcpu);
4821
4822         fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4823         fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4824         fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4825         fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4826         fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4827         fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4828
4829         kvm_mmu_reset_context(vcpu);
4830 }
4831
4832 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
4833 {
4834         struct vcpu_vmx *vmx = to_vmx(vcpu);
4835         struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
4836
4837         if (!msr)
4838                 return;
4839
4840         /*
4841          * Force kernel_gs_base reloading before EFER changes, as control
4842          * of this msr depends on is_long_mode().
4843          */
4844         vmx_load_host_state(to_vmx(vcpu));
4845         vcpu->arch.efer = efer;
4846         if (efer & EFER_LMA) {
4847                 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4848                 msr->data = efer;
4849         } else {
4850                 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4851
4852                 msr->data = efer & ~EFER_LME;
4853         }
4854         setup_msrs(vmx);
4855 }
4856
4857 #ifdef CONFIG_X86_64
4858
4859 static void enter_lmode(struct kvm_vcpu *vcpu)
4860 {
4861         u32 guest_tr_ar;
4862
4863         vmx_segment_cache_clear(to_vmx(vcpu));
4864
4865         guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
4866         if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
4867                 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
4868                                      __func__);
4869                 vmcs_write32(GUEST_TR_AR_BYTES,
4870                              (guest_tr_ar & ~VMX_AR_TYPE_MASK)
4871                              | VMX_AR_TYPE_BUSY_64_TSS);
4872         }
4873         vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
4874 }
4875
4876 static void exit_lmode(struct kvm_vcpu *vcpu)
4877 {
4878         vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4879         vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
4880 }
4881
4882 #endif
4883
4884 static inline void __vmx_flush_tlb(struct kvm_vcpu *vcpu, int vpid,
4885                                 bool invalidate_gpa)
4886 {
4887         if (enable_ept && (invalidate_gpa || !enable_vpid)) {
4888                 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
4889                         return;
4890                 ept_sync_context(construct_eptp(vcpu, vcpu->arch.mmu.root_hpa));
4891         } else {
4892                 vpid_sync_context(vpid);
4893         }
4894 }
4895
4896 static void vmx_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
4897 {
4898         __vmx_flush_tlb(vcpu, to_vmx(vcpu)->vpid, invalidate_gpa);
4899 }
4900
4901 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
4902 {
4903         int vpid = to_vmx(vcpu)->vpid;
4904
4905         if (!vpid_sync_vcpu_addr(vpid, addr))
4906                 vpid_sync_context(vpid);
4907
4908         /*
4909          * If VPIDs are not supported or enabled, then the above is a no-op.
4910          * But we don't really need a TLB flush in that case anyway, because
4911          * each VM entry/exit includes an implicit flush when VPID is 0.
4912          */
4913 }
4914
4915 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
4916 {
4917         ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
4918
4919         vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
4920         vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
4921 }
4922
4923 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
4924 {
4925         if (enable_unrestricted_guest || (enable_ept && is_paging(vcpu)))
4926                 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
4927         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
4928 }
4929
4930 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
4931 {
4932         ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
4933
4934         vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
4935         vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
4936 }
4937
4938 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
4939 {
4940         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4941
4942         if (!test_bit(VCPU_EXREG_PDPTR,
4943                       (unsigned long *)&vcpu->arch.regs_dirty))
4944                 return;
4945
4946         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
4947                 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
4948                 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
4949                 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
4950                 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
4951         }
4952 }
4953
4954 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
4955 {
4956         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4957
4958         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
4959                 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
4960                 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
4961                 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
4962                 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
4963         }
4964
4965         __set_bit(VCPU_EXREG_PDPTR,
4966                   (unsigned long *)&vcpu->arch.regs_avail);
4967         __set_bit(VCPU_EXREG_PDPTR,
4968                   (unsigned long *)&vcpu->arch.regs_dirty);
4969 }
4970
4971 static bool nested_guest_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
4972 {
4973         u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr0_fixed0;
4974         u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr0_fixed1;
4975         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4976
4977         if (to_vmx(vcpu)->nested.msrs.secondary_ctls_high &
4978                 SECONDARY_EXEC_UNRESTRICTED_GUEST &&
4979             nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
4980                 fixed0 &= ~(X86_CR0_PE | X86_CR0_PG);
4981
4982         return fixed_bits_valid(val, fixed0, fixed1);
4983 }
4984
4985 static bool nested_host_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
4986 {
4987         u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr0_fixed0;
4988         u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr0_fixed1;
4989
4990         return fixed_bits_valid(val, fixed0, fixed1);
4991 }
4992
4993 static bool nested_cr4_valid(struct kvm_vcpu *vcpu, unsigned long val)
4994 {
4995         u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr4_fixed0;
4996         u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr4_fixed1;
4997
4998         return fixed_bits_valid(val, fixed0, fixed1);
4999 }
5000
5001 /* No difference in the restrictions on guest and host CR4 in VMX operation. */
5002 #define nested_guest_cr4_valid  nested_cr4_valid
5003 #define nested_host_cr4_valid   nested_cr4_valid
5004
5005 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
5006
5007 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
5008                                         unsigned long cr0,
5009                                         struct kvm_vcpu *vcpu)
5010 {
5011         if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
5012                 vmx_decache_cr3(vcpu);
5013         if (!(cr0 & X86_CR0_PG)) {
5014                 /* From paging/starting to nonpaging */
5015                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
5016                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
5017                              (CPU_BASED_CR3_LOAD_EXITING |
5018                               CPU_BASED_CR3_STORE_EXITING));
5019                 vcpu->arch.cr0 = cr0;
5020                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
5021         } else if (!is_paging(vcpu)) {
5022                 /* From nonpaging to paging */
5023                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
5024                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
5025                              ~(CPU_BASED_CR3_LOAD_EXITING |
5026                                CPU_BASED_CR3_STORE_EXITING));
5027                 vcpu->arch.cr0 = cr0;
5028                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
5029         }
5030
5031         if (!(cr0 & X86_CR0_WP))
5032                 *hw_cr0 &= ~X86_CR0_WP;
5033 }
5034
5035 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
5036 {
5037         struct vcpu_vmx *vmx = to_vmx(vcpu);
5038         unsigned long hw_cr0;
5039
5040         hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
5041         if (enable_unrestricted_guest)
5042                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
5043         else {
5044                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
5045
5046                 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
5047                         enter_pmode(vcpu);
5048
5049                 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
5050                         enter_rmode(vcpu);
5051         }
5052
5053 #ifdef CONFIG_X86_64
5054         if (vcpu->arch.efer & EFER_LME) {
5055                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
5056                         enter_lmode(vcpu);
5057                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
5058                         exit_lmode(vcpu);
5059         }
5060 #endif
5061
5062         if (enable_ept && !enable_unrestricted_guest)
5063                 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
5064
5065         vmcs_writel(CR0_READ_SHADOW, cr0);
5066         vmcs_writel(GUEST_CR0, hw_cr0);
5067         vcpu->arch.cr0 = cr0;
5068
5069         /* depends on vcpu->arch.cr0 to be set to a new value */
5070         vmx->emulation_required = emulation_required(vcpu);
5071 }
5072
5073 static int get_ept_level(struct kvm_vcpu *vcpu)
5074 {
5075         if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
5076                 return 5;
5077         return 4;
5078 }
5079
5080 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
5081 {
5082         u64 eptp = VMX_EPTP_MT_WB;
5083
5084         eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
5085
5086         if (enable_ept_ad_bits &&
5087             (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
5088                 eptp |= VMX_EPTP_AD_ENABLE_BIT;
5089         eptp |= (root_hpa & PAGE_MASK);
5090
5091         return eptp;
5092 }
5093
5094 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
5095 {
5096         struct kvm *kvm = vcpu->kvm;
5097         unsigned long guest_cr3;
5098         u64 eptp;
5099
5100         guest_cr3 = cr3;
5101         if (enable_ept) {
5102                 eptp = construct_eptp(vcpu, cr3);
5103                 vmcs_write64(EPT_POINTER, eptp);
5104
5105                 if (kvm_x86_ops->tlb_remote_flush) {
5106                         spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
5107                         to_vmx(vcpu)->ept_pointer = eptp;
5108                         to_kvm_vmx(kvm)->ept_pointers_match
5109                                 = EPT_POINTERS_CHECK;
5110                         spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
5111                 }
5112
5113                 if (enable_unrestricted_guest || is_paging(vcpu) ||
5114                     is_guest_mode(vcpu))
5115                         guest_cr3 = kvm_read_cr3(vcpu);
5116                 else
5117                         guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
5118                 ept_load_pdptrs(vcpu);
5119         }
5120
5121         vmcs_writel(GUEST_CR3, guest_cr3);
5122 }
5123
5124 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
5125 {
5126         /*
5127          * Pass through host's Machine Check Enable value to hw_cr4, which
5128          * is in force while we are in guest mode.  Do not let guests control
5129          * this bit, even if host CR4.MCE == 0.
5130          */
5131         unsigned long hw_cr4;
5132
5133         hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
5134         if (enable_unrestricted_guest)
5135                 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
5136         else if (to_vmx(vcpu)->rmode.vm86_active)
5137                 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
5138         else
5139                 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
5140
5141         if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
5142                 if (cr4 & X86_CR4_UMIP) {
5143                         vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
5144                                 SECONDARY_EXEC_DESC);
5145                         hw_cr4 &= ~X86_CR4_UMIP;
5146                 } else if (!is_guest_mode(vcpu) ||
5147                         !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC))
5148                         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
5149                                         SECONDARY_EXEC_DESC);
5150         }
5151
5152         if (cr4 & X86_CR4_VMXE) {
5153                 /*
5154                  * To use VMXON (and later other VMX instructions), a guest
5155                  * must first be able to turn on cr4.VMXE (see handle_vmon()).
5156                  * So basically the check on whether to allow nested VMX
5157                  * is here.
5158                  */
5159                 if (!nested_vmx_allowed(vcpu))
5160                         return 1;
5161         }
5162
5163         if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
5164                 return 1;
5165
5166         vcpu->arch.cr4 = cr4;
5167
5168         if (!enable_unrestricted_guest) {
5169                 if (enable_ept) {
5170                         if (!is_paging(vcpu)) {
5171                                 hw_cr4 &= ~X86_CR4_PAE;
5172                                 hw_cr4 |= X86_CR4_PSE;
5173                         } else if (!(cr4 & X86_CR4_PAE)) {
5174                                 hw_cr4 &= ~X86_CR4_PAE;
5175                         }
5176                 }
5177
5178                 /*
5179                  * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
5180                  * hardware.  To emulate this behavior, SMEP/SMAP/PKU needs
5181                  * to be manually disabled when guest switches to non-paging
5182                  * mode.
5183                  *
5184                  * If !enable_unrestricted_guest, the CPU is always running
5185                  * with CR0.PG=1 and CR4 needs to be modified.
5186                  * If enable_unrestricted_guest, the CPU automatically
5187                  * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
5188                  */
5189                 if (!is_paging(vcpu))
5190                         hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
5191         }
5192
5193         vmcs_writel(CR4_READ_SHADOW, cr4);
5194         vmcs_writel(GUEST_CR4, hw_cr4);
5195         return 0;
5196 }
5197
5198 static void vmx_get_segment(struct kvm_vcpu *vcpu,
5199                             struct kvm_segment *var, int seg)
5200 {
5201         struct vcpu_vmx *vmx = to_vmx(vcpu);
5202         u32 ar;
5203
5204         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
5205                 *var = vmx->rmode.segs[seg];
5206                 if (seg == VCPU_SREG_TR
5207                     || var->selector == vmx_read_guest_seg_selector(vmx, seg))
5208                         return;
5209                 var->base = vmx_read_guest_seg_base(vmx, seg);
5210                 var->selector = vmx_read_guest_seg_selector(vmx, seg);
5211                 return;
5212         }
5213         var->base = vmx_read_guest_seg_base(vmx, seg);
5214         var->limit = vmx_read_guest_seg_limit(vmx, seg);
5215         var->selector = vmx_read_guest_seg_selector(vmx, seg);
5216         ar = vmx_read_guest_seg_ar(vmx, seg);
5217         var->unusable = (ar >> 16) & 1;
5218         var->type = ar & 15;
5219         var->s = (ar >> 4) & 1;
5220         var->dpl = (ar >> 5) & 3;
5221         /*
5222          * Some userspaces do not preserve unusable property. Since usable
5223          * segment has to be present according to VMX spec we can use present
5224          * property to amend userspace bug by making unusable segment always
5225          * nonpresent. vmx_segment_access_rights() already marks nonpresent
5226          * segment as unusable.
5227          */
5228         var->present = !var->unusable;
5229         var->avl = (ar >> 12) & 1;
5230         var->l = (ar >> 13) & 1;
5231         var->db = (ar >> 14) & 1;
5232         var->g = (ar >> 15) & 1;
5233 }
5234
5235 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
5236 {
5237         struct kvm_segment s;
5238
5239         if (to_vmx(vcpu)->rmode.vm86_active) {
5240                 vmx_get_segment(vcpu, &s, seg);
5241                 return s.base;
5242         }
5243         return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
5244 }
5245
5246 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
5247 {
5248         struct vcpu_vmx *vmx = to_vmx(vcpu);
5249
5250         if (unlikely(vmx->rmode.vm86_active))
5251                 return 0;
5252         else {
5253                 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
5254                 return VMX_AR_DPL(ar);
5255         }
5256 }
5257
5258 static u32 vmx_segment_access_rights(struct kvm_segment *var)
5259 {
5260         u32 ar;
5261
5262         if (var->unusable || !var->present)
5263                 ar = 1 << 16;
5264         else {
5265                 ar = var->type & 15;
5266                 ar |= (var->s & 1) << 4;
5267                 ar |= (var->dpl & 3) << 5;
5268                 ar |= (var->present & 1) << 7;
5269                 ar |= (var->avl & 1) << 12;
5270                 ar |= (var->l & 1) << 13;
5271                 ar |= (var->db & 1) << 14;
5272                 ar |= (var->g & 1) << 15;
5273         }
5274
5275         return ar;
5276 }
5277
5278 static void vmx_set_segment(struct kvm_vcpu *vcpu,
5279                             struct kvm_segment *var, int seg)
5280 {
5281         struct vcpu_vmx *vmx = to_vmx(vcpu);
5282         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
5283
5284         vmx_segment_cache_clear(vmx);
5285
5286         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
5287                 vmx->rmode.segs[seg] = *var;
5288                 if (seg == VCPU_SREG_TR)
5289                         vmcs_write16(sf->selector, var->selector);
5290                 else if (var->s)
5291                         fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
5292                 goto out;
5293         }
5294
5295         vmcs_writel(sf->base, var->base);
5296         vmcs_write32(sf->limit, var->limit);
5297         vmcs_write16(sf->selector, var->selector);
5298
5299         /*
5300          *   Fix the "Accessed" bit in AR field of segment registers for older
5301          * qemu binaries.
5302          *   IA32 arch specifies that at the time of processor reset the
5303          * "Accessed" bit in the AR field of segment registers is 1. And qemu
5304          * is setting it to 0 in the userland code. This causes invalid guest
5305          * state vmexit when "unrestricted guest" mode is turned on.
5306          *    Fix for this setup issue in cpu_reset is being pushed in the qemu
5307          * tree. Newer qemu binaries with that qemu fix would not need this
5308          * kvm hack.
5309          */
5310         if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
5311                 var->type |= 0x1; /* Accessed */
5312
5313         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
5314
5315 out:
5316         vmx->emulation_required = emulation_required(vcpu);
5317 }
5318
5319 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
5320 {
5321         u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
5322
5323         *db = (ar >> 14) & 1;
5324         *l = (ar >> 13) & 1;
5325 }
5326
5327 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5328 {
5329         dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
5330         dt->address = vmcs_readl(GUEST_IDTR_BASE);
5331 }
5332
5333 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5334 {
5335         vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
5336         vmcs_writel(GUEST_IDTR_BASE, dt->address);
5337 }
5338
5339 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5340 {
5341         dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
5342         dt->address = vmcs_readl(GUEST_GDTR_BASE);
5343 }
5344
5345 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5346 {
5347         vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
5348         vmcs_writel(GUEST_GDTR_BASE, dt->address);
5349 }
5350
5351 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
5352 {
5353         struct kvm_segment var;
5354         u32 ar;
5355
5356         vmx_get_segment(vcpu, &var, seg);
5357         var.dpl = 0x3;
5358         if (seg == VCPU_SREG_CS)
5359                 var.type = 0x3;
5360         ar = vmx_segment_access_rights(&var);
5361
5362         if (var.base != (var.selector << 4))
5363                 return false;
5364         if (var.limit != 0xffff)
5365                 return false;
5366         if (ar != 0xf3)
5367                 return false;
5368
5369         return true;
5370 }
5371
5372 static bool code_segment_valid(struct kvm_vcpu *vcpu)
5373 {
5374         struct kvm_segment cs;
5375         unsigned int cs_rpl;
5376
5377         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5378         cs_rpl = cs.selector & SEGMENT_RPL_MASK;
5379
5380         if (cs.unusable)
5381                 return false;
5382         if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
5383                 return false;
5384         if (!cs.s)
5385                 return false;
5386         if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
5387                 if (cs.dpl > cs_rpl)
5388                         return false;
5389         } else {
5390                 if (cs.dpl != cs_rpl)
5391                         return false;
5392         }
5393         if (!cs.present)
5394                 return false;
5395
5396         /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
5397         return true;
5398 }
5399
5400 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
5401 {
5402         struct kvm_segment ss;
5403         unsigned int ss_rpl;
5404
5405         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
5406         ss_rpl = ss.selector & SEGMENT_RPL_MASK;
5407
5408         if (ss.unusable)
5409                 return true;
5410         if (ss.type != 3 && ss.type != 7)
5411                 return false;
5412         if (!ss.s)
5413                 return false;
5414         if (ss.dpl != ss_rpl) /* DPL != RPL */
5415                 return false;
5416         if (!ss.present)
5417                 return false;
5418
5419         return true;
5420 }
5421
5422 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
5423 {
5424         struct kvm_segment var;
5425         unsigned int rpl;
5426
5427         vmx_get_segment(vcpu, &var, seg);
5428         rpl = var.selector & SEGMENT_RPL_MASK;
5429
5430         if (var.unusable)
5431                 return true;
5432         if (!var.s)
5433                 return false;
5434         if (!var.present)
5435                 return false;
5436         if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
5437                 if (var.dpl < rpl) /* DPL < RPL */
5438                         return false;
5439         }
5440
5441         /* TODO: Add other members to kvm_segment_field to allow checking for other access
5442          * rights flags
5443          */
5444         return true;
5445 }
5446
5447 static bool tr_valid(struct kvm_vcpu *vcpu)
5448 {
5449         struct kvm_segment tr;
5450
5451         vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
5452
5453         if (tr.unusable)
5454                 return false;
5455         if (tr.selector & SEGMENT_TI_MASK)      /* TI = 1 */
5456                 return false;
5457         if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
5458                 return false;
5459         if (!tr.present)
5460                 return false;
5461
5462         return true;
5463 }
5464
5465 static bool ldtr_valid(struct kvm_vcpu *vcpu)
5466 {
5467         struct kvm_segment ldtr;
5468
5469         vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
5470
5471         if (ldtr.unusable)
5472                 return true;
5473         if (ldtr.selector & SEGMENT_TI_MASK)    /* TI = 1 */
5474                 return false;
5475         if (ldtr.type != 2)
5476                 return false;
5477         if (!ldtr.present)
5478                 return false;
5479
5480         return true;
5481 }
5482
5483 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
5484 {
5485         struct kvm_segment cs, ss;
5486
5487         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5488         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
5489
5490         return ((cs.selector & SEGMENT_RPL_MASK) ==
5491                  (ss.selector & SEGMENT_RPL_MASK));
5492 }
5493
5494 /*
5495  * Check if guest state is valid. Returns true if valid, false if
5496  * not.
5497  * We assume that registers are always usable
5498  */
5499 static bool guest_state_valid(struct kvm_vcpu *vcpu)
5500 {
5501         if (enable_unrestricted_guest)
5502                 return true;
5503
5504         /* real mode guest state checks */
5505         if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
5506                 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
5507                         return false;
5508                 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
5509                         return false;
5510                 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
5511                         return false;
5512                 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
5513                         return false;
5514                 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
5515                         return false;
5516                 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
5517                         return false;
5518         } else {
5519         /* protected mode guest state checks */
5520                 if (!cs_ss_rpl_check(vcpu))
5521                         return false;
5522                 if (!code_segment_valid(vcpu))
5523                         return false;
5524                 if (!stack_segment_valid(vcpu))
5525                         return false;
5526                 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
5527                         return false;
5528                 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
5529                         return false;
5530                 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
5531                         return false;
5532                 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
5533                         return false;
5534                 if (!tr_valid(vcpu))
5535                         return false;
5536                 if (!ldtr_valid(vcpu))
5537                         return false;
5538         }
5539         /* TODO:
5540          * - Add checks on RIP
5541          * - Add checks on RFLAGS
5542          */
5543
5544         return true;
5545 }
5546
5547 static bool page_address_valid(struct kvm_vcpu *vcpu, gpa_t gpa)
5548 {
5549         return PAGE_ALIGNED(gpa) && !(gpa >> cpuid_maxphyaddr(vcpu));
5550 }
5551
5552 static int init_rmode_tss(struct kvm *kvm)
5553 {
5554         gfn_t fn;
5555         u16 data = 0;
5556         int idx, r;
5557
5558         idx = srcu_read_lock(&kvm->srcu);
5559         fn = to_kvm_vmx(kvm)->tss_addr >> PAGE_SHIFT;
5560         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
5561         if (r < 0)
5562                 goto out;
5563         data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
5564         r = kvm_write_guest_page(kvm, fn++, &data,
5565                         TSS_IOPB_BASE_OFFSET, sizeof(u16));
5566         if (r < 0)
5567                 goto out;
5568         r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
5569         if (r < 0)
5570                 goto out;
5571         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
5572         if (r < 0)
5573                 goto out;
5574         data = ~0;
5575         r = kvm_write_guest_page(kvm, fn, &data,
5576                                  RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
5577                                  sizeof(u8));
5578 out:
5579         srcu_read_unlock(&kvm->srcu, idx);
5580         return r;
5581 }
5582
5583 static int init_rmode_identity_map(struct kvm *kvm)
5584 {
5585         struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
5586         int i, idx, r = 0;
5587         kvm_pfn_t identity_map_pfn;
5588         u32 tmp;
5589
5590         /* Protect kvm_vmx->ept_identity_pagetable_done. */
5591         mutex_lock(&kvm->slots_lock);
5592
5593         if (likely(kvm_vmx->ept_identity_pagetable_done))
5594                 goto out2;
5595
5596         if (!kvm_vmx->ept_identity_map_addr)
5597                 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
5598         identity_map_pfn = kvm_vmx->ept_identity_map_addr >> PAGE_SHIFT;
5599
5600         r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
5601                                     kvm_vmx->ept_identity_map_addr, PAGE_SIZE);
5602         if (r < 0)
5603                 goto out2;
5604
5605         idx = srcu_read_lock(&kvm->srcu);
5606         r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
5607         if (r < 0)
5608                 goto out;
5609         /* Set up identity-mapping pagetable for EPT in real mode */
5610         for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
5611                 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
5612                         _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
5613                 r = kvm_write_guest_page(kvm, identity_map_pfn,
5614                                 &tmp, i * sizeof(tmp), sizeof(tmp));
5615                 if (r < 0)
5616                         goto out;
5617         }
5618         kvm_vmx->ept_identity_pagetable_done = true;
5619
5620 out:
5621         srcu_read_unlock(&kvm->srcu, idx);
5622
5623 out2:
5624         mutex_unlock(&kvm->slots_lock);
5625         return r;
5626 }
5627
5628 static void seg_setup(int seg)
5629 {
5630         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
5631         unsigned int ar;
5632
5633         vmcs_write16(sf->selector, 0);
5634         vmcs_writel(sf->base, 0);
5635         vmcs_write32(sf->limit, 0xffff);
5636         ar = 0x93;
5637         if (seg == VCPU_SREG_CS)
5638                 ar |= 0x08; /* code segment */
5639
5640         vmcs_write32(sf->ar_bytes, ar);
5641 }
5642
5643 static int alloc_apic_access_page(struct kvm *kvm)
5644 {
5645         struct page *page;
5646         int r = 0;
5647
5648         mutex_lock(&kvm->slots_lock);
5649         if (kvm->arch.apic_access_page_done)
5650                 goto out;
5651         r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
5652                                     APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
5653         if (r)
5654                 goto out;
5655
5656         page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
5657         if (is_error_page(page)) {
5658                 r = -EFAULT;
5659                 goto out;
5660         }
5661
5662         /*
5663          * Do not pin the page in memory, so that memory hot-unplug
5664          * is able to migrate it.
5665          */
5666         put_page(page);
5667         kvm->arch.apic_access_page_done = true;
5668 out:
5669         mutex_unlock(&kvm->slots_lock);
5670         return r;
5671 }
5672
5673 static int allocate_vpid(void)
5674 {
5675         int vpid;
5676
5677         if (!enable_vpid)
5678                 return 0;
5679         spin_lock(&vmx_vpid_lock);
5680         vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
5681         if (vpid < VMX_NR_VPIDS)
5682                 __set_bit(vpid, vmx_vpid_bitmap);
5683         else
5684                 vpid = 0;
5685         spin_unlock(&vmx_vpid_lock);
5686         return vpid;
5687 }
5688
5689 static void free_vpid(int vpid)
5690 {
5691         if (!enable_vpid || vpid == 0)
5692                 return;
5693         spin_lock(&vmx_vpid_lock);
5694         __clear_bit(vpid, vmx_vpid_bitmap);
5695         spin_unlock(&vmx_vpid_lock);
5696 }
5697
5698 static void __always_inline vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
5699                                                           u32 msr, int type)
5700 {
5701         int f = sizeof(unsigned long);
5702
5703         if (!cpu_has_vmx_msr_bitmap())
5704                 return;
5705
5706         if (static_branch_unlikely(&enable_evmcs))
5707                 evmcs_touch_msr_bitmap();
5708
5709         /*
5710          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5711          * have the write-low and read-high bitmap offsets the wrong way round.
5712          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5713          */
5714         if (msr <= 0x1fff) {
5715                 if (type & MSR_TYPE_R)
5716                         /* read-low */
5717                         __clear_bit(msr, msr_bitmap + 0x000 / f);
5718
5719                 if (type & MSR_TYPE_W)
5720                         /* write-low */
5721                         __clear_bit(msr, msr_bitmap + 0x800 / f);
5722
5723         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5724                 msr &= 0x1fff;
5725                 if (type & MSR_TYPE_R)
5726                         /* read-high */
5727                         __clear_bit(msr, msr_bitmap + 0x400 / f);
5728
5729                 if (type & MSR_TYPE_W)
5730                         /* write-high */
5731                         __clear_bit(msr, msr_bitmap + 0xc00 / f);
5732
5733         }
5734 }
5735
5736 static void __always_inline vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
5737                                                          u32 msr, int type)
5738 {
5739         int f = sizeof(unsigned long);
5740
5741         if (!cpu_has_vmx_msr_bitmap())
5742                 return;
5743
5744         if (static_branch_unlikely(&enable_evmcs))
5745                 evmcs_touch_msr_bitmap();
5746
5747         /*
5748          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5749          * have the write-low and read-high bitmap offsets the wrong way round.
5750          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5751          */
5752         if (msr <= 0x1fff) {
5753                 if (type & MSR_TYPE_R)
5754                         /* read-low */
5755                         __set_bit(msr, msr_bitmap + 0x000 / f);
5756
5757                 if (type & MSR_TYPE_W)
5758                         /* write-low */
5759                         __set_bit(msr, msr_bitmap + 0x800 / f);
5760
5761         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5762                 msr &= 0x1fff;
5763                 if (type & MSR_TYPE_R)
5764                         /* read-high */
5765                         __set_bit(msr, msr_bitmap + 0x400 / f);
5766
5767                 if (type & MSR_TYPE_W)
5768                         /* write-high */
5769                         __set_bit(msr, msr_bitmap + 0xc00 / f);
5770
5771         }
5772 }
5773
5774 static void __always_inline vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
5775                                                       u32 msr, int type, bool value)
5776 {
5777         if (value)
5778                 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
5779         else
5780                 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
5781 }
5782
5783 /*
5784  * If a msr is allowed by L0, we should check whether it is allowed by L1.
5785  * The corresponding bit will be cleared unless both of L0 and L1 allow it.
5786  */
5787 static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
5788                                                unsigned long *msr_bitmap_nested,
5789                                                u32 msr, int type)
5790 {
5791         int f = sizeof(unsigned long);
5792
5793         /*
5794          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5795          * have the write-low and read-high bitmap offsets the wrong way round.
5796          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5797          */
5798         if (msr <= 0x1fff) {
5799                 if (type & MSR_TYPE_R &&
5800                    !test_bit(msr, msr_bitmap_l1 + 0x000 / f))
5801                         /* read-low */
5802                         __clear_bit(msr, msr_bitmap_nested + 0x000 / f);
5803
5804                 if (type & MSR_TYPE_W &&
5805                    !test_bit(msr, msr_bitmap_l1 + 0x800 / f))
5806                         /* write-low */
5807                         __clear_bit(msr, msr_bitmap_nested + 0x800 / f);
5808
5809         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5810                 msr &= 0x1fff;
5811                 if (type & MSR_TYPE_R &&
5812                    !test_bit(msr, msr_bitmap_l1 + 0x400 / f))
5813                         /* read-high */
5814                         __clear_bit(msr, msr_bitmap_nested + 0x400 / f);
5815
5816                 if (type & MSR_TYPE_W &&
5817                    !test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
5818                         /* write-high */
5819                         __clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
5820
5821         }
5822 }
5823
5824 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
5825 {
5826         u8 mode = 0;
5827
5828         if (cpu_has_secondary_exec_ctrls() &&
5829             (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
5830              SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
5831                 mode |= MSR_BITMAP_MODE_X2APIC;
5832                 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
5833                         mode |= MSR_BITMAP_MODE_X2APIC_APICV;
5834         }
5835
5836         if (is_long_mode(vcpu))
5837                 mode |= MSR_BITMAP_MODE_LM;
5838
5839         return mode;
5840 }
5841
5842 #define X2APIC_MSR(r) (APIC_BASE_MSR + ((r) >> 4))
5843
5844 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
5845                                          u8 mode)
5846 {
5847         int msr;
5848
5849         for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
5850                 unsigned word = msr / BITS_PER_LONG;
5851                 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
5852                 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
5853         }
5854
5855         if (mode & MSR_BITMAP_MODE_X2APIC) {
5856                 /*
5857                  * TPR reads and writes can be virtualized even if virtual interrupt
5858                  * delivery is not in use.
5859                  */
5860                 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
5861                 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
5862                         vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
5863                         vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
5864                         vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
5865                 }
5866         }
5867 }
5868
5869 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
5870 {
5871         struct vcpu_vmx *vmx = to_vmx(vcpu);
5872         unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
5873         u8 mode = vmx_msr_bitmap_mode(vcpu);
5874         u8 changed = mode ^ vmx->msr_bitmap_mode;
5875
5876         if (!changed)
5877                 return;
5878
5879         vmx_set_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW,
5880                                   !(mode & MSR_BITMAP_MODE_LM));
5881
5882         if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
5883                 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
5884
5885         vmx->msr_bitmap_mode = mode;
5886 }
5887
5888 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
5889 {
5890         return enable_apicv;
5891 }
5892
5893 static void nested_mark_vmcs12_pages_dirty(struct kvm_vcpu *vcpu)
5894 {
5895         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5896         gfn_t gfn;
5897
5898         /*
5899          * Don't need to mark the APIC access page dirty; it is never
5900          * written to by the CPU during APIC virtualization.
5901          */
5902
5903         if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
5904                 gfn = vmcs12->virtual_apic_page_addr >> PAGE_SHIFT;
5905                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5906         }
5907
5908         if (nested_cpu_has_posted_intr(vmcs12)) {
5909                 gfn = vmcs12->posted_intr_desc_addr >> PAGE_SHIFT;
5910                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5911         }
5912 }
5913
5914
5915 static void vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
5916 {
5917         struct vcpu_vmx *vmx = to_vmx(vcpu);
5918         int max_irr;
5919         void *vapic_page;
5920         u16 status;
5921
5922         if (!vmx->nested.pi_desc || !vmx->nested.pi_pending)
5923                 return;
5924
5925         vmx->nested.pi_pending = false;
5926         if (!pi_test_and_clear_on(vmx->nested.pi_desc))
5927                 return;
5928
5929         max_irr = find_last_bit((unsigned long *)vmx->nested.pi_desc->pir, 256);
5930         if (max_irr != 256) {
5931                 vapic_page = kmap(vmx->nested.virtual_apic_page);
5932                 __kvm_apic_update_irr(vmx->nested.pi_desc->pir,
5933                         vapic_page, &max_irr);
5934                 kunmap(vmx->nested.virtual_apic_page);
5935
5936                 status = vmcs_read16(GUEST_INTR_STATUS);
5937                 if ((u8)max_irr > ((u8)status & 0xff)) {
5938                         status &= ~0xff;
5939                         status |= (u8)max_irr;
5940                         vmcs_write16(GUEST_INTR_STATUS, status);
5941                 }
5942         }
5943
5944         nested_mark_vmcs12_pages_dirty(vcpu);
5945 }
5946
5947 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
5948                                                      bool nested)
5949 {
5950 #ifdef CONFIG_SMP
5951         int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
5952
5953         if (vcpu->mode == IN_GUEST_MODE) {
5954                 /*
5955                  * The vector of interrupt to be delivered to vcpu had
5956                  * been set in PIR before this function.
5957                  *
5958                  * Following cases will be reached in this block, and
5959                  * we always send a notification event in all cases as
5960                  * explained below.
5961                  *
5962                  * Case 1: vcpu keeps in non-root mode. Sending a
5963                  * notification event posts the interrupt to vcpu.
5964                  *
5965                  * Case 2: vcpu exits to root mode and is still
5966                  * runnable. PIR will be synced to vIRR before the
5967                  * next vcpu entry. Sending a notification event in
5968                  * this case has no effect, as vcpu is not in root
5969                  * mode.
5970                  *
5971                  * Case 3: vcpu exits to root mode and is blocked.
5972                  * vcpu_block() has already synced PIR to vIRR and
5973                  * never blocks vcpu if vIRR is not cleared. Therefore,
5974                  * a blocked vcpu here does not wait for any requested
5975                  * interrupts in PIR, and sending a notification event
5976                  * which has no effect is safe here.
5977                  */
5978
5979                 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
5980                 return true;
5981         }
5982 #endif
5983         return false;
5984 }
5985
5986 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
5987                                                 int vector)
5988 {
5989         struct vcpu_vmx *vmx = to_vmx(vcpu);
5990
5991         if (is_guest_mode(vcpu) &&
5992             vector == vmx->nested.posted_intr_nv) {
5993                 /*
5994                  * If a posted intr is not recognized by hardware,
5995                  * we will accomplish it in the next vmentry.
5996                  */
5997                 vmx->nested.pi_pending = true;
5998                 kvm_make_request(KVM_REQ_EVENT, vcpu);
5999                 /* the PIR and ON have been set by L1. */
6000                 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
6001                         kvm_vcpu_kick(vcpu);
6002                 return 0;
6003         }
6004         return -1;
6005 }
6006 /*
6007  * Send interrupt to vcpu via posted interrupt way.
6008  * 1. If target vcpu is running(non-root mode), send posted interrupt
6009  * notification to vcpu and hardware will sync PIR to vIRR atomically.
6010  * 2. If target vcpu isn't running(root mode), kick it to pick up the
6011  * interrupt from PIR in next vmentry.
6012  */
6013 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
6014 {
6015         struct vcpu_vmx *vmx = to_vmx(vcpu);
6016         int r;
6017
6018         r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
6019         if (!r)
6020                 return;
6021
6022         if (pi_test_and_set_pir(vector, &vmx->pi_desc))
6023                 return;
6024
6025         /* If a previous notification has sent the IPI, nothing to do.  */
6026         if (pi_test_and_set_on(&vmx->pi_desc))
6027                 return;
6028
6029         if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
6030                 kvm_vcpu_kick(vcpu);
6031 }
6032
6033 /*
6034  * Set up the vmcs's constant host-state fields, i.e., host-state fields that
6035  * will not change in the lifetime of the guest.
6036  * Note that host-state that does change is set elsewhere. E.g., host-state
6037  * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
6038  */
6039 static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
6040 {
6041         u32 low32, high32;
6042         unsigned long tmpl;
6043         struct desc_ptr dt;
6044         unsigned long cr0, cr3, cr4;
6045
6046         cr0 = read_cr0();
6047         WARN_ON(cr0 & X86_CR0_TS);
6048         vmcs_writel(HOST_CR0, cr0);  /* 22.2.3 */
6049
6050         /*
6051          * Save the most likely value for this task's CR3 in the VMCS.
6052          * We can't use __get_current_cr3_fast() because we're not atomic.
6053          */
6054         cr3 = __read_cr3();
6055         vmcs_writel(HOST_CR3, cr3);             /* 22.2.3  FIXME: shadow tables */
6056         vmx->loaded_vmcs->vmcs_host_cr3 = cr3;
6057
6058         /* Save the most likely value for this task's CR4 in the VMCS. */
6059         cr4 = cr4_read_shadow();
6060         vmcs_writel(HOST_CR4, cr4);                     /* 22.2.3, 22.2.5 */
6061         vmx->loaded_vmcs->vmcs_host_cr4 = cr4;
6062
6063         vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
6064 #ifdef CONFIG_X86_64
6065         /*
6066          * Load null selectors, so we can avoid reloading them in
6067          * __vmx_load_host_state(), in case userspace uses the null selectors
6068          * too (the expected case).
6069          */
6070         vmcs_write16(HOST_DS_SELECTOR, 0);
6071         vmcs_write16(HOST_ES_SELECTOR, 0);
6072 #else
6073         vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
6074         vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
6075 #endif
6076         vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
6077         vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
6078
6079         store_idt(&dt);
6080         vmcs_writel(HOST_IDTR_BASE, dt.address);   /* 22.2.4 */
6081         vmx->host_idt_base = dt.address;
6082
6083         vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
6084
6085         rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
6086         vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
6087         rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
6088         vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl);   /* 22.2.3 */
6089
6090         if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
6091                 rdmsr(MSR_IA32_CR_PAT, low32, high32);
6092                 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
6093         }
6094 }
6095
6096 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
6097 {
6098         vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
6099         if (enable_ept)
6100                 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
6101         if (is_guest_mode(&vmx->vcpu))
6102                 vmx->vcpu.arch.cr4_guest_owned_bits &=
6103                         ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
6104         vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
6105 }
6106
6107 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
6108 {
6109         u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
6110
6111         if (!kvm_vcpu_apicv_active(&vmx->vcpu))
6112                 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
6113
6114         if (!enable_vnmi)
6115                 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
6116
6117         /* Enable the preemption timer dynamically */
6118         pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
6119         return pin_based_exec_ctrl;
6120 }
6121
6122 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
6123 {
6124         struct vcpu_vmx *vmx = to_vmx(vcpu);
6125
6126         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
6127         if (cpu_has_secondary_exec_ctrls()) {
6128                 if (kvm_vcpu_apicv_active(vcpu))
6129                         vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
6130                                       SECONDARY_EXEC_APIC_REGISTER_VIRT |
6131                                       SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6132                 else
6133                         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
6134                                         SECONDARY_EXEC_APIC_REGISTER_VIRT |
6135                                         SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6136         }
6137
6138         if (cpu_has_vmx_msr_bitmap())
6139                 vmx_update_msr_bitmap(vcpu);
6140 }
6141
6142 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
6143 {
6144         u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
6145
6146         if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
6147                 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
6148
6149         if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
6150                 exec_control &= ~CPU_BASED_TPR_SHADOW;
6151 #ifdef CONFIG_X86_64
6152                 exec_control |= CPU_BASED_CR8_STORE_EXITING |
6153                                 CPU_BASED_CR8_LOAD_EXITING;
6154 #endif
6155         }
6156         if (!enable_ept)
6157                 exec_control |= CPU_BASED_CR3_STORE_EXITING |
6158                                 CPU_BASED_CR3_LOAD_EXITING  |
6159                                 CPU_BASED_INVLPG_EXITING;
6160         if (kvm_mwait_in_guest(vmx->vcpu.kvm))
6161                 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
6162                                 CPU_BASED_MONITOR_EXITING);
6163         if (kvm_hlt_in_guest(vmx->vcpu.kvm))
6164                 exec_control &= ~CPU_BASED_HLT_EXITING;
6165         return exec_control;
6166 }
6167
6168 static bool vmx_rdrand_supported(void)
6169 {
6170         return vmcs_config.cpu_based_2nd_exec_ctrl &
6171                 SECONDARY_EXEC_RDRAND_EXITING;
6172 }
6173
6174 static bool vmx_rdseed_supported(void)
6175 {
6176         return vmcs_config.cpu_based_2nd_exec_ctrl &
6177                 SECONDARY_EXEC_RDSEED_EXITING;
6178 }
6179
6180 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
6181 {
6182         struct kvm_vcpu *vcpu = &vmx->vcpu;
6183
6184         u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
6185
6186         if (!cpu_need_virtualize_apic_accesses(vcpu))
6187                 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6188         if (vmx->vpid == 0)
6189                 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
6190         if (!enable_ept) {
6191                 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
6192                 enable_unrestricted_guest = 0;
6193         }
6194         if (!enable_unrestricted_guest)
6195                 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
6196         if (kvm_pause_in_guest(vmx->vcpu.kvm))
6197                 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
6198         if (!kvm_vcpu_apicv_active(vcpu))
6199                 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
6200                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6201         exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6202
6203         /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
6204          * in vmx_set_cr4.  */
6205         exec_control &= ~SECONDARY_EXEC_DESC;
6206
6207         /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
6208            (handle_vmptrld).
6209            We can NOT enable shadow_vmcs here because we don't have yet
6210            a current VMCS12
6211         */
6212         exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
6213
6214         if (!enable_pml)
6215                 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
6216
6217         if (vmx_xsaves_supported()) {
6218                 /* Exposing XSAVES only when XSAVE is exposed */
6219                 bool xsaves_enabled =
6220                         guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
6221                         guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
6222
6223                 if (!xsaves_enabled)
6224                         exec_control &= ~SECONDARY_EXEC_XSAVES;
6225
6226                 if (nested) {
6227                         if (xsaves_enabled)
6228                                 vmx->nested.msrs.secondary_ctls_high |=
6229                                         SECONDARY_EXEC_XSAVES;
6230                         else
6231                                 vmx->nested.msrs.secondary_ctls_high &=
6232                                         ~SECONDARY_EXEC_XSAVES;
6233                 }
6234         }
6235
6236         if (vmx_rdtscp_supported()) {
6237                 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
6238                 if (!rdtscp_enabled)
6239                         exec_control &= ~SECONDARY_EXEC_RDTSCP;
6240
6241                 if (nested) {
6242                         if (rdtscp_enabled)
6243                                 vmx->nested.msrs.secondary_ctls_high |=
6244                                         SECONDARY_EXEC_RDTSCP;
6245                         else
6246                                 vmx->nested.msrs.secondary_ctls_high &=
6247                                         ~SECONDARY_EXEC_RDTSCP;
6248                 }
6249         }
6250
6251         if (vmx_invpcid_supported()) {
6252                 /* Exposing INVPCID only when PCID is exposed */
6253                 bool invpcid_enabled =
6254                         guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
6255                         guest_cpuid_has(vcpu, X86_FEATURE_PCID);
6256
6257                 if (!invpcid_enabled) {
6258                         exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
6259                         guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
6260                 }
6261
6262                 if (nested) {
6263                         if (invpcid_enabled)
6264                                 vmx->nested.msrs.secondary_ctls_high |=
6265                                         SECONDARY_EXEC_ENABLE_INVPCID;
6266                         else
6267                                 vmx->nested.msrs.secondary_ctls_high &=
6268                                         ~SECONDARY_EXEC_ENABLE_INVPCID;
6269                 }
6270         }
6271
6272         if (vmx_rdrand_supported()) {
6273                 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
6274                 if (rdrand_enabled)
6275                         exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
6276
6277                 if (nested) {
6278                         if (rdrand_enabled)
6279                                 vmx->nested.msrs.secondary_ctls_high |=
6280                                         SECONDARY_EXEC_RDRAND_EXITING;
6281                         else
6282                                 vmx->nested.msrs.secondary_ctls_high &=
6283                                         ~SECONDARY_EXEC_RDRAND_EXITING;
6284                 }
6285         }
6286
6287         if (vmx_rdseed_supported()) {
6288                 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
6289                 if (rdseed_enabled)
6290                         exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
6291
6292                 if (nested) {
6293                         if (rdseed_enabled)
6294                                 vmx->nested.msrs.secondary_ctls_high |=
6295                                         SECONDARY_EXEC_RDSEED_EXITING;
6296                         else
6297                                 vmx->nested.msrs.secondary_ctls_high &=
6298                                         ~SECONDARY_EXEC_RDSEED_EXITING;
6299                 }
6300         }
6301
6302         vmx->secondary_exec_control = exec_control;
6303 }
6304
6305 static void ept_set_mmio_spte_mask(void)
6306 {
6307         /*
6308          * EPT Misconfigurations can be generated if the value of bits 2:0
6309          * of an EPT paging-structure entry is 110b (write/execute).
6310          */
6311         kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
6312                                    VMX_EPT_MISCONFIG_WX_VALUE);
6313 }
6314
6315 #define VMX_XSS_EXIT_BITMAP 0
6316 /*
6317  * Sets up the vmcs for emulated real mode.
6318  */
6319 static void vmx_vcpu_setup(struct vcpu_vmx *vmx)
6320 {
6321 #ifdef CONFIG_X86_64
6322         unsigned long a;
6323 #endif
6324         int i;
6325
6326         if (enable_shadow_vmcs) {
6327                 /*
6328                  * At vCPU creation, "VMWRITE to any supported field
6329                  * in the VMCS" is supported, so use the more
6330                  * permissive vmx_vmread_bitmap to specify both read
6331                  * and write permissions for the shadow VMCS.
6332                  */
6333                 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
6334                 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmread_bitmap));
6335         }
6336         if (cpu_has_vmx_msr_bitmap())
6337                 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
6338
6339         vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
6340
6341         /* Control */
6342         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
6343         vmx->hv_deadline_tsc = -1;
6344
6345         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
6346
6347         if (cpu_has_secondary_exec_ctrls()) {
6348                 vmx_compute_secondary_exec_control(vmx);
6349                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
6350                              vmx->secondary_exec_control);
6351         }
6352
6353         if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
6354                 vmcs_write64(EOI_EXIT_BITMAP0, 0);
6355                 vmcs_write64(EOI_EXIT_BITMAP1, 0);
6356                 vmcs_write64(EOI_EXIT_BITMAP2, 0);
6357                 vmcs_write64(EOI_EXIT_BITMAP3, 0);
6358
6359                 vmcs_write16(GUEST_INTR_STATUS, 0);
6360
6361                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
6362                 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
6363         }
6364
6365         if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
6366                 vmcs_write32(PLE_GAP, ple_gap);
6367                 vmx->ple_window = ple_window;
6368                 vmx->ple_window_dirty = true;
6369         }
6370
6371         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
6372         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
6373         vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
6374
6375         vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
6376         vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
6377         vmx_set_constant_host_state(vmx);
6378 #ifdef CONFIG_X86_64
6379         rdmsrl(MSR_FS_BASE, a);
6380         vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
6381         rdmsrl(MSR_GS_BASE, a);
6382         vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
6383 #else
6384         vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
6385         vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
6386 #endif
6387
6388         if (cpu_has_vmx_vmfunc())
6389                 vmcs_write64(VM_FUNCTION_CONTROL, 0);
6390
6391         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
6392         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
6393         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
6394         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
6395         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
6396
6397         if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
6398                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
6399
6400         for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
6401                 u32 index = vmx_msr_index[i];
6402                 u32 data_low, data_high;
6403                 int j = vmx->nmsrs;
6404
6405                 if (rdmsr_safe(index, &data_low, &data_high) < 0)
6406                         continue;
6407                 if (wrmsr_safe(index, data_low, data_high) < 0)
6408                         continue;
6409                 vmx->guest_msrs[j].index = i;
6410                 vmx->guest_msrs[j].data = 0;
6411                 vmx->guest_msrs[j].mask = -1ull;
6412                 ++vmx->nmsrs;
6413         }
6414
6415         if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
6416                 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, vmx->arch_capabilities);
6417
6418         vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
6419
6420         /* 22.2.1, 20.8.1 */
6421         vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
6422
6423         vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
6424         vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
6425
6426         set_cr4_guest_host_mask(vmx);
6427
6428         if (vmx_xsaves_supported())
6429                 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
6430
6431         if (enable_pml) {
6432                 ASSERT(vmx->pml_pg);
6433                 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
6434                 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
6435         }
6436 }
6437
6438 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
6439 {
6440         struct vcpu_vmx *vmx = to_vmx(vcpu);
6441         struct msr_data apic_base_msr;
6442         u64 cr0;
6443
6444         vmx->rmode.vm86_active = 0;
6445         vmx->spec_ctrl = 0;
6446
6447         vcpu->arch.microcode_version = 0x100000000ULL;
6448         vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
6449         kvm_set_cr8(vcpu, 0);
6450
6451         if (!init_event) {
6452                 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
6453                                      MSR_IA32_APICBASE_ENABLE;
6454                 if (kvm_vcpu_is_reset_bsp(vcpu))
6455                         apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
6456                 apic_base_msr.host_initiated = true;
6457                 kvm_set_apic_base(vcpu, &apic_base_msr);
6458         }
6459
6460         vmx_segment_cache_clear(vmx);
6461
6462         seg_setup(VCPU_SREG_CS);
6463         vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
6464         vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
6465
6466         seg_setup(VCPU_SREG_DS);
6467         seg_setup(VCPU_SREG_ES);
6468         seg_setup(VCPU_SREG_FS);
6469         seg_setup(VCPU_SREG_GS);
6470         seg_setup(VCPU_SREG_SS);
6471
6472         vmcs_write16(GUEST_TR_SELECTOR, 0);
6473         vmcs_writel(GUEST_TR_BASE, 0);
6474         vmcs_write32(GUEST_TR_LIMIT, 0xffff);
6475         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
6476
6477         vmcs_write16(GUEST_LDTR_SELECTOR, 0);
6478         vmcs_writel(GUEST_LDTR_BASE, 0);
6479         vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
6480         vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
6481
6482         if (!init_event) {
6483                 vmcs_write32(GUEST_SYSENTER_CS, 0);
6484                 vmcs_writel(GUEST_SYSENTER_ESP, 0);
6485                 vmcs_writel(GUEST_SYSENTER_EIP, 0);
6486                 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
6487         }
6488
6489         kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
6490         kvm_rip_write(vcpu, 0xfff0);
6491
6492         vmcs_writel(GUEST_GDTR_BASE, 0);
6493         vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
6494
6495         vmcs_writel(GUEST_IDTR_BASE, 0);
6496         vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
6497
6498         vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
6499         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
6500         vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
6501         if (kvm_mpx_supported())
6502                 vmcs_write64(GUEST_BNDCFGS, 0);
6503
6504         setup_msrs(vmx);
6505
6506         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
6507
6508         if (cpu_has_vmx_tpr_shadow() && !init_event) {
6509                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
6510                 if (cpu_need_tpr_shadow(vcpu))
6511                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
6512                                      __pa(vcpu->arch.apic->regs));
6513                 vmcs_write32(TPR_THRESHOLD, 0);
6514         }
6515
6516         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6517
6518         if (vmx->vpid != 0)
6519                 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
6520
6521         cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
6522         vmx->vcpu.arch.cr0 = cr0;
6523         vmx_set_cr0(vcpu, cr0); /* enter rmode */
6524         vmx_set_cr4(vcpu, 0);
6525         vmx_set_efer(vcpu, 0);
6526
6527         update_exception_bitmap(vcpu);
6528
6529         vpid_sync_context(vmx->vpid);
6530         if (init_event)
6531                 vmx_clear_hlt(vcpu);
6532 }
6533
6534 /*
6535  * In nested virtualization, check if L1 asked to exit on external interrupts.
6536  * For most existing hypervisors, this will always return true.
6537  */
6538 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
6539 {
6540         return get_vmcs12(vcpu)->pin_based_vm_exec_control &
6541                 PIN_BASED_EXT_INTR_MASK;
6542 }
6543
6544 /*
6545  * In nested virtualization, check if L1 has set
6546  * VM_EXIT_ACK_INTR_ON_EXIT
6547  */
6548 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
6549 {
6550         return get_vmcs12(vcpu)->vm_exit_controls &
6551                 VM_EXIT_ACK_INTR_ON_EXIT;
6552 }
6553
6554 static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
6555 {
6556         return nested_cpu_has_nmi_exiting(get_vmcs12(vcpu));
6557 }
6558
6559 static void enable_irq_window(struct kvm_vcpu *vcpu)
6560 {
6561         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
6562                       CPU_BASED_VIRTUAL_INTR_PENDING);
6563 }
6564
6565 static void enable_nmi_window(struct kvm_vcpu *vcpu)
6566 {
6567         if (!enable_vnmi ||
6568             vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
6569                 enable_irq_window(vcpu);
6570                 return;
6571         }
6572
6573         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
6574                       CPU_BASED_VIRTUAL_NMI_PENDING);
6575 }
6576
6577 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
6578 {
6579         struct vcpu_vmx *vmx = to_vmx(vcpu);
6580         uint32_t intr;
6581         int irq = vcpu->arch.interrupt.nr;
6582
6583         trace_kvm_inj_virq(irq);
6584
6585         ++vcpu->stat.irq_injections;
6586         if (vmx->rmode.vm86_active) {
6587                 int inc_eip = 0;
6588                 if (vcpu->arch.interrupt.soft)
6589                         inc_eip = vcpu->arch.event_exit_inst_len;
6590                 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
6591                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6592                 return;
6593         }
6594         intr = irq | INTR_INFO_VALID_MASK;
6595         if (vcpu->arch.interrupt.soft) {
6596                 intr |= INTR_TYPE_SOFT_INTR;
6597                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
6598                              vmx->vcpu.arch.event_exit_inst_len);
6599         } else
6600                 intr |= INTR_TYPE_EXT_INTR;
6601         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
6602
6603         vmx_clear_hlt(vcpu);
6604 }
6605
6606 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
6607 {
6608         struct vcpu_vmx *vmx = to_vmx(vcpu);
6609
6610         if (!enable_vnmi) {
6611                 /*
6612                  * Tracking the NMI-blocked state in software is built upon
6613                  * finding the next open IRQ window. This, in turn, depends on
6614                  * well-behaving guests: They have to keep IRQs disabled at
6615                  * least as long as the NMI handler runs. Otherwise we may
6616                  * cause NMI nesting, maybe breaking the guest. But as this is
6617                  * highly unlikely, we can live with the residual risk.
6618                  */
6619                 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
6620                 vmx->loaded_vmcs->vnmi_blocked_time = 0;
6621         }
6622
6623         ++vcpu->stat.nmi_injections;
6624         vmx->loaded_vmcs->nmi_known_unmasked = false;
6625
6626         if (vmx->rmode.vm86_active) {
6627                 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
6628                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6629                 return;
6630         }
6631
6632         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
6633                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
6634
6635         vmx_clear_hlt(vcpu);
6636 }
6637
6638 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
6639 {
6640         struct vcpu_vmx *vmx = to_vmx(vcpu);
6641         bool masked;
6642
6643         if (!enable_vnmi)
6644                 return vmx->loaded_vmcs->soft_vnmi_blocked;
6645         if (vmx->loaded_vmcs->nmi_known_unmasked)
6646                 return false;
6647         masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
6648         vmx->loaded_vmcs->nmi_known_unmasked = !masked;
6649         return masked;
6650 }
6651
6652 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
6653 {
6654         struct vcpu_vmx *vmx = to_vmx(vcpu);
6655
6656         if (!enable_vnmi) {
6657                 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
6658                         vmx->loaded_vmcs->soft_vnmi_blocked = masked;
6659                         vmx->loaded_vmcs->vnmi_blocked_time = 0;
6660                 }
6661         } else {
6662                 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
6663                 if (masked)
6664                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6665                                       GUEST_INTR_STATE_NMI);
6666                 else
6667                         vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
6668                                         GUEST_INTR_STATE_NMI);
6669         }
6670 }
6671
6672 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
6673 {
6674         if (to_vmx(vcpu)->nested.nested_run_pending)
6675                 return 0;
6676
6677         if (!enable_vnmi &&
6678             to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
6679                 return 0;
6680
6681         return  !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6682                   (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
6683                    | GUEST_INTR_STATE_NMI));
6684 }
6685
6686 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
6687 {
6688         return (!to_vmx(vcpu)->nested.nested_run_pending &&
6689                 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
6690                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6691                         (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
6692 }
6693
6694 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
6695 {
6696         int ret;
6697
6698         if (enable_unrestricted_guest)
6699                 return 0;
6700
6701         ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
6702                                     PAGE_SIZE * 3);
6703         if (ret)
6704                 return ret;
6705         to_kvm_vmx(kvm)->tss_addr = addr;
6706         return init_rmode_tss(kvm);
6707 }
6708
6709 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
6710 {
6711         to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
6712         return 0;
6713 }
6714
6715 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
6716 {
6717         switch (vec) {
6718         case BP_VECTOR:
6719                 /*
6720                  * Update instruction length as we may reinject the exception
6721                  * from user space while in guest debugging mode.
6722                  */
6723                 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
6724                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6725                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
6726                         return false;
6727                 /* fall through */
6728         case DB_VECTOR:
6729                 if (vcpu->guest_debug &
6730                         (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
6731                         return false;
6732                 /* fall through */
6733         case DE_VECTOR:
6734         case OF_VECTOR:
6735         case BR_VECTOR:
6736         case UD_VECTOR:
6737         case DF_VECTOR:
6738         case SS_VECTOR:
6739         case GP_VECTOR:
6740         case MF_VECTOR:
6741                 return true;
6742         break;
6743         }
6744         return false;
6745 }
6746
6747 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
6748                                   int vec, u32 err_code)
6749 {
6750         /*
6751          * Instruction with address size override prefix opcode 0x67
6752          * Cause the #SS fault with 0 error code in VM86 mode.
6753          */
6754         if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
6755                 if (emulate_instruction(vcpu, 0) == EMULATE_DONE) {
6756                         if (vcpu->arch.halt_request) {
6757                                 vcpu->arch.halt_request = 0;
6758                                 return kvm_vcpu_halt(vcpu);
6759                         }
6760                         return 1;
6761                 }
6762                 return 0;
6763         }
6764
6765         /*
6766          * Forward all other exceptions that are valid in real mode.
6767          * FIXME: Breaks guest debugging in real mode, needs to be fixed with
6768          *        the required debugging infrastructure rework.
6769          */
6770         kvm_queue_exception(vcpu, vec);
6771         return 1;
6772 }
6773
6774 /*
6775  * Trigger machine check on the host. We assume all the MSRs are already set up
6776  * by the CPU and that we still run on the same CPU as the MCE occurred on.
6777  * We pass a fake environment to the machine check handler because we want
6778  * the guest to be always treated like user space, no matter what context
6779  * it used internally.
6780  */
6781 static void kvm_machine_check(void)
6782 {
6783 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
6784         struct pt_regs regs = {
6785                 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
6786                 .flags = X86_EFLAGS_IF,
6787         };
6788
6789         do_machine_check(&regs, 0);
6790 #endif
6791 }
6792
6793 static int handle_machine_check(struct kvm_vcpu *vcpu)
6794 {
6795         /* already handled by vcpu_run */
6796         return 1;
6797 }
6798
6799 static int handle_exception(struct kvm_vcpu *vcpu)
6800 {
6801         struct vcpu_vmx *vmx = to_vmx(vcpu);
6802         struct kvm_run *kvm_run = vcpu->run;
6803         u32 intr_info, ex_no, error_code;
6804         unsigned long cr2, rip, dr6;
6805         u32 vect_info;
6806         enum emulation_result er;
6807
6808         vect_info = vmx->idt_vectoring_info;
6809         intr_info = vmx->exit_intr_info;
6810
6811         if (is_machine_check(intr_info))
6812                 return handle_machine_check(vcpu);
6813
6814         if (is_nmi(intr_info))
6815                 return 1;  /* already handled by vmx_vcpu_run() */
6816
6817         if (is_invalid_opcode(intr_info))
6818                 return handle_ud(vcpu);
6819
6820         error_code = 0;
6821         if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
6822                 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
6823
6824         if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
6825                 WARN_ON_ONCE(!enable_vmware_backdoor);
6826                 er = emulate_instruction(vcpu,
6827                         EMULTYPE_VMWARE | EMULTYPE_NO_UD_ON_FAIL);
6828                 if (er == EMULATE_USER_EXIT)
6829                         return 0;
6830                 else if (er != EMULATE_DONE)
6831                         kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
6832                 return 1;
6833         }
6834
6835         /*
6836          * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
6837          * MMIO, it is better to report an internal error.
6838          * See the comments in vmx_handle_exit.
6839          */
6840         if ((vect_info & VECTORING_INFO_VALID_MASK) &&
6841             !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
6842                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6843                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
6844                 vcpu->run->internal.ndata = 3;
6845                 vcpu->run->internal.data[0] = vect_info;
6846                 vcpu->run->internal.data[1] = intr_info;
6847                 vcpu->run->internal.data[2] = error_code;
6848                 return 0;
6849         }
6850
6851         if (is_page_fault(intr_info)) {
6852                 cr2 = vmcs_readl(EXIT_QUALIFICATION);
6853                 /* EPT won't cause page fault directly */
6854                 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
6855                 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
6856         }
6857
6858         ex_no = intr_info & INTR_INFO_VECTOR_MASK;
6859
6860         if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
6861                 return handle_rmode_exception(vcpu, ex_no, error_code);
6862
6863         switch (ex_no) {
6864         case AC_VECTOR:
6865                 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
6866                 return 1;
6867         case DB_VECTOR:
6868                 dr6 = vmcs_readl(EXIT_QUALIFICATION);
6869                 if (!(vcpu->guest_debug &
6870                       (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
6871                         vcpu->arch.dr6 &= ~15;
6872                         vcpu->arch.dr6 |= dr6 | DR6_RTM;
6873                         if (is_icebp(intr_info))
6874                                 skip_emulated_instruction(vcpu);
6875
6876                         kvm_queue_exception(vcpu, DB_VECTOR);
6877                         return 1;
6878                 }
6879                 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
6880                 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
6881                 /* fall through */
6882         case BP_VECTOR:
6883                 /*
6884                  * Update instruction length as we may reinject #BP from
6885                  * user space while in guest debugging mode. Reading it for
6886                  * #DB as well causes no harm, it is not used in that case.
6887                  */
6888                 vmx->vcpu.arch.event_exit_inst_len =
6889                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6890                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6891                 rip = kvm_rip_read(vcpu);
6892                 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
6893                 kvm_run->debug.arch.exception = ex_no;
6894                 break;
6895         default:
6896                 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
6897                 kvm_run->ex.exception = ex_no;
6898                 kvm_run->ex.error_code = error_code;
6899                 break;
6900         }
6901         return 0;
6902 }
6903
6904 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
6905 {
6906         ++vcpu->stat.irq_exits;
6907         return 1;
6908 }
6909
6910 static int handle_triple_fault(struct kvm_vcpu *vcpu)
6911 {
6912         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6913         vcpu->mmio_needed = 0;
6914         return 0;
6915 }
6916
6917 static int handle_io(struct kvm_vcpu *vcpu)
6918 {
6919         unsigned long exit_qualification;
6920         int size, in, string;
6921         unsigned port;
6922
6923         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6924         string = (exit_qualification & 16) != 0;
6925
6926         ++vcpu->stat.io_exits;
6927
6928         if (string)
6929                 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6930
6931         port = exit_qualification >> 16;
6932         size = (exit_qualification & 7) + 1;
6933         in = (exit_qualification & 8) != 0;
6934
6935         return kvm_fast_pio(vcpu, size, port, in);
6936 }
6937
6938 static void
6939 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
6940 {
6941         /*
6942          * Patch in the VMCALL instruction:
6943          */
6944         hypercall[0] = 0x0f;
6945         hypercall[1] = 0x01;
6946         hypercall[2] = 0xc1;
6947 }
6948
6949 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
6950 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
6951 {
6952         if (is_guest_mode(vcpu)) {
6953                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6954                 unsigned long orig_val = val;
6955
6956                 /*
6957                  * We get here when L2 changed cr0 in a way that did not change
6958                  * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
6959                  * but did change L0 shadowed bits. So we first calculate the
6960                  * effective cr0 value that L1 would like to write into the
6961                  * hardware. It consists of the L2-owned bits from the new
6962                  * value combined with the L1-owned bits from L1's guest_cr0.
6963                  */
6964                 val = (val & ~vmcs12->cr0_guest_host_mask) |
6965                         (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
6966
6967                 if (!nested_guest_cr0_valid(vcpu, val))
6968                         return 1;
6969
6970                 if (kvm_set_cr0(vcpu, val))
6971                         return 1;
6972                 vmcs_writel(CR0_READ_SHADOW, orig_val);
6973                 return 0;
6974         } else {
6975                 if (to_vmx(vcpu)->nested.vmxon &&
6976                     !nested_host_cr0_valid(vcpu, val))
6977                         return 1;
6978
6979                 return kvm_set_cr0(vcpu, val);
6980         }
6981 }
6982
6983 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
6984 {
6985         if (is_guest_mode(vcpu)) {
6986                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6987                 unsigned long orig_val = val;
6988
6989                 /* analogously to handle_set_cr0 */
6990                 val = (val & ~vmcs12->cr4_guest_host_mask) |
6991                         (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
6992                 if (kvm_set_cr4(vcpu, val))
6993                         return 1;
6994                 vmcs_writel(CR4_READ_SHADOW, orig_val);
6995                 return 0;
6996         } else
6997                 return kvm_set_cr4(vcpu, val);
6998 }
6999
7000 static int handle_desc(struct kvm_vcpu *vcpu)
7001 {
7002         WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
7003         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
7004 }
7005
7006 static int handle_cr(struct kvm_vcpu *vcpu)
7007 {
7008         unsigned long exit_qualification, val;
7009         int cr;
7010         int reg;
7011         int err;
7012         int ret;
7013
7014         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7015         cr = exit_qualification & 15;
7016         reg = (exit_qualification >> 8) & 15;
7017         switch ((exit_qualification >> 4) & 3) {
7018         case 0: /* mov to cr */
7019                 val = kvm_register_readl(vcpu, reg);
7020                 trace_kvm_cr_write(cr, val);
7021                 switch (cr) {
7022                 case 0:
7023                         err = handle_set_cr0(vcpu, val);
7024                         return kvm_complete_insn_gp(vcpu, err);
7025                 case 3:
7026                         WARN_ON_ONCE(enable_unrestricted_guest);
7027                         err = kvm_set_cr3(vcpu, val);
7028                         return kvm_complete_insn_gp(vcpu, err);
7029                 case 4:
7030                         err = handle_set_cr4(vcpu, val);
7031                         return kvm_complete_insn_gp(vcpu, err);
7032                 case 8: {
7033                                 u8 cr8_prev = kvm_get_cr8(vcpu);
7034                                 u8 cr8 = (u8)val;
7035                                 err = kvm_set_cr8(vcpu, cr8);
7036                                 ret = kvm_complete_insn_gp(vcpu, err);
7037                                 if (lapic_in_kernel(vcpu))
7038                                         return ret;
7039                                 if (cr8_prev <= cr8)
7040                                         return ret;
7041                                 /*
7042                                  * TODO: we might be squashing a
7043                                  * KVM_GUESTDBG_SINGLESTEP-triggered
7044                                  * KVM_EXIT_DEBUG here.
7045                                  */
7046                                 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
7047                                 return 0;
7048                         }
7049                 }
7050                 break;
7051         case 2: /* clts */
7052                 WARN_ONCE(1, "Guest should always own CR0.TS");
7053                 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
7054                 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
7055                 return kvm_skip_emulated_instruction(vcpu);
7056         case 1: /*mov from cr*/
7057                 switch (cr) {
7058                 case 3:
7059                         WARN_ON_ONCE(enable_unrestricted_guest);
7060                         val = kvm_read_cr3(vcpu);
7061                         kvm_register_write(vcpu, reg, val);
7062                         trace_kvm_cr_read(cr, val);
7063                         return kvm_skip_emulated_instruction(vcpu);
7064                 case 8:
7065                         val = kvm_get_cr8(vcpu);
7066                         kvm_register_write(vcpu, reg, val);
7067                         trace_kvm_cr_read(cr, val);
7068                         return kvm_skip_emulated_instruction(vcpu);
7069                 }
7070                 break;
7071         case 3: /* lmsw */
7072                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
7073                 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
7074                 kvm_lmsw(vcpu, val);
7075
7076                 return kvm_skip_emulated_instruction(vcpu);
7077         default:
7078                 break;
7079         }
7080         vcpu->run->exit_reason = 0;
7081         vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
7082                (int)(exit_qualification >> 4) & 3, cr);
7083         return 0;
7084 }
7085
7086 static int handle_dr(struct kvm_vcpu *vcpu)
7087 {
7088         unsigned long exit_qualification;
7089         int dr, dr7, reg;
7090
7091         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7092         dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
7093
7094         /* First, if DR does not exist, trigger UD */
7095         if (!kvm_require_dr(vcpu, dr))
7096                 return 1;
7097
7098         /* Do not handle if the CPL > 0, will trigger GP on re-entry */
7099         if (!kvm_require_cpl(vcpu, 0))
7100                 return 1;
7101         dr7 = vmcs_readl(GUEST_DR7);
7102         if (dr7 & DR7_GD) {
7103                 /*
7104                  * As the vm-exit takes precedence over the debug trap, we
7105                  * need to emulate the latter, either for the host or the
7106                  * guest debugging itself.
7107                  */
7108                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
7109                         vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
7110                         vcpu->run->debug.arch.dr7 = dr7;
7111                         vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
7112                         vcpu->run->debug.arch.exception = DB_VECTOR;
7113                         vcpu->run->exit_reason = KVM_EXIT_DEBUG;
7114                         return 0;
7115                 } else {
7116                         vcpu->arch.dr6 &= ~15;
7117                         vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
7118                         kvm_queue_exception(vcpu, DB_VECTOR);
7119                         return 1;
7120                 }
7121         }
7122
7123         if (vcpu->guest_debug == 0) {
7124                 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7125                                 CPU_BASED_MOV_DR_EXITING);
7126
7127                 /*
7128                  * No more DR vmexits; force a reload of the debug registers
7129                  * and reenter on this instruction.  The next vmexit will
7130                  * retrieve the full state of the debug registers.
7131                  */
7132                 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
7133                 return 1;
7134         }
7135
7136         reg = DEBUG_REG_ACCESS_REG(exit_qualification);
7137         if (exit_qualification & TYPE_MOV_FROM_DR) {
7138                 unsigned long val;
7139
7140                 if (kvm_get_dr(vcpu, dr, &val))
7141                         return 1;
7142                 kvm_register_write(vcpu, reg, val);
7143         } else
7144                 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
7145                         return 1;
7146
7147         return kvm_skip_emulated_instruction(vcpu);
7148 }
7149
7150 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
7151 {
7152         return vcpu->arch.dr6;
7153 }
7154
7155 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
7156 {
7157 }
7158
7159 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
7160 {
7161         get_debugreg(vcpu->arch.db[0], 0);
7162         get_debugreg(vcpu->arch.db[1], 1);
7163         get_debugreg(vcpu->arch.db[2], 2);
7164         get_debugreg(vcpu->arch.db[3], 3);
7165         get_debugreg(vcpu->arch.dr6, 6);
7166         vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
7167
7168         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
7169         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
7170 }
7171
7172 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
7173 {
7174         vmcs_writel(GUEST_DR7, val);
7175 }
7176
7177 static int handle_cpuid(struct kvm_vcpu *vcpu)
7178 {
7179         return kvm_emulate_cpuid(vcpu);
7180 }
7181
7182 static int handle_rdmsr(struct kvm_vcpu *vcpu)
7183 {
7184         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
7185         struct msr_data msr_info;
7186
7187         msr_info.index = ecx;
7188         msr_info.host_initiated = false;
7189         if (vmx_get_msr(vcpu, &msr_info)) {
7190                 trace_kvm_msr_read_ex(ecx);
7191                 kvm_inject_gp(vcpu, 0);
7192                 return 1;
7193         }
7194
7195         trace_kvm_msr_read(ecx, msr_info.data);
7196
7197         /* FIXME: handling of bits 32:63 of rax, rdx */
7198         vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
7199         vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
7200         return kvm_skip_emulated_instruction(vcpu);
7201 }
7202
7203 static int handle_wrmsr(struct kvm_vcpu *vcpu)
7204 {
7205         struct msr_data msr;
7206         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
7207         u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
7208                 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
7209
7210         msr.data = data;
7211         msr.index = ecx;
7212         msr.host_initiated = false;
7213         if (kvm_set_msr(vcpu, &msr) != 0) {
7214                 trace_kvm_msr_write_ex(ecx, data);
7215                 kvm_inject_gp(vcpu, 0);
7216                 return 1;
7217         }
7218
7219         trace_kvm_msr_write(ecx, data);
7220         return kvm_skip_emulated_instruction(vcpu);
7221 }
7222
7223 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
7224 {
7225         kvm_apic_update_ppr(vcpu);
7226         return 1;
7227 }
7228
7229 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
7230 {
7231         vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7232                         CPU_BASED_VIRTUAL_INTR_PENDING);
7233
7234         kvm_make_request(KVM_REQ_EVENT, vcpu);
7235
7236         ++vcpu->stat.irq_window_exits;
7237         return 1;
7238 }
7239
7240 static int handle_halt(struct kvm_vcpu *vcpu)
7241 {
7242         return kvm_emulate_halt(vcpu);
7243 }
7244
7245 static int handle_vmcall(struct kvm_vcpu *vcpu)
7246 {
7247         return kvm_emulate_hypercall(vcpu);
7248 }
7249
7250 static int handle_invd(struct kvm_vcpu *vcpu)
7251 {
7252         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
7253 }
7254
7255 static int handle_invlpg(struct kvm_vcpu *vcpu)
7256 {
7257         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7258
7259         kvm_mmu_invlpg(vcpu, exit_qualification);
7260         return kvm_skip_emulated_instruction(vcpu);
7261 }
7262
7263 static int handle_rdpmc(struct kvm_vcpu *vcpu)
7264 {
7265         int err;
7266
7267         err = kvm_rdpmc(vcpu);
7268         return kvm_complete_insn_gp(vcpu, err);
7269 }
7270
7271 static int handle_wbinvd(struct kvm_vcpu *vcpu)
7272 {
7273         return kvm_emulate_wbinvd(vcpu);
7274 }
7275
7276 static int handle_xsetbv(struct kvm_vcpu *vcpu)
7277 {
7278         u64 new_bv = kvm_read_edx_eax(vcpu);
7279         u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
7280
7281         if (kvm_set_xcr(vcpu, index, new_bv) == 0)
7282                 return kvm_skip_emulated_instruction(vcpu);
7283         return 1;
7284 }
7285
7286 static int handle_xsaves(struct kvm_vcpu *vcpu)
7287 {
7288         kvm_skip_emulated_instruction(vcpu);
7289         WARN(1, "this should never happen\n");
7290         return 1;
7291 }
7292
7293 static int handle_xrstors(struct kvm_vcpu *vcpu)
7294 {
7295         kvm_skip_emulated_instruction(vcpu);
7296         WARN(1, "this should never happen\n");
7297         return 1;
7298 }
7299
7300 static int handle_apic_access(struct kvm_vcpu *vcpu)
7301 {
7302         if (likely(fasteoi)) {
7303                 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7304                 int access_type, offset;
7305
7306                 access_type = exit_qualification & APIC_ACCESS_TYPE;
7307                 offset = exit_qualification & APIC_ACCESS_OFFSET;
7308                 /*
7309                  * Sane guest uses MOV to write EOI, with written value
7310                  * not cared. So make a short-circuit here by avoiding
7311                  * heavy instruction emulation.
7312                  */
7313                 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
7314                     (offset == APIC_EOI)) {
7315                         kvm_lapic_set_eoi(vcpu);
7316                         return kvm_skip_emulated_instruction(vcpu);
7317                 }
7318         }
7319         return emulate_instruction(vcpu, 0) == EMULATE_DONE;
7320 }
7321
7322 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
7323 {
7324         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7325         int vector = exit_qualification & 0xff;
7326
7327         /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
7328         kvm_apic_set_eoi_accelerated(vcpu, vector);
7329         return 1;
7330 }
7331
7332 static int handle_apic_write(struct kvm_vcpu *vcpu)
7333 {
7334         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7335         u32 offset = exit_qualification & 0xfff;
7336
7337         /* APIC-write VM exit is trap-like and thus no need to adjust IP */
7338         kvm_apic_write_nodecode(vcpu, offset);
7339         return 1;
7340 }
7341
7342 static int handle_task_switch(struct kvm_vcpu *vcpu)
7343 {
7344         struct vcpu_vmx *vmx = to_vmx(vcpu);
7345         unsigned long exit_qualification;
7346         bool has_error_code = false;
7347         u32 error_code = 0;
7348         u16 tss_selector;
7349         int reason, type, idt_v, idt_index;
7350
7351         idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
7352         idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
7353         type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
7354
7355         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7356
7357         reason = (u32)exit_qualification >> 30;
7358         if (reason == TASK_SWITCH_GATE && idt_v) {
7359                 switch (type) {
7360                 case INTR_TYPE_NMI_INTR:
7361                         vcpu->arch.nmi_injected = false;
7362                         vmx_set_nmi_mask(vcpu, true);
7363                         break;
7364                 case INTR_TYPE_EXT_INTR:
7365                 case INTR_TYPE_SOFT_INTR:
7366                         kvm_clear_interrupt_queue(vcpu);
7367                         break;
7368                 case INTR_TYPE_HARD_EXCEPTION:
7369                         if (vmx->idt_vectoring_info &
7370                             VECTORING_INFO_DELIVER_CODE_MASK) {
7371                                 has_error_code = true;
7372                                 error_code =
7373                                         vmcs_read32(IDT_VECTORING_ERROR_CODE);
7374                         }
7375                         /* fall through */
7376                 case INTR_TYPE_SOFT_EXCEPTION:
7377                         kvm_clear_exception_queue(vcpu);
7378                         break;
7379                 default:
7380                         break;
7381                 }
7382         }
7383         tss_selector = exit_qualification;
7384
7385         if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
7386                        type != INTR_TYPE_EXT_INTR &&
7387                        type != INTR_TYPE_NMI_INTR))
7388                 skip_emulated_instruction(vcpu);
7389
7390         if (kvm_task_switch(vcpu, tss_selector,
7391                             type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
7392                             has_error_code, error_code) == EMULATE_FAIL) {
7393                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7394                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7395                 vcpu->run->internal.ndata = 0;
7396                 return 0;
7397         }
7398
7399         /*
7400          * TODO: What about debug traps on tss switch?
7401          *       Are we supposed to inject them and update dr6?
7402          */
7403
7404         return 1;
7405 }
7406
7407 static int handle_ept_violation(struct kvm_vcpu *vcpu)
7408 {
7409         unsigned long exit_qualification;
7410         gpa_t gpa;
7411         u64 error_code;
7412
7413         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7414
7415         /*
7416          * EPT violation happened while executing iret from NMI,
7417          * "blocked by NMI" bit has to be set before next VM entry.
7418          * There are errata that may cause this bit to not be set:
7419          * AAK134, BY25.
7420          */
7421         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
7422                         enable_vnmi &&
7423                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
7424                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
7425
7426         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
7427         trace_kvm_page_fault(gpa, exit_qualification);
7428
7429         /* Is it a read fault? */
7430         error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
7431                      ? PFERR_USER_MASK : 0;
7432         /* Is it a write fault? */
7433         error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
7434                       ? PFERR_WRITE_MASK : 0;
7435         /* Is it a fetch fault? */
7436         error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
7437                       ? PFERR_FETCH_MASK : 0;
7438         /* ept page table entry is present? */
7439         error_code |= (exit_qualification &
7440                        (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
7441                         EPT_VIOLATION_EXECUTABLE))
7442                       ? PFERR_PRESENT_MASK : 0;
7443
7444         error_code |= (exit_qualification & 0x100) != 0 ?
7445                PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
7446
7447         vcpu->arch.exit_qualification = exit_qualification;
7448         return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
7449 }
7450
7451 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
7452 {
7453         gpa_t gpa;
7454
7455         /*
7456          * A nested guest cannot optimize MMIO vmexits, because we have an
7457          * nGPA here instead of the required GPA.
7458          */
7459         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
7460         if (!is_guest_mode(vcpu) &&
7461             !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
7462                 trace_kvm_fast_mmio(gpa);
7463                 /*
7464                  * Doing kvm_skip_emulated_instruction() depends on undefined
7465                  * behavior: Intel's manual doesn't mandate
7466                  * VM_EXIT_INSTRUCTION_LEN to be set in VMCS when EPT MISCONFIG
7467                  * occurs and while on real hardware it was observed to be set,
7468                  * other hypervisors (namely Hyper-V) don't set it, we end up
7469                  * advancing IP with some random value. Disable fast mmio when
7470                  * running nested and keep it for real hardware in hope that
7471                  * VM_EXIT_INSTRUCTION_LEN will always be set correctly.
7472                  */
7473                 if (!static_cpu_has(X86_FEATURE_HYPERVISOR))
7474                         return kvm_skip_emulated_instruction(vcpu);
7475                 else
7476                         return x86_emulate_instruction(vcpu, gpa, EMULTYPE_SKIP,
7477                                                        NULL, 0) == EMULATE_DONE;
7478         }
7479
7480         return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
7481 }
7482
7483 static int handle_nmi_window(struct kvm_vcpu *vcpu)
7484 {
7485         WARN_ON_ONCE(!enable_vnmi);
7486         vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7487                         CPU_BASED_VIRTUAL_NMI_PENDING);
7488         ++vcpu->stat.nmi_window_exits;
7489         kvm_make_request(KVM_REQ_EVENT, vcpu);
7490
7491         return 1;
7492 }
7493
7494 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
7495 {
7496         struct vcpu_vmx *vmx = to_vmx(vcpu);
7497         enum emulation_result err = EMULATE_DONE;
7498         int ret = 1;
7499         u32 cpu_exec_ctrl;
7500         bool intr_window_requested;
7501         unsigned count = 130;
7502
7503         /*
7504          * We should never reach the point where we are emulating L2
7505          * due to invalid guest state as that means we incorrectly
7506          * allowed a nested VMEntry with an invalid vmcs12.
7507          */
7508         WARN_ON_ONCE(vmx->emulation_required && vmx->nested.nested_run_pending);
7509
7510         cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
7511         intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
7512
7513         while (vmx->emulation_required && count-- != 0) {
7514                 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
7515                         return handle_interrupt_window(&vmx->vcpu);
7516
7517                 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
7518                         return 1;
7519
7520                 err = emulate_instruction(vcpu, 0);
7521
7522                 if (err == EMULATE_USER_EXIT) {
7523                         ++vcpu->stat.mmio_exits;
7524                         ret = 0;
7525                         goto out;
7526                 }
7527
7528                 if (err != EMULATE_DONE)
7529                         goto emulation_error;
7530
7531                 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
7532                     vcpu->arch.exception.pending)
7533                         goto emulation_error;
7534
7535                 if (vcpu->arch.halt_request) {
7536                         vcpu->arch.halt_request = 0;
7537                         ret = kvm_vcpu_halt(vcpu);
7538                         goto out;
7539                 }
7540
7541                 if (signal_pending(current))
7542                         goto out;
7543                 if (need_resched())
7544                         schedule();
7545         }
7546
7547 out:
7548         return ret;
7549
7550 emulation_error:
7551         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7552         vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7553         vcpu->run->internal.ndata = 0;
7554         return 0;
7555 }
7556
7557 static void grow_ple_window(struct kvm_vcpu *vcpu)
7558 {
7559         struct vcpu_vmx *vmx = to_vmx(vcpu);
7560         int old = vmx->ple_window;
7561
7562         vmx->ple_window = __grow_ple_window(old, ple_window,
7563                                             ple_window_grow,
7564                                             ple_window_max);
7565
7566         if (vmx->ple_window != old)
7567                 vmx->ple_window_dirty = true;
7568
7569         trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
7570 }
7571
7572 static void shrink_ple_window(struct kvm_vcpu *vcpu)
7573 {
7574         struct vcpu_vmx *vmx = to_vmx(vcpu);
7575         int old = vmx->ple_window;
7576
7577         vmx->ple_window = __shrink_ple_window(old, ple_window,
7578                                               ple_window_shrink,
7579                                               ple_window);
7580
7581         if (vmx->ple_window != old)
7582                 vmx->ple_window_dirty = true;
7583
7584         trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
7585 }
7586
7587 /*
7588  * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
7589  */
7590 static void wakeup_handler(void)
7591 {
7592         struct kvm_vcpu *vcpu;
7593         int cpu = smp_processor_id();
7594
7595         spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
7596         list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
7597                         blocked_vcpu_list) {
7598                 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7599
7600                 if (pi_test_on(pi_desc) == 1)
7601                         kvm_vcpu_kick(vcpu);
7602         }
7603         spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
7604 }
7605
7606 static void vmx_enable_tdp(void)
7607 {
7608         kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
7609                 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
7610                 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
7611                 0ull, VMX_EPT_EXECUTABLE_MASK,
7612                 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
7613                 VMX_EPT_RWX_MASK, 0ull);
7614
7615         ept_set_mmio_spte_mask();
7616         kvm_enable_tdp();
7617 }
7618
7619 static __init int hardware_setup(void)
7620 {
7621         unsigned long host_bndcfgs;
7622         int r = -ENOMEM, i;
7623
7624         rdmsrl_safe(MSR_EFER, &host_efer);
7625
7626         for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7627                 kvm_define_shared_msr(i, vmx_msr_index[i]);
7628
7629         for (i = 0; i < VMX_BITMAP_NR; i++) {
7630                 vmx_bitmap[i] = (unsigned long *)__get_free_page(GFP_KERNEL);
7631                 if (!vmx_bitmap[i])
7632                         goto out;
7633         }
7634
7635         memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
7636         memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
7637
7638         if (setup_vmcs_config(&vmcs_config) < 0) {
7639                 r = -EIO;
7640                 goto out;
7641         }
7642
7643         if (boot_cpu_has(X86_FEATURE_NX))
7644                 kvm_enable_efer_bits(EFER_NX);
7645
7646         if (boot_cpu_has(X86_FEATURE_MPX)) {
7647                 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7648                 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7649         }
7650
7651         if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7652                 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7653                 enable_vpid = 0;
7654
7655         if (!cpu_has_vmx_ept() ||
7656             !cpu_has_vmx_ept_4levels() ||
7657             !cpu_has_vmx_ept_mt_wb() ||
7658             !cpu_has_vmx_invept_global())
7659                 enable_ept = 0;
7660
7661         if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7662                 enable_ept_ad_bits = 0;
7663
7664         if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7665                 enable_unrestricted_guest = 0;
7666
7667         if (!cpu_has_vmx_flexpriority())
7668                 flexpriority_enabled = 0;
7669
7670         if (!cpu_has_virtual_nmis())
7671                 enable_vnmi = 0;
7672
7673         /*
7674          * set_apic_access_page_addr() is used to reload apic access
7675          * page upon invalidation.  No need to do anything if not
7676          * using the APIC_ACCESS_ADDR VMCS field.
7677          */
7678         if (!flexpriority_enabled)
7679                 kvm_x86_ops->set_apic_access_page_addr = NULL;
7680
7681         if (!cpu_has_vmx_tpr_shadow())
7682                 kvm_x86_ops->update_cr8_intercept = NULL;
7683
7684         if (enable_ept && !cpu_has_vmx_ept_2m_page())
7685                 kvm_disable_largepages();
7686
7687 #if IS_ENABLED(CONFIG_HYPERV)
7688         if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7689             && enable_ept)
7690                 kvm_x86_ops->tlb_remote_flush = vmx_hv_remote_flush_tlb;
7691 #endif
7692
7693         if (!cpu_has_vmx_ple()) {
7694                 ple_gap = 0;
7695                 ple_window = 0;
7696                 ple_window_grow = 0;
7697                 ple_window_max = 0;
7698                 ple_window_shrink = 0;
7699         }
7700
7701         if (!cpu_has_vmx_apicv()) {
7702                 enable_apicv = 0;
7703                 kvm_x86_ops->sync_pir_to_irr = NULL;
7704         }
7705
7706         if (cpu_has_vmx_tsc_scaling()) {
7707                 kvm_has_tsc_control = true;
7708                 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7709                 kvm_tsc_scaling_ratio_frac_bits = 48;
7710         }
7711
7712         set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7713
7714         if (enable_ept)
7715                 vmx_enable_tdp();
7716         else
7717                 kvm_disable_tdp();
7718
7719         if (!nested) {
7720                 kvm_x86_ops->get_nested_state = NULL;
7721                 kvm_x86_ops->set_nested_state = NULL;
7722         }
7723
7724         /*
7725          * Only enable PML when hardware supports PML feature, and both EPT
7726          * and EPT A/D bit features are enabled -- PML depends on them to work.
7727          */
7728         if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7729                 enable_pml = 0;
7730
7731         if (!enable_pml) {
7732                 kvm_x86_ops->slot_enable_log_dirty = NULL;
7733                 kvm_x86_ops->slot_disable_log_dirty = NULL;
7734                 kvm_x86_ops->flush_log_dirty = NULL;
7735                 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
7736         }
7737
7738         if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
7739                 u64 vmx_msr;
7740
7741                 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7742                 cpu_preemption_timer_multi =
7743                          vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7744         } else {
7745                 kvm_x86_ops->set_hv_timer = NULL;
7746                 kvm_x86_ops->cancel_hv_timer = NULL;
7747         }
7748
7749         if (!cpu_has_vmx_shadow_vmcs())
7750                 enable_shadow_vmcs = 0;
7751         if (enable_shadow_vmcs)
7752                 init_vmcs_shadow_fields();
7753
7754         kvm_set_posted_intr_wakeup_handler(wakeup_handler);
7755         nested_vmx_setup_ctls_msrs(&vmcs_config.nested, enable_apicv);
7756
7757         kvm_mce_cap_supported |= MCG_LMCE_P;
7758
7759         return alloc_kvm_area();
7760
7761 out:
7762         for (i = 0; i < VMX_BITMAP_NR; i++)
7763                 free_page((unsigned long)vmx_bitmap[i]);
7764
7765     return r;
7766 }
7767
7768 static __exit void hardware_unsetup(void)
7769 {
7770         int i;
7771
7772         for (i = 0; i < VMX_BITMAP_NR; i++)
7773                 free_page((unsigned long)vmx_bitmap[i]);
7774
7775         free_kvm_area();
7776 }
7777
7778 /*
7779  * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
7780  * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
7781  */
7782 static int handle_pause(struct kvm_vcpu *vcpu)
7783 {
7784         if (!kvm_pause_in_guest(vcpu->kvm))
7785                 grow_ple_window(vcpu);
7786
7787         /*
7788          * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
7789          * VM-execution control is ignored if CPL > 0. OTOH, KVM
7790          * never set PAUSE_EXITING and just set PLE if supported,
7791          * so the vcpu must be CPL=0 if it gets a PAUSE exit.
7792          */
7793         kvm_vcpu_on_spin(vcpu, true);
7794         return kvm_skip_emulated_instruction(vcpu);
7795 }
7796
7797 static int handle_nop(struct kvm_vcpu *vcpu)
7798 {
7799         return kvm_skip_emulated_instruction(vcpu);
7800 }
7801
7802 static int handle_mwait(struct kvm_vcpu *vcpu)
7803 {
7804         printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
7805         return handle_nop(vcpu);
7806 }
7807
7808 static int handle_invalid_op(struct kvm_vcpu *vcpu)
7809 {
7810         kvm_queue_exception(vcpu, UD_VECTOR);
7811         return 1;
7812 }
7813
7814 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
7815 {
7816         return 1;
7817 }
7818
7819 static int handle_monitor(struct kvm_vcpu *vcpu)
7820 {
7821         printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
7822         return handle_nop(vcpu);
7823 }
7824
7825 /*
7826  * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
7827  * set the success or error code of an emulated VMX instruction, as specified
7828  * by Vol 2B, VMX Instruction Reference, "Conventions".
7829  */
7830 static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
7831 {
7832         vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
7833                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
7834                             X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
7835 }
7836
7837 static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
7838 {
7839         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
7840                         & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
7841                             X86_EFLAGS_SF | X86_EFLAGS_OF))
7842                         | X86_EFLAGS_CF);
7843 }
7844
7845 static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
7846                                         u32 vm_instruction_error)
7847 {
7848         if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
7849                 /*
7850                  * failValid writes the error number to the current VMCS, which
7851                  * can't be done there isn't a current VMCS.
7852                  */
7853                 nested_vmx_failInvalid(vcpu);
7854                 return;
7855         }
7856         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
7857                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
7858                             X86_EFLAGS_SF | X86_EFLAGS_OF))
7859                         | X86_EFLAGS_ZF);
7860         get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
7861         /*
7862          * We don't need to force a shadow sync because
7863          * VM_INSTRUCTION_ERROR is not shadowed
7864          */
7865 }
7866
7867 static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
7868 {
7869         /* TODO: not to reset guest simply here. */
7870         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
7871         pr_debug_ratelimited("kvm: nested vmx abort, indicator %d\n", indicator);
7872 }
7873
7874 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
7875 {
7876         struct vcpu_vmx *vmx =
7877                 container_of(timer, struct vcpu_vmx, nested.preemption_timer);
7878
7879         vmx->nested.preemption_timer_expired = true;
7880         kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
7881         kvm_vcpu_kick(&vmx->vcpu);
7882
7883         return HRTIMER_NORESTART;
7884 }
7885
7886 /*
7887  * Decode the memory-address operand of a vmx instruction, as recorded on an
7888  * exit caused by such an instruction (run by a guest hypervisor).
7889  * On success, returns 0. When the operand is invalid, returns 1 and throws
7890  * #UD or #GP.
7891  */
7892 static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
7893                                  unsigned long exit_qualification,
7894                                  u32 vmx_instruction_info, bool wr, gva_t *ret)
7895 {
7896         gva_t off;
7897         bool exn;
7898         struct kvm_segment s;
7899
7900         /*
7901          * According to Vol. 3B, "Information for VM Exits Due to Instruction
7902          * Execution", on an exit, vmx_instruction_info holds most of the
7903          * addressing components of the operand. Only the displacement part
7904          * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
7905          * For how an actual address is calculated from all these components,
7906          * refer to Vol. 1, "Operand Addressing".
7907          */
7908         int  scaling = vmx_instruction_info & 3;
7909         int  addr_size = (vmx_instruction_info >> 7) & 7;
7910         bool is_reg = vmx_instruction_info & (1u << 10);
7911         int  seg_reg = (vmx_instruction_info >> 15) & 7;
7912         int  index_reg = (vmx_instruction_info >> 18) & 0xf;
7913         bool index_is_valid = !(vmx_instruction_info & (1u << 22));
7914         int  base_reg       = (vmx_instruction_info >> 23) & 0xf;
7915         bool base_is_valid  = !(vmx_instruction_info & (1u << 27));
7916
7917         if (is_reg) {
7918                 kvm_queue_exception(vcpu, UD_VECTOR);
7919                 return 1;
7920         }
7921
7922         /* Addr = segment_base + offset */
7923         /* offset = base + [index * scale] + displacement */
7924         off = exit_qualification; /* holds the displacement */
7925         if (base_is_valid)
7926                 off += kvm_register_read(vcpu, base_reg);
7927         if (index_is_valid)
7928                 off += kvm_register_read(vcpu, index_reg)<<scaling;
7929         vmx_get_segment(vcpu, &s, seg_reg);
7930         *ret = s.base + off;
7931
7932         if (addr_size == 1) /* 32 bit */
7933                 *ret &= 0xffffffff;
7934
7935         /* Checks for #GP/#SS exceptions. */
7936         exn = false;
7937         if (is_long_mode(vcpu)) {
7938                 /* Long mode: #GP(0)/#SS(0) if the memory address is in a
7939                  * non-canonical form. This is the only check on the memory
7940                  * destination for long mode!
7941                  */
7942                 exn = is_noncanonical_address(*ret, vcpu);
7943         } else if (is_protmode(vcpu)) {
7944                 /* Protected mode: apply checks for segment validity in the
7945                  * following order:
7946                  * - segment type check (#GP(0) may be thrown)
7947                  * - usability check (#GP(0)/#SS(0))
7948                  * - limit check (#GP(0)/#SS(0))
7949                  */
7950                 if (wr)
7951                         /* #GP(0) if the destination operand is located in a
7952                          * read-only data segment or any code segment.
7953                          */
7954                         exn = ((s.type & 0xa) == 0 || (s.type & 8));
7955                 else
7956                         /* #GP(0) if the source operand is located in an
7957                          * execute-only code segment
7958                          */
7959                         exn = ((s.type & 0xa) == 8);
7960                 if (exn) {
7961                         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
7962                         return 1;
7963                 }
7964                 /* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
7965                  */
7966                 exn = (s.unusable != 0);
7967                 /* Protected mode: #GP(0)/#SS(0) if the memory
7968                  * operand is outside the segment limit.
7969                  */
7970                 exn = exn || (off + sizeof(u64) > s.limit);
7971         }
7972         if (exn) {
7973                 kvm_queue_exception_e(vcpu,
7974                                       seg_reg == VCPU_SREG_SS ?
7975                                                 SS_VECTOR : GP_VECTOR,
7976                                       0);
7977                 return 1;
7978         }
7979
7980         return 0;
7981 }
7982
7983 static int nested_vmx_get_vmptr(struct kvm_vcpu *vcpu, gpa_t *vmpointer)
7984 {
7985         gva_t gva;
7986         struct x86_exception e;
7987
7988         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7989                         vmcs_read32(VMX_INSTRUCTION_INFO), false, &gva))
7990                 return 1;
7991
7992         if (kvm_read_guest_virt(vcpu, gva, vmpointer, sizeof(*vmpointer), &e)) {
7993                 kvm_inject_page_fault(vcpu, &e);
7994                 return 1;
7995         }
7996
7997         return 0;
7998 }
7999
8000 /*
8001  * Allocate a shadow VMCS and associate it with the currently loaded
8002  * VMCS, unless such a shadow VMCS already exists. The newly allocated
8003  * VMCS is also VMCLEARed, so that it is ready for use.
8004  */
8005 static struct vmcs *alloc_shadow_vmcs(struct kvm_vcpu *vcpu)
8006 {
8007         struct vcpu_vmx *vmx = to_vmx(vcpu);
8008         struct loaded_vmcs *loaded_vmcs = vmx->loaded_vmcs;
8009
8010         /*
8011          * We should allocate a shadow vmcs for vmcs01 only when L1
8012          * executes VMXON and free it when L1 executes VMXOFF.
8013          * As it is invalid to execute VMXON twice, we shouldn't reach
8014          * here when vmcs01 already have an allocated shadow vmcs.
8015          */
8016         WARN_ON(loaded_vmcs == &vmx->vmcs01 && loaded_vmcs->shadow_vmcs);
8017
8018         if (!loaded_vmcs->shadow_vmcs) {
8019                 loaded_vmcs->shadow_vmcs = alloc_vmcs(true);
8020                 if (loaded_vmcs->shadow_vmcs)
8021                         vmcs_clear(loaded_vmcs->shadow_vmcs);
8022         }
8023         return loaded_vmcs->shadow_vmcs;
8024 }
8025
8026 static int enter_vmx_operation(struct kvm_vcpu *vcpu)
8027 {
8028         struct vcpu_vmx *vmx = to_vmx(vcpu);
8029         int r;
8030
8031         r = alloc_loaded_vmcs(&vmx->nested.vmcs02);
8032         if (r < 0)
8033                 goto out_vmcs02;
8034
8035         vmx->nested.cached_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
8036         if (!vmx->nested.cached_vmcs12)
8037                 goto out_cached_vmcs12;
8038
8039         vmx->nested.cached_shadow_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
8040         if (!vmx->nested.cached_shadow_vmcs12)
8041                 goto out_cached_shadow_vmcs12;
8042
8043         if (enable_shadow_vmcs && !alloc_shadow_vmcs(vcpu))
8044                 goto out_shadow_vmcs;
8045
8046         hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
8047                      HRTIMER_MODE_REL_PINNED);
8048         vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
8049
8050         vmx->nested.vmxon = true;
8051         return 0;
8052
8053 out_shadow_vmcs:
8054         kfree(vmx->nested.cached_shadow_vmcs12);
8055
8056 out_cached_shadow_vmcs12:
8057         kfree(vmx->nested.cached_vmcs12);
8058
8059 out_cached_vmcs12:
8060         free_loaded_vmcs(&vmx->nested.vmcs02);
8061
8062 out_vmcs02:
8063         return -ENOMEM;
8064 }
8065
8066 /*
8067  * Emulate the VMXON instruction.
8068  * Currently, we just remember that VMX is active, and do not save or even
8069  * inspect the argument to VMXON (the so-called "VMXON pointer") because we
8070  * do not currently need to store anything in that guest-allocated memory
8071  * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
8072  * argument is different from the VMXON pointer (which the spec says they do).
8073  */
8074 static int handle_vmon(struct kvm_vcpu *vcpu)
8075 {
8076         int ret;
8077         gpa_t vmptr;
8078         struct page *page;
8079         struct vcpu_vmx *vmx = to_vmx(vcpu);
8080         const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
8081                 | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
8082
8083         /*
8084          * The Intel VMX Instruction Reference lists a bunch of bits that are
8085          * prerequisite to running VMXON, most notably cr4.VMXE must be set to
8086          * 1 (see vmx_set_cr4() for when we allow the guest to set this).
8087          * Otherwise, we should fail with #UD.  But most faulting conditions
8088          * have already been checked by hardware, prior to the VM-exit for
8089          * VMXON.  We do test guest cr4.VMXE because processor CR4 always has
8090          * that bit set to 1 in non-root mode.
8091          */
8092         if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) {
8093                 kvm_queue_exception(vcpu, UD_VECTOR);
8094                 return 1;
8095         }
8096
8097         /* CPL=0 must be checked manually. */
8098         if (vmx_get_cpl(vcpu)) {
8099                 kvm_inject_gp(vcpu, 0);
8100                 return 1;
8101         }
8102
8103         if (vmx->nested.vmxon) {
8104                 nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
8105                 return kvm_skip_emulated_instruction(vcpu);
8106         }
8107
8108         if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
8109                         != VMXON_NEEDED_FEATURES) {
8110                 kvm_inject_gp(vcpu, 0);
8111                 return 1;
8112         }
8113
8114         if (nested_vmx_get_vmptr(vcpu, &vmptr))
8115                 return 1;
8116
8117         /*
8118          * SDM 3: 24.11.5
8119          * The first 4 bytes of VMXON region contain the supported
8120          * VMCS revision identifier
8121          *
8122          * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
8123          * which replaces physical address width with 32
8124          */
8125         if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
8126                 nested_vmx_failInvalid(vcpu);
8127                 return kvm_skip_emulated_instruction(vcpu);
8128         }
8129
8130         page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
8131         if (is_error_page(page)) {
8132                 nested_vmx_failInvalid(vcpu);
8133                 return kvm_skip_emulated_instruction(vcpu);
8134         }
8135         if (*(u32 *)kmap(page) != VMCS12_REVISION) {
8136                 kunmap(page);
8137                 kvm_release_page_clean(page);
8138                 nested_vmx_failInvalid(vcpu);
8139                 return kvm_skip_emulated_instruction(vcpu);
8140         }
8141         kunmap(page);
8142         kvm_release_page_clean(page);
8143
8144         vmx->nested.vmxon_ptr = vmptr;
8145         ret = enter_vmx_operation(vcpu);
8146         if (ret)
8147                 return ret;
8148
8149         nested_vmx_succeed(vcpu);
8150         return kvm_skip_emulated_instruction(vcpu);
8151 }
8152
8153 /*
8154  * Intel's VMX Instruction Reference specifies a common set of prerequisites
8155  * for running VMX instructions (except VMXON, whose prerequisites are
8156  * slightly different). It also specifies what exception to inject otherwise.
8157  * Note that many of these exceptions have priority over VM exits, so they
8158  * don't have to be checked again here.
8159  */
8160 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
8161 {
8162         if (!to_vmx(vcpu)->nested.vmxon) {
8163                 kvm_queue_exception(vcpu, UD_VECTOR);
8164                 return 0;
8165         }
8166
8167         if (vmx_get_cpl(vcpu)) {
8168                 kvm_inject_gp(vcpu, 0);
8169                 return 0;
8170         }
8171
8172         return 1;
8173 }
8174
8175 static void vmx_disable_shadow_vmcs(struct vcpu_vmx *vmx)
8176 {
8177         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL, SECONDARY_EXEC_SHADOW_VMCS);
8178         vmcs_write64(VMCS_LINK_POINTER, -1ull);
8179 }
8180
8181 static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
8182 {
8183         if (vmx->nested.current_vmptr == -1ull)
8184                 return;
8185
8186         if (enable_shadow_vmcs) {
8187                 /* copy to memory all shadowed fields in case
8188                    they were modified */
8189                 copy_shadow_to_vmcs12(vmx);
8190                 vmx->nested.sync_shadow_vmcs = false;
8191                 vmx_disable_shadow_vmcs(vmx);
8192         }
8193         vmx->nested.posted_intr_nv = -1;
8194
8195         /* Flush VMCS12 to guest memory */
8196         kvm_vcpu_write_guest_page(&vmx->vcpu,
8197                                   vmx->nested.current_vmptr >> PAGE_SHIFT,
8198                                   vmx->nested.cached_vmcs12, 0, VMCS12_SIZE);
8199
8200         vmx->nested.current_vmptr = -1ull;
8201 }
8202
8203 /*
8204  * Free whatever needs to be freed from vmx->nested when L1 goes down, or
8205  * just stops using VMX.
8206  */
8207 static void free_nested(struct vcpu_vmx *vmx)
8208 {
8209         if (!vmx->nested.vmxon && !vmx->nested.smm.vmxon)
8210                 return;
8211
8212         vmx->nested.vmxon = false;
8213         vmx->nested.smm.vmxon = false;
8214         free_vpid(vmx->nested.vpid02);
8215         vmx->nested.posted_intr_nv = -1;
8216         vmx->nested.current_vmptr = -1ull;
8217         if (enable_shadow_vmcs) {
8218                 vmx_disable_shadow_vmcs(vmx);
8219                 vmcs_clear(vmx->vmcs01.shadow_vmcs);
8220                 free_vmcs(vmx->vmcs01.shadow_vmcs);
8221                 vmx->vmcs01.shadow_vmcs = NULL;
8222         }
8223         kfree(vmx->nested.cached_vmcs12);
8224         kfree(vmx->nested.cached_shadow_vmcs12);
8225         /* Unpin physical memory we referred to in the vmcs02 */
8226         if (vmx->nested.apic_access_page) {
8227                 kvm_release_page_dirty(vmx->nested.apic_access_page);
8228                 vmx->nested.apic_access_page = NULL;
8229         }
8230         if (vmx->nested.virtual_apic_page) {
8231                 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
8232                 vmx->nested.virtual_apic_page = NULL;
8233         }
8234         if (vmx->nested.pi_desc_page) {
8235                 kunmap(vmx->nested.pi_desc_page);
8236                 kvm_release_page_dirty(vmx->nested.pi_desc_page);
8237                 vmx->nested.pi_desc_page = NULL;
8238                 vmx->nested.pi_desc = NULL;
8239         }
8240
8241         free_loaded_vmcs(&vmx->nested.vmcs02);
8242 }
8243
8244 /* Emulate the VMXOFF instruction */
8245 static int handle_vmoff(struct kvm_vcpu *vcpu)
8246 {
8247         if (!nested_vmx_check_permission(vcpu))
8248                 return 1;
8249         free_nested(to_vmx(vcpu));
8250         nested_vmx_succeed(vcpu);
8251         return kvm_skip_emulated_instruction(vcpu);
8252 }
8253
8254 /* Emulate the VMCLEAR instruction */
8255 static int handle_vmclear(struct kvm_vcpu *vcpu)
8256 {
8257         struct vcpu_vmx *vmx = to_vmx(vcpu);
8258         u32 zero = 0;
8259         gpa_t vmptr;
8260
8261         if (!nested_vmx_check_permission(vcpu))
8262                 return 1;
8263
8264         if (nested_vmx_get_vmptr(vcpu, &vmptr))
8265                 return 1;
8266
8267         if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
8268                 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS);
8269                 return kvm_skip_emulated_instruction(vcpu);
8270         }
8271
8272         if (vmptr == vmx->nested.vmxon_ptr) {
8273                 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_VMXON_POINTER);
8274                 return kvm_skip_emulated_instruction(vcpu);
8275         }
8276
8277         if (vmptr == vmx->nested.current_vmptr)
8278                 nested_release_vmcs12(vmx);
8279
8280         kvm_vcpu_write_guest(vcpu,
8281                         vmptr + offsetof(struct vmcs12, launch_state),
8282                         &zero, sizeof(zero));
8283
8284         nested_vmx_succeed(vcpu);
8285         return kvm_skip_emulated_instruction(vcpu);
8286 }
8287
8288 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
8289
8290 /* Emulate the VMLAUNCH instruction */
8291 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
8292 {
8293         return nested_vmx_run(vcpu, true);
8294 }
8295
8296 /* Emulate the VMRESUME instruction */
8297 static int handle_vmresume(struct kvm_vcpu *vcpu)
8298 {
8299
8300         return nested_vmx_run(vcpu, false);
8301 }
8302
8303 /*
8304  * Read a vmcs12 field. Since these can have varying lengths and we return
8305  * one type, we chose the biggest type (u64) and zero-extend the return value
8306  * to that size. Note that the caller, handle_vmread, might need to use only
8307  * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
8308  * 64-bit fields are to be returned).
8309  */
8310 static inline int vmcs12_read_any(struct vmcs12 *vmcs12,
8311                                   unsigned long field, u64 *ret)
8312 {
8313         short offset = vmcs_field_to_offset(field);
8314         char *p;
8315
8316         if (offset < 0)
8317                 return offset;
8318
8319         p = (char *)vmcs12 + offset;
8320
8321         switch (vmcs_field_width(field)) {
8322         case VMCS_FIELD_WIDTH_NATURAL_WIDTH:
8323                 *ret = *((natural_width *)p);
8324                 return 0;
8325         case VMCS_FIELD_WIDTH_U16:
8326                 *ret = *((u16 *)p);
8327                 return 0;
8328         case VMCS_FIELD_WIDTH_U32:
8329                 *ret = *((u32 *)p);
8330                 return 0;
8331         case VMCS_FIELD_WIDTH_U64:
8332                 *ret = *((u64 *)p);
8333                 return 0;
8334         default:
8335                 WARN_ON(1);
8336                 return -ENOENT;
8337         }
8338 }
8339
8340
8341 static inline int vmcs12_write_any(struct vmcs12 *vmcs12,
8342                                    unsigned long field, u64 field_value){
8343         short offset = vmcs_field_to_offset(field);
8344         char *p = (char *)vmcs12 + offset;
8345         if (offset < 0)
8346                 return offset;
8347
8348         switch (vmcs_field_width(field)) {
8349         case VMCS_FIELD_WIDTH_U16:
8350                 *(u16 *)p = field_value;
8351                 return 0;
8352         case VMCS_FIELD_WIDTH_U32:
8353                 *(u32 *)p = field_value;
8354                 return 0;
8355         case VMCS_FIELD_WIDTH_U64:
8356                 *(u64 *)p = field_value;
8357                 return 0;
8358         case VMCS_FIELD_WIDTH_NATURAL_WIDTH:
8359                 *(natural_width *)p = field_value;
8360                 return 0;
8361         default:
8362                 WARN_ON(1);
8363                 return -ENOENT;
8364         }
8365
8366 }
8367
8368 /*
8369  * Copy the writable VMCS shadow fields back to the VMCS12, in case
8370  * they have been modified by the L1 guest. Note that the "read-only"
8371  * VM-exit information fields are actually writable if the vCPU is
8372  * configured to support "VMWRITE to any supported field in the VMCS."
8373  */
8374 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
8375 {
8376         const u16 *fields[] = {
8377                 shadow_read_write_fields,
8378                 shadow_read_only_fields
8379         };
8380         const int max_fields[] = {
8381                 max_shadow_read_write_fields,
8382                 max_shadow_read_only_fields
8383         };
8384         int i, q;
8385         unsigned long field;
8386         u64 field_value;
8387         struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
8388
8389         preempt_disable();
8390
8391         vmcs_load(shadow_vmcs);
8392
8393         for (q = 0; q < ARRAY_SIZE(fields); q++) {
8394                 for (i = 0; i < max_fields[q]; i++) {
8395                         field = fields[q][i];
8396                         field_value = __vmcs_readl(field);
8397                         vmcs12_write_any(get_vmcs12(&vmx->vcpu), field, field_value);
8398                 }
8399                 /*
8400                  * Skip the VM-exit information fields if they are read-only.
8401                  */
8402                 if (!nested_cpu_has_vmwrite_any_field(&vmx->vcpu))
8403                         break;
8404         }
8405
8406         vmcs_clear(shadow_vmcs);
8407         vmcs_load(vmx->loaded_vmcs->vmcs);
8408
8409         preempt_enable();
8410 }
8411
8412 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
8413 {
8414         const u16 *fields[] = {
8415                 shadow_read_write_fields,
8416                 shadow_read_only_fields
8417         };
8418         const int max_fields[] = {
8419                 max_shadow_read_write_fields,
8420                 max_shadow_read_only_fields
8421         };
8422         int i, q;
8423         unsigned long field;
8424         u64 field_value = 0;
8425         struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
8426
8427         vmcs_load(shadow_vmcs);
8428
8429         for (q = 0; q < ARRAY_SIZE(fields); q++) {
8430                 for (i = 0; i < max_fields[q]; i++) {
8431                         field = fields[q][i];
8432                         vmcs12_read_any(get_vmcs12(&vmx->vcpu), field, &field_value);
8433                         __vmcs_writel(field, field_value);
8434                 }
8435         }
8436
8437         vmcs_clear(shadow_vmcs);
8438         vmcs_load(vmx->loaded_vmcs->vmcs);
8439 }
8440
8441 /*
8442  * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
8443  * used before) all generate the same failure when it is missing.
8444  */
8445 static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
8446 {
8447         struct vcpu_vmx *vmx = to_vmx(vcpu);
8448         if (vmx->nested.current_vmptr == -1ull) {
8449                 nested_vmx_failInvalid(vcpu);
8450                 return 0;
8451         }
8452         return 1;
8453 }
8454
8455 static int handle_vmread(struct kvm_vcpu *vcpu)
8456 {
8457         unsigned long field;
8458         u64 field_value;
8459         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8460         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8461         gva_t gva = 0;
8462         struct vmcs12 *vmcs12;
8463
8464         if (!nested_vmx_check_permission(vcpu))
8465                 return 1;
8466
8467         if (!nested_vmx_check_vmcs12(vcpu))
8468                 return kvm_skip_emulated_instruction(vcpu);
8469
8470         if (!is_guest_mode(vcpu))
8471                 vmcs12 = get_vmcs12(vcpu);
8472         else {
8473                 /*
8474                  * When vmcs->vmcs_link_pointer is -1ull, any VMREAD
8475                  * to shadowed-field sets the ALU flags for VMfailInvalid.
8476                  */
8477                 if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull) {
8478                         nested_vmx_failInvalid(vcpu);
8479                         return kvm_skip_emulated_instruction(vcpu);
8480                 }
8481                 vmcs12 = get_shadow_vmcs12(vcpu);
8482         }
8483
8484         /* Decode instruction info and find the field to read */
8485         field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
8486         /* Read the field, zero-extended to a u64 field_value */
8487         if (vmcs12_read_any(vmcs12, field, &field_value) < 0) {
8488                 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
8489                 return kvm_skip_emulated_instruction(vcpu);
8490         }
8491         /*
8492          * Now copy part of this value to register or memory, as requested.
8493          * Note that the number of bits actually copied is 32 or 64 depending
8494          * on the guest's mode (32 or 64 bit), not on the given field's length.
8495          */
8496         if (vmx_instruction_info & (1u << 10)) {
8497                 kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
8498                         field_value);
8499         } else {
8500                 if (get_vmx_mem_address(vcpu, exit_qualification,
8501                                 vmx_instruction_info, true, &gva))
8502                         return 1;
8503                 /* _system ok, nested_vmx_check_permission has verified cpl=0 */
8504                 kvm_write_guest_virt_system(vcpu, gva, &field_value,
8505                                             (is_long_mode(vcpu) ? 8 : 4), NULL);
8506         }
8507
8508         nested_vmx_succeed(vcpu);
8509         return kvm_skip_emulated_instruction(vcpu);
8510 }
8511
8512
8513 static int handle_vmwrite(struct kvm_vcpu *vcpu)
8514 {
8515         unsigned long field;
8516         gva_t gva;
8517         struct vcpu_vmx *vmx = to_vmx(vcpu);
8518         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8519         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8520
8521         /* The value to write might be 32 or 64 bits, depending on L1's long
8522          * mode, and eventually we need to write that into a field of several
8523          * possible lengths. The code below first zero-extends the value to 64
8524          * bit (field_value), and then copies only the appropriate number of
8525          * bits into the vmcs12 field.
8526          */
8527         u64 field_value = 0;
8528         struct x86_exception e;
8529         struct vmcs12 *vmcs12;
8530
8531         if (!nested_vmx_check_permission(vcpu))
8532                 return 1;
8533
8534         if (!nested_vmx_check_vmcs12(vcpu))
8535                 return kvm_skip_emulated_instruction(vcpu);
8536
8537         if (vmx_instruction_info & (1u << 10))
8538                 field_value = kvm_register_readl(vcpu,
8539                         (((vmx_instruction_info) >> 3) & 0xf));
8540         else {
8541                 if (get_vmx_mem_address(vcpu, exit_qualification,
8542                                 vmx_instruction_info, false, &gva))
8543                         return 1;
8544                 if (kvm_read_guest_virt(vcpu, gva, &field_value,
8545                                         (is_64_bit_mode(vcpu) ? 8 : 4), &e)) {
8546                         kvm_inject_page_fault(vcpu, &e);
8547                         return 1;
8548                 }
8549         }
8550
8551
8552         field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
8553         /*
8554          * If the vCPU supports "VMWRITE to any supported field in the
8555          * VMCS," then the "read-only" fields are actually read/write.
8556          */
8557         if (vmcs_field_readonly(field) &&
8558             !nested_cpu_has_vmwrite_any_field(vcpu)) {
8559                 nested_vmx_failValid(vcpu,
8560                         VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
8561                 return kvm_skip_emulated_instruction(vcpu);
8562         }
8563
8564         if (!is_guest_mode(vcpu))
8565                 vmcs12 = get_vmcs12(vcpu);
8566         else {
8567                 /*
8568                  * When vmcs->vmcs_link_pointer is -1ull, any VMWRITE
8569                  * to shadowed-field sets the ALU flags for VMfailInvalid.
8570                  */
8571                 if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull) {
8572                         nested_vmx_failInvalid(vcpu);
8573                         return kvm_skip_emulated_instruction(vcpu);
8574                 }
8575                 vmcs12 = get_shadow_vmcs12(vcpu);
8576
8577         }
8578
8579         if (vmcs12_write_any(vmcs12, field, field_value) < 0) {
8580                 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
8581                 return kvm_skip_emulated_instruction(vcpu);
8582         }
8583
8584         /*
8585          * Do not track vmcs12 dirty-state if in guest-mode
8586          * as we actually dirty shadow vmcs12 instead of vmcs12.
8587          */
8588         if (!is_guest_mode(vcpu)) {
8589                 switch (field) {
8590 #define SHADOW_FIELD_RW(x) case x:
8591 #include "vmx_shadow_fields.h"
8592                         /*
8593                          * The fields that can be updated by L1 without a vmexit are
8594                          * always updated in the vmcs02, the others go down the slow
8595                          * path of prepare_vmcs02.
8596                          */
8597                         break;
8598                 default:
8599                         vmx->nested.dirty_vmcs12 = true;
8600                         break;
8601                 }
8602         }
8603
8604         nested_vmx_succeed(vcpu);
8605         return kvm_skip_emulated_instruction(vcpu);
8606 }
8607
8608 static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
8609 {
8610         vmx->nested.current_vmptr = vmptr;
8611         if (enable_shadow_vmcs) {
8612                 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
8613                               SECONDARY_EXEC_SHADOW_VMCS);
8614                 vmcs_write64(VMCS_LINK_POINTER,
8615                              __pa(vmx->vmcs01.shadow_vmcs));
8616                 vmx->nested.sync_shadow_vmcs = true;
8617         }
8618         vmx->nested.dirty_vmcs12 = true;
8619 }
8620
8621 /* Emulate the VMPTRLD instruction */
8622 static int handle_vmptrld(struct kvm_vcpu *vcpu)
8623 {
8624         struct vcpu_vmx *vmx = to_vmx(vcpu);
8625         gpa_t vmptr;
8626
8627         if (!nested_vmx_check_permission(vcpu))
8628                 return 1;
8629
8630         if (nested_vmx_get_vmptr(vcpu, &vmptr))
8631                 return 1;
8632
8633         if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
8634                 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS);
8635                 return kvm_skip_emulated_instruction(vcpu);
8636         }
8637
8638         if (vmptr == vmx->nested.vmxon_ptr) {
8639                 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_VMXON_POINTER);
8640                 return kvm_skip_emulated_instruction(vcpu);
8641         }
8642
8643         if (vmx->nested.current_vmptr != vmptr) {
8644                 struct vmcs12 *new_vmcs12;
8645                 struct page *page;
8646                 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
8647                 if (is_error_page(page)) {
8648                         nested_vmx_failInvalid(vcpu);
8649                         return kvm_skip_emulated_instruction(vcpu);
8650                 }
8651                 new_vmcs12 = kmap(page);
8652                 if (new_vmcs12->hdr.revision_id != VMCS12_REVISION ||
8653                     (new_vmcs12->hdr.shadow_vmcs &&
8654                      !nested_cpu_has_vmx_shadow_vmcs(vcpu))) {
8655                         kunmap(page);
8656                         kvm_release_page_clean(page);
8657                         nested_vmx_failValid(vcpu,
8658                                 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
8659                         return kvm_skip_emulated_instruction(vcpu);
8660                 }
8661
8662                 nested_release_vmcs12(vmx);
8663                 /*
8664                  * Load VMCS12 from guest memory since it is not already
8665                  * cached.
8666                  */
8667                 memcpy(vmx->nested.cached_vmcs12, new_vmcs12, VMCS12_SIZE);
8668                 kunmap(page);
8669                 kvm_release_page_clean(page);
8670
8671                 set_current_vmptr(vmx, vmptr);
8672         }
8673
8674         nested_vmx_succeed(vcpu);
8675         return kvm_skip_emulated_instruction(vcpu);
8676 }
8677
8678 /* Emulate the VMPTRST instruction */
8679 static int handle_vmptrst(struct kvm_vcpu *vcpu)
8680 {
8681         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8682         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8683         gva_t vmcs_gva;
8684         struct x86_exception e;
8685
8686         if (!nested_vmx_check_permission(vcpu))
8687                 return 1;
8688
8689         if (get_vmx_mem_address(vcpu, exit_qualification,
8690                         vmx_instruction_info, true, &vmcs_gva))
8691                 return 1;
8692         /* *_system ok, nested_vmx_check_permission has verified cpl=0 */
8693         if (kvm_write_guest_virt_system(vcpu, vmcs_gva,
8694                                         (void *)&to_vmx(vcpu)->nested.current_vmptr,
8695                                         sizeof(u64), &e)) {
8696                 kvm_inject_page_fault(vcpu, &e);
8697                 return 1;
8698         }
8699         nested_vmx_succeed(vcpu);
8700         return kvm_skip_emulated_instruction(vcpu);
8701 }
8702
8703 /* Emulate the INVEPT instruction */
8704 static int handle_invept(struct kvm_vcpu *vcpu)
8705 {
8706         struct vcpu_vmx *vmx = to_vmx(vcpu);
8707         u32 vmx_instruction_info, types;
8708         unsigned long type;
8709         gva_t gva;
8710         struct x86_exception e;
8711         struct {
8712                 u64 eptp, gpa;
8713         } operand;
8714
8715         if (!(vmx->nested.msrs.secondary_ctls_high &
8716               SECONDARY_EXEC_ENABLE_EPT) ||
8717             !(vmx->nested.msrs.ept_caps & VMX_EPT_INVEPT_BIT)) {
8718                 kvm_queue_exception(vcpu, UD_VECTOR);
8719                 return 1;
8720         }
8721
8722         if (!nested_vmx_check_permission(vcpu))
8723                 return 1;
8724
8725         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8726         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
8727
8728         types = (vmx->nested.msrs.ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
8729
8730         if (type >= 32 || !(types & (1 << type))) {
8731                 nested_vmx_failValid(vcpu,
8732                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8733                 return kvm_skip_emulated_instruction(vcpu);
8734         }
8735
8736         /* According to the Intel VMX instruction reference, the memory
8737          * operand is read even if it isn't needed (e.g., for type==global)
8738          */
8739         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
8740                         vmx_instruction_info, false, &gva))
8741                 return 1;
8742         if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
8743                 kvm_inject_page_fault(vcpu, &e);
8744                 return 1;
8745         }
8746
8747         switch (type) {
8748         case VMX_EPT_EXTENT_GLOBAL:
8749         /*
8750          * TODO: track mappings and invalidate
8751          * single context requests appropriately
8752          */
8753         case VMX_EPT_EXTENT_CONTEXT:
8754                 kvm_mmu_sync_roots(vcpu);
8755                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
8756                 nested_vmx_succeed(vcpu);
8757                 break;
8758         default:
8759                 BUG_ON(1);
8760                 break;
8761         }
8762
8763         return kvm_skip_emulated_instruction(vcpu);
8764 }
8765
8766 static int handle_invvpid(struct kvm_vcpu *vcpu)
8767 {
8768         struct vcpu_vmx *vmx = to_vmx(vcpu);
8769         u32 vmx_instruction_info;
8770         unsigned long type, types;
8771         gva_t gva;
8772         struct x86_exception e;
8773         struct {
8774                 u64 vpid;
8775                 u64 gla;
8776         } operand;
8777
8778         if (!(vmx->nested.msrs.secondary_ctls_high &
8779               SECONDARY_EXEC_ENABLE_VPID) ||
8780                         !(vmx->nested.msrs.vpid_caps & VMX_VPID_INVVPID_BIT)) {
8781                 kvm_queue_exception(vcpu, UD_VECTOR);
8782                 return 1;
8783         }
8784
8785         if (!nested_vmx_check_permission(vcpu))
8786                 return 1;
8787
8788         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8789         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
8790
8791         types = (vmx->nested.msrs.vpid_caps &
8792                         VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
8793
8794         if (type >= 32 || !(types & (1 << type))) {
8795                 nested_vmx_failValid(vcpu,
8796                         VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8797                 return kvm_skip_emulated_instruction(vcpu);
8798         }
8799
8800         /* according to the intel vmx instruction reference, the memory
8801          * operand is read even if it isn't needed (e.g., for type==global)
8802          */
8803         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
8804                         vmx_instruction_info, false, &gva))
8805                 return 1;
8806         if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
8807                 kvm_inject_page_fault(vcpu, &e);
8808                 return 1;
8809         }
8810         if (operand.vpid >> 16) {
8811                 nested_vmx_failValid(vcpu,
8812                         VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8813                 return kvm_skip_emulated_instruction(vcpu);
8814         }
8815
8816         switch (type) {
8817         case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
8818                 if (!operand.vpid ||
8819                     is_noncanonical_address(operand.gla, vcpu)) {
8820                         nested_vmx_failValid(vcpu,
8821                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8822                         return kvm_skip_emulated_instruction(vcpu);
8823                 }
8824                 if (cpu_has_vmx_invvpid_individual_addr() &&
8825                     vmx->nested.vpid02) {
8826                         __invvpid(VMX_VPID_EXTENT_INDIVIDUAL_ADDR,
8827                                 vmx->nested.vpid02, operand.gla);
8828                 } else
8829                         __vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
8830                 break;
8831         case VMX_VPID_EXTENT_SINGLE_CONTEXT:
8832         case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
8833                 if (!operand.vpid) {
8834                         nested_vmx_failValid(vcpu,
8835                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8836                         return kvm_skip_emulated_instruction(vcpu);
8837                 }
8838                 __vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
8839                 break;
8840         case VMX_VPID_EXTENT_ALL_CONTEXT:
8841                 __vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
8842                 break;
8843         default:
8844                 WARN_ON_ONCE(1);
8845                 return kvm_skip_emulated_instruction(vcpu);
8846         }
8847
8848         nested_vmx_succeed(vcpu);
8849
8850         return kvm_skip_emulated_instruction(vcpu);
8851 }
8852
8853 static int handle_invpcid(struct kvm_vcpu *vcpu)
8854 {
8855         u32 vmx_instruction_info;
8856         unsigned long type;
8857         bool pcid_enabled;
8858         gva_t gva;
8859         struct x86_exception e;
8860         unsigned i;
8861         unsigned long roots_to_free = 0;
8862         struct {
8863                 u64 pcid;
8864                 u64 gla;
8865         } operand;
8866
8867         if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
8868                 kvm_queue_exception(vcpu, UD_VECTOR);
8869                 return 1;
8870         }
8871
8872         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8873         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
8874
8875         if (type > 3) {
8876                 kvm_inject_gp(vcpu, 0);
8877                 return 1;
8878         }
8879
8880         /* According to the Intel instruction reference, the memory operand
8881          * is read even if it isn't needed (e.g., for type==all)
8882          */
8883         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
8884                                 vmx_instruction_info, false, &gva))
8885                 return 1;
8886
8887         if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
8888                 kvm_inject_page_fault(vcpu, &e);
8889                 return 1;
8890         }
8891
8892         if (operand.pcid >> 12 != 0) {
8893                 kvm_inject_gp(vcpu, 0);
8894                 return 1;
8895         }
8896
8897         pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
8898
8899         switch (type) {
8900         case INVPCID_TYPE_INDIV_ADDR:
8901                 if ((!pcid_enabled && (operand.pcid != 0)) ||
8902                     is_noncanonical_address(operand.gla, vcpu)) {
8903                         kvm_inject_gp(vcpu, 0);
8904                         return 1;
8905                 }
8906                 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
8907                 return kvm_skip_emulated_instruction(vcpu);
8908
8909         case INVPCID_TYPE_SINGLE_CTXT:
8910                 if (!pcid_enabled && (operand.pcid != 0)) {
8911                         kvm_inject_gp(vcpu, 0);
8912                         return 1;
8913                 }
8914
8915                 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
8916                         kvm_mmu_sync_roots(vcpu);
8917                         kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
8918                 }
8919
8920                 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
8921                         if (kvm_get_pcid(vcpu, vcpu->arch.mmu.prev_roots[i].cr3)
8922                             == operand.pcid)
8923                                 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
8924
8925                 kvm_mmu_free_roots(vcpu, roots_to_free);
8926                 /*
8927                  * If neither the current cr3 nor any of the prev_roots use the
8928                  * given PCID, then nothing needs to be done here because a
8929                  * resync will happen anyway before switching to any other CR3.
8930                  */
8931
8932                 return kvm_skip_emulated_instruction(vcpu);
8933
8934         case INVPCID_TYPE_ALL_NON_GLOBAL:
8935                 /*
8936                  * Currently, KVM doesn't mark global entries in the shadow
8937                  * page tables, so a non-global flush just degenerates to a
8938                  * global flush. If needed, we could optimize this later by
8939                  * keeping track of global entries in shadow page tables.
8940                  */
8941
8942                 /* fall-through */
8943         case INVPCID_TYPE_ALL_INCL_GLOBAL:
8944                 kvm_mmu_unload(vcpu);
8945                 return kvm_skip_emulated_instruction(vcpu);
8946
8947         default:
8948                 BUG(); /* We have already checked above that type <= 3 */
8949         }
8950 }
8951
8952 static int handle_pml_full(struct kvm_vcpu *vcpu)
8953 {
8954         unsigned long exit_qualification;
8955
8956         trace_kvm_pml_full(vcpu->vcpu_id);
8957
8958         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8959
8960         /*
8961          * PML buffer FULL happened while executing iret from NMI,
8962          * "blocked by NMI" bit has to be set before next VM entry.
8963          */
8964         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
8965                         enable_vnmi &&
8966                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
8967                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
8968                                 GUEST_INTR_STATE_NMI);
8969
8970         /*
8971          * PML buffer already flushed at beginning of VMEXIT. Nothing to do
8972          * here.., and there's no userspace involvement needed for PML.
8973          */
8974         return 1;
8975 }
8976
8977 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
8978 {
8979         kvm_lapic_expired_hv_timer(vcpu);
8980         return 1;
8981 }
8982
8983 static bool valid_ept_address(struct kvm_vcpu *vcpu, u64 address)
8984 {
8985         struct vcpu_vmx *vmx = to_vmx(vcpu);
8986         int maxphyaddr = cpuid_maxphyaddr(vcpu);
8987
8988         /* Check for memory type validity */
8989         switch (address & VMX_EPTP_MT_MASK) {
8990         case VMX_EPTP_MT_UC:
8991                 if (!(vmx->nested.msrs.ept_caps & VMX_EPTP_UC_BIT))
8992                         return false;
8993                 break;
8994         case VMX_EPTP_MT_WB:
8995                 if (!(vmx->nested.msrs.ept_caps & VMX_EPTP_WB_BIT))
8996                         return false;
8997                 break;
8998         default:
8999                 return false;
9000         }
9001
9002         /* only 4 levels page-walk length are valid */
9003         if ((address & VMX_EPTP_PWL_MASK) != VMX_EPTP_PWL_4)
9004                 return false;
9005
9006         /* Reserved bits should not be set */
9007         if (address >> maxphyaddr || ((address >> 7) & 0x1f))
9008                 return false;
9009
9010         /* AD, if set, should be supported */
9011         if (address & VMX_EPTP_AD_ENABLE_BIT) {
9012                 if (!(vmx->nested.msrs.ept_caps & VMX_EPT_AD_BIT))
9013                         return false;
9014         }
9015
9016         return true;
9017 }
9018
9019 static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
9020                                      struct vmcs12 *vmcs12)
9021 {
9022         u32 index = vcpu->arch.regs[VCPU_REGS_RCX];
9023         u64 address;
9024         bool accessed_dirty;
9025         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
9026
9027         if (!nested_cpu_has_eptp_switching(vmcs12) ||
9028             !nested_cpu_has_ept(vmcs12))
9029                 return 1;
9030
9031         if (index >= VMFUNC_EPTP_ENTRIES)
9032                 return 1;
9033
9034
9035         if (kvm_vcpu_read_guest_page(vcpu, vmcs12->eptp_list_address >> PAGE_SHIFT,
9036                                      &address, index * 8, 8))
9037                 return 1;
9038
9039         accessed_dirty = !!(address & VMX_EPTP_AD_ENABLE_BIT);
9040
9041         /*
9042          * If the (L2) guest does a vmfunc to the currently
9043          * active ept pointer, we don't have to do anything else
9044          */
9045         if (vmcs12->ept_pointer != address) {
9046                 if (!valid_ept_address(vcpu, address))
9047                         return 1;
9048
9049                 kvm_mmu_unload(vcpu);
9050                 mmu->ept_ad = accessed_dirty;
9051                 mmu->base_role.ad_disabled = !accessed_dirty;
9052                 vmcs12->ept_pointer = address;
9053                 /*
9054                  * TODO: Check what's the correct approach in case
9055                  * mmu reload fails. Currently, we just let the next
9056                  * reload potentially fail
9057                  */
9058                 kvm_mmu_reload(vcpu);
9059         }
9060
9061         return 0;
9062 }
9063
9064 static int handle_vmfunc(struct kvm_vcpu *vcpu)
9065 {
9066         struct vcpu_vmx *vmx = to_vmx(vcpu);
9067         struct vmcs12 *vmcs12;
9068         u32 function = vcpu->arch.regs[VCPU_REGS_RAX];
9069
9070         /*
9071          * VMFUNC is only supported for nested guests, but we always enable the
9072          * secondary control for simplicity; for non-nested mode, fake that we
9073          * didn't by injecting #UD.
9074          */
9075         if (!is_guest_mode(vcpu)) {
9076                 kvm_queue_exception(vcpu, UD_VECTOR);
9077                 return 1;
9078         }
9079
9080         vmcs12 = get_vmcs12(vcpu);
9081         if ((vmcs12->vm_function_control & (1 << function)) == 0)
9082                 goto fail;
9083
9084         switch (function) {
9085         case 0:
9086                 if (nested_vmx_eptp_switching(vcpu, vmcs12))
9087                         goto fail;
9088                 break;
9089         default:
9090                 goto fail;
9091         }
9092         return kvm_skip_emulated_instruction(vcpu);
9093
9094 fail:
9095         nested_vmx_vmexit(vcpu, vmx->exit_reason,
9096                           vmcs_read32(VM_EXIT_INTR_INFO),
9097                           vmcs_readl(EXIT_QUALIFICATION));
9098         return 1;
9099 }
9100
9101 /*
9102  * The exit handlers return 1 if the exit was handled fully and guest execution
9103  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
9104  * to be done to userspace and return 0.
9105  */
9106 static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
9107         [EXIT_REASON_EXCEPTION_NMI]           = handle_exception,
9108         [EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
9109         [EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
9110         [EXIT_REASON_NMI_WINDOW]              = handle_nmi_window,
9111         [EXIT_REASON_IO_INSTRUCTION]          = handle_io,
9112         [EXIT_REASON_CR_ACCESS]               = handle_cr,
9113         [EXIT_REASON_DR_ACCESS]               = handle_dr,
9114         [EXIT_REASON_CPUID]                   = handle_cpuid,
9115         [EXIT_REASON_MSR_READ]                = handle_rdmsr,
9116         [EXIT_REASON_MSR_WRITE]               = handle_wrmsr,
9117         [EXIT_REASON_PENDING_INTERRUPT]       = handle_interrupt_window,
9118         [EXIT_REASON_HLT]                     = handle_halt,
9119         [EXIT_REASON_INVD]                    = handle_invd,
9120         [EXIT_REASON_INVLPG]                  = handle_invlpg,
9121         [EXIT_REASON_RDPMC]                   = handle_rdpmc,
9122         [EXIT_REASON_VMCALL]                  = handle_vmcall,
9123         [EXIT_REASON_VMCLEAR]                 = handle_vmclear,
9124         [EXIT_REASON_VMLAUNCH]                = handle_vmlaunch,
9125         [EXIT_REASON_VMPTRLD]                 = handle_vmptrld,
9126         [EXIT_REASON_VMPTRST]                 = handle_vmptrst,
9127         [EXIT_REASON_VMREAD]                  = handle_vmread,
9128         [EXIT_REASON_VMRESUME]                = handle_vmresume,
9129         [EXIT_REASON_VMWRITE]                 = handle_vmwrite,
9130         [EXIT_REASON_VMOFF]                   = handle_vmoff,
9131         [EXIT_REASON_VMON]                    = handle_vmon,
9132         [EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
9133         [EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
9134         [EXIT_REASON_APIC_WRITE]              = handle_apic_write,
9135         [EXIT_REASON_EOI_INDUCED]             = handle_apic_eoi_induced,
9136         [EXIT_REASON_WBINVD]                  = handle_wbinvd,
9137         [EXIT_REASON_XSETBV]                  = handle_xsetbv,
9138         [EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
9139         [EXIT_REASON_MCE_DURING_VMENTRY]      = handle_machine_check,
9140         [EXIT_REASON_GDTR_IDTR]               = handle_desc,
9141         [EXIT_REASON_LDTR_TR]                 = handle_desc,
9142         [EXIT_REASON_EPT_VIOLATION]           = handle_ept_violation,
9143         [EXIT_REASON_EPT_MISCONFIG]           = handle_ept_misconfig,
9144         [EXIT_REASON_PAUSE_INSTRUCTION]       = handle_pause,
9145         [EXIT_REASON_MWAIT_INSTRUCTION]       = handle_mwait,
9146         [EXIT_REASON_MONITOR_TRAP_FLAG]       = handle_monitor_trap,
9147         [EXIT_REASON_MONITOR_INSTRUCTION]     = handle_monitor,
9148         [EXIT_REASON_INVEPT]                  = handle_invept,
9149         [EXIT_REASON_INVVPID]                 = handle_invvpid,
9150         [EXIT_REASON_RDRAND]                  = handle_invalid_op,
9151         [EXIT_REASON_RDSEED]                  = handle_invalid_op,
9152         [EXIT_REASON_XSAVES]                  = handle_xsaves,
9153         [EXIT_REASON_XRSTORS]                 = handle_xrstors,
9154         [EXIT_REASON_PML_FULL]                = handle_pml_full,
9155         [EXIT_REASON_INVPCID]                 = handle_invpcid,
9156         [EXIT_REASON_VMFUNC]                  = handle_vmfunc,
9157         [EXIT_REASON_PREEMPTION_TIMER]        = handle_preemption_timer,
9158 };
9159
9160 static const int kvm_vmx_max_exit_handlers =
9161         ARRAY_SIZE(kvm_vmx_exit_handlers);
9162
9163 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
9164                                        struct vmcs12 *vmcs12)
9165 {
9166         unsigned long exit_qualification;
9167         gpa_t bitmap, last_bitmap;
9168         unsigned int port;
9169         int size;
9170         u8 b;
9171
9172         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
9173                 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
9174
9175         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9176
9177         port = exit_qualification >> 16;
9178         size = (exit_qualification & 7) + 1;
9179
9180         last_bitmap = (gpa_t)-1;
9181         b = -1;
9182
9183         while (size > 0) {
9184                 if (port < 0x8000)
9185                         bitmap = vmcs12->io_bitmap_a;
9186                 else if (port < 0x10000)
9187                         bitmap = vmcs12->io_bitmap_b;
9188                 else
9189                         return true;
9190                 bitmap += (port & 0x7fff) / 8;
9191
9192                 if (last_bitmap != bitmap)
9193                         if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
9194                                 return true;
9195                 if (b & (1 << (port & 7)))
9196                         return true;
9197
9198                 port++;
9199                 size--;
9200                 last_bitmap = bitmap;
9201         }
9202
9203         return false;
9204 }
9205
9206 /*
9207  * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
9208  * rather than handle it ourselves in L0. I.e., check whether L1 expressed
9209  * disinterest in the current event (read or write a specific MSR) by using an
9210  * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
9211  */
9212 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
9213         struct vmcs12 *vmcs12, u32 exit_reason)
9214 {
9215         u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
9216         gpa_t bitmap;
9217
9218         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
9219                 return true;
9220
9221         /*
9222          * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
9223          * for the four combinations of read/write and low/high MSR numbers.
9224          * First we need to figure out which of the four to use:
9225          */
9226         bitmap = vmcs12->msr_bitmap;
9227         if (exit_reason == EXIT_REASON_MSR_WRITE)
9228                 bitmap += 2048;
9229         if (msr_index >= 0xc0000000) {
9230                 msr_index -= 0xc0000000;
9231                 bitmap += 1024;
9232         }
9233
9234         /* Then read the msr_index'th bit from this bitmap: */
9235         if (msr_index < 1024*8) {
9236                 unsigned char b;
9237                 if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
9238                         return true;
9239                 return 1 & (b >> (msr_index & 7));
9240         } else
9241                 return true; /* let L1 handle the wrong parameter */
9242 }
9243
9244 /*
9245  * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
9246  * rather than handle it ourselves in L0. I.e., check if L1 wanted to
9247  * intercept (via guest_host_mask etc.) the current event.
9248  */
9249 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
9250         struct vmcs12 *vmcs12)
9251 {
9252         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9253         int cr = exit_qualification & 15;
9254         int reg;
9255         unsigned long val;
9256
9257         switch ((exit_qualification >> 4) & 3) {
9258         case 0: /* mov to cr */
9259                 reg = (exit_qualification >> 8) & 15;
9260                 val = kvm_register_readl(vcpu, reg);
9261                 switch (cr) {
9262                 case 0:
9263                         if (vmcs12->cr0_guest_host_mask &
9264                             (val ^ vmcs12->cr0_read_shadow))
9265                                 return true;
9266                         break;
9267                 case 3:
9268                         if ((vmcs12->cr3_target_count >= 1 &&
9269                                         vmcs12->cr3_target_value0 == val) ||
9270                                 (vmcs12->cr3_target_count >= 2 &&
9271                                         vmcs12->cr3_target_value1 == val) ||
9272                                 (vmcs12->cr3_target_count >= 3 &&
9273                                         vmcs12->cr3_target_value2 == val) ||
9274                                 (vmcs12->cr3_target_count >= 4 &&
9275                                         vmcs12->cr3_target_value3 == val))
9276                                 return false;
9277                         if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
9278                                 return true;
9279                         break;
9280                 case 4:
9281                         if (vmcs12->cr4_guest_host_mask &
9282                             (vmcs12->cr4_read_shadow ^ val))
9283                                 return true;
9284                         break;
9285                 case 8:
9286                         if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
9287                                 return true;
9288                         break;
9289                 }
9290                 break;
9291         case 2: /* clts */
9292                 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
9293                     (vmcs12->cr0_read_shadow & X86_CR0_TS))
9294                         return true;
9295                 break;
9296         case 1: /* mov from cr */
9297                 switch (cr) {
9298                 case 3:
9299                         if (vmcs12->cpu_based_vm_exec_control &
9300                             CPU_BASED_CR3_STORE_EXITING)
9301                                 return true;
9302                         break;
9303                 case 8:
9304                         if (vmcs12->cpu_based_vm_exec_control &
9305                             CPU_BASED_CR8_STORE_EXITING)
9306                                 return true;
9307                         break;
9308                 }
9309                 break;
9310         case 3: /* lmsw */
9311                 /*
9312                  * lmsw can change bits 1..3 of cr0, and only set bit 0 of
9313                  * cr0. Other attempted changes are ignored, with no exit.
9314                  */
9315                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
9316                 if (vmcs12->cr0_guest_host_mask & 0xe &
9317                     (val ^ vmcs12->cr0_read_shadow))
9318                         return true;
9319                 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
9320                     !(vmcs12->cr0_read_shadow & 0x1) &&
9321                     (val & 0x1))
9322                         return true;
9323                 break;
9324         }
9325         return false;
9326 }
9327
9328 static bool nested_vmx_exit_handled_vmcs_access(struct kvm_vcpu *vcpu,
9329         struct vmcs12 *vmcs12, gpa_t bitmap)
9330 {
9331         u32 vmx_instruction_info;
9332         unsigned long field;
9333         u8 b;
9334
9335         if (!nested_cpu_has_shadow_vmcs(vmcs12))
9336                 return true;
9337
9338         /* Decode instruction info and find the field to access */
9339         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9340         field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
9341
9342         /* Out-of-range fields always cause a VM exit from L2 to L1 */
9343         if (field >> 15)
9344                 return true;
9345
9346         if (kvm_vcpu_read_guest(vcpu, bitmap + field/8, &b, 1))
9347                 return true;
9348
9349         return 1 & (b >> (field & 7));
9350 }
9351
9352 /*
9353  * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
9354  * should handle it ourselves in L0 (and then continue L2). Only call this
9355  * when in is_guest_mode (L2).
9356  */
9357 static bool nested_vmx_exit_reflected(struct kvm_vcpu *vcpu, u32 exit_reason)
9358 {
9359         u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9360         struct vcpu_vmx *vmx = to_vmx(vcpu);
9361         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9362
9363         if (vmx->nested.nested_run_pending)
9364                 return false;
9365
9366         if (unlikely(vmx->fail)) {
9367                 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
9368                                     vmcs_read32(VM_INSTRUCTION_ERROR));
9369                 return true;
9370         }
9371
9372         /*
9373          * The host physical addresses of some pages of guest memory
9374          * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
9375          * Page). The CPU may write to these pages via their host
9376          * physical address while L2 is running, bypassing any
9377          * address-translation-based dirty tracking (e.g. EPT write
9378          * protection).
9379          *
9380          * Mark them dirty on every exit from L2 to prevent them from
9381          * getting out of sync with dirty tracking.
9382          */
9383         nested_mark_vmcs12_pages_dirty(vcpu);
9384
9385         trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
9386                                 vmcs_readl(EXIT_QUALIFICATION),
9387                                 vmx->idt_vectoring_info,
9388                                 intr_info,
9389                                 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
9390                                 KVM_ISA_VMX);
9391
9392         switch (exit_reason) {
9393         case EXIT_REASON_EXCEPTION_NMI:
9394                 if (is_nmi(intr_info))
9395                         return false;
9396                 else if (is_page_fault(intr_info))
9397                         return !vmx->vcpu.arch.apf.host_apf_reason && enable_ept;
9398                 else if (is_no_device(intr_info) &&
9399                          !(vmcs12->guest_cr0 & X86_CR0_TS))
9400                         return false;
9401                 else if (is_debug(intr_info) &&
9402                          vcpu->guest_debug &
9403                          (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
9404                         return false;
9405                 else if (is_breakpoint(intr_info) &&
9406                          vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
9407                         return false;
9408                 return vmcs12->exception_bitmap &
9409                                 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
9410         case EXIT_REASON_EXTERNAL_INTERRUPT:
9411                 return false;
9412         case EXIT_REASON_TRIPLE_FAULT:
9413                 return true;
9414         case EXIT_REASON_PENDING_INTERRUPT:
9415                 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
9416         case EXIT_REASON_NMI_WINDOW:
9417                 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
9418         case EXIT_REASON_TASK_SWITCH:
9419                 return true;
9420         case EXIT_REASON_CPUID:
9421                 return true;
9422         case EXIT_REASON_HLT:
9423                 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
9424         case EXIT_REASON_INVD:
9425                 return true;
9426         case EXIT_REASON_INVLPG:
9427                 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
9428         case EXIT_REASON_RDPMC:
9429                 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
9430         case EXIT_REASON_RDRAND:
9431                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDRAND_EXITING);
9432         case EXIT_REASON_RDSEED:
9433                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDSEED_EXITING);
9434         case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
9435                 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
9436         case EXIT_REASON_VMREAD:
9437                 return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
9438                         vmcs12->vmread_bitmap);
9439         case EXIT_REASON_VMWRITE:
9440                 return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
9441                         vmcs12->vmwrite_bitmap);
9442         case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
9443         case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
9444         case EXIT_REASON_VMPTRST: case EXIT_REASON_VMRESUME:
9445         case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
9446         case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
9447                 /*
9448                  * VMX instructions trap unconditionally. This allows L1 to
9449                  * emulate them for its L2 guest, i.e., allows 3-level nesting!
9450                  */
9451                 return true;
9452         case EXIT_REASON_CR_ACCESS:
9453                 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
9454         case EXIT_REASON_DR_ACCESS:
9455                 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
9456         case EXIT_REASON_IO_INSTRUCTION:
9457                 return nested_vmx_exit_handled_io(vcpu, vmcs12);
9458         case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
9459                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
9460         case EXIT_REASON_MSR_READ:
9461         case EXIT_REASON_MSR_WRITE:
9462                 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
9463         case EXIT_REASON_INVALID_STATE:
9464                 return true;
9465         case EXIT_REASON_MWAIT_INSTRUCTION:
9466                 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
9467         case EXIT_REASON_MONITOR_TRAP_FLAG:
9468                 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG);
9469         case EXIT_REASON_MONITOR_INSTRUCTION:
9470                 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
9471         case EXIT_REASON_PAUSE_INSTRUCTION:
9472                 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
9473                         nested_cpu_has2(vmcs12,
9474                                 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
9475         case EXIT_REASON_MCE_DURING_VMENTRY:
9476                 return false;
9477         case EXIT_REASON_TPR_BELOW_THRESHOLD:
9478                 return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
9479         case EXIT_REASON_APIC_ACCESS:
9480         case EXIT_REASON_APIC_WRITE:
9481         case EXIT_REASON_EOI_INDUCED:
9482                 /*
9483                  * The controls for "virtualize APIC accesses," "APIC-
9484                  * register virtualization," and "virtual-interrupt
9485                  * delivery" only come from vmcs12.
9486                  */
9487                 return true;
9488         case EXIT_REASON_EPT_VIOLATION:
9489                 /*
9490                  * L0 always deals with the EPT violation. If nested EPT is
9491                  * used, and the nested mmu code discovers that the address is
9492                  * missing in the guest EPT table (EPT12), the EPT violation
9493                  * will be injected with nested_ept_inject_page_fault()
9494                  */
9495                 return false;
9496         case EXIT_REASON_EPT_MISCONFIG:
9497                 /*
9498                  * L2 never uses directly L1's EPT, but rather L0's own EPT
9499                  * table (shadow on EPT) or a merged EPT table that L0 built
9500                  * (EPT on EPT). So any problems with the structure of the
9501                  * table is L0's fault.
9502                  */
9503                 return false;
9504         case EXIT_REASON_INVPCID:
9505                 return
9506                         nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_INVPCID) &&
9507                         nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
9508         case EXIT_REASON_WBINVD:
9509                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
9510         case EXIT_REASON_XSETBV:
9511                 return true;
9512         case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
9513                 /*
9514                  * This should never happen, since it is not possible to
9515                  * set XSS to a non-zero value---neither in L1 nor in L2.
9516                  * If if it were, XSS would have to be checked against
9517                  * the XSS exit bitmap in vmcs12.
9518                  */
9519                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
9520         case EXIT_REASON_PREEMPTION_TIMER:
9521                 return false;
9522         case EXIT_REASON_PML_FULL:
9523                 /* We emulate PML support to L1. */
9524                 return false;
9525         case EXIT_REASON_VMFUNC:
9526                 /* VM functions are emulated through L2->L0 vmexits. */
9527                 return false;
9528         default:
9529                 return true;
9530         }
9531 }
9532
9533 static int nested_vmx_reflect_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason)
9534 {
9535         u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9536
9537         /*
9538          * At this point, the exit interruption info in exit_intr_info
9539          * is only valid for EXCEPTION_NMI exits.  For EXTERNAL_INTERRUPT
9540          * we need to query the in-kernel LAPIC.
9541          */
9542         WARN_ON(exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT);
9543         if ((exit_intr_info &
9544              (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
9545             (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) {
9546                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9547                 vmcs12->vm_exit_intr_error_code =
9548                         vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
9549         }
9550
9551         nested_vmx_vmexit(vcpu, exit_reason, exit_intr_info,
9552                           vmcs_readl(EXIT_QUALIFICATION));
9553         return 1;
9554 }
9555
9556 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
9557 {
9558         *info1 = vmcs_readl(EXIT_QUALIFICATION);
9559         *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
9560 }
9561
9562 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
9563 {
9564         if (vmx->pml_pg) {
9565                 __free_page(vmx->pml_pg);
9566                 vmx->pml_pg = NULL;
9567         }
9568 }
9569
9570 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
9571 {
9572         struct vcpu_vmx *vmx = to_vmx(vcpu);
9573         u64 *pml_buf;
9574         u16 pml_idx;
9575
9576         pml_idx = vmcs_read16(GUEST_PML_INDEX);
9577
9578         /* Do nothing if PML buffer is empty */
9579         if (pml_idx == (PML_ENTITY_NUM - 1))
9580                 return;
9581
9582         /* PML index always points to next available PML buffer entity */
9583         if (pml_idx >= PML_ENTITY_NUM)
9584                 pml_idx = 0;
9585         else
9586                 pml_idx++;
9587
9588         pml_buf = page_address(vmx->pml_pg);
9589         for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
9590                 u64 gpa;
9591
9592                 gpa = pml_buf[pml_idx];
9593                 WARN_ON(gpa & (PAGE_SIZE - 1));
9594                 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
9595         }
9596
9597         /* reset PML index */
9598         vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
9599 }
9600
9601 /*
9602  * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
9603  * Called before reporting dirty_bitmap to userspace.
9604  */
9605 static void kvm_flush_pml_buffers(struct kvm *kvm)
9606 {
9607         int i;
9608         struct kvm_vcpu *vcpu;
9609         /*
9610          * We only need to kick vcpu out of guest mode here, as PML buffer
9611          * is flushed at beginning of all VMEXITs, and it's obvious that only
9612          * vcpus running in guest are possible to have unflushed GPAs in PML
9613          * buffer.
9614          */
9615         kvm_for_each_vcpu(i, vcpu, kvm)
9616                 kvm_vcpu_kick(vcpu);
9617 }
9618
9619 static void vmx_dump_sel(char *name, uint32_t sel)
9620 {
9621         pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
9622                name, vmcs_read16(sel),
9623                vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
9624                vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
9625                vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
9626 }
9627
9628 static void vmx_dump_dtsel(char *name, uint32_t limit)
9629 {
9630         pr_err("%s                           limit=0x%08x, base=0x%016lx\n",
9631                name, vmcs_read32(limit),
9632                vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
9633 }
9634
9635 static void dump_vmcs(void)
9636 {
9637         u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
9638         u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
9639         u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
9640         u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
9641         u32 secondary_exec_control = 0;
9642         unsigned long cr4 = vmcs_readl(GUEST_CR4);
9643         u64 efer = vmcs_read64(GUEST_IA32_EFER);
9644         int i, n;
9645
9646         if (cpu_has_secondary_exec_ctrls())
9647                 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
9648
9649         pr_err("*** Guest State ***\n");
9650         pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
9651                vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
9652                vmcs_readl(CR0_GUEST_HOST_MASK));
9653         pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
9654                cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
9655         pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
9656         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
9657             (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
9658         {
9659                 pr_err("PDPTR0 = 0x%016llx  PDPTR1 = 0x%016llx\n",
9660                        vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
9661                 pr_err("PDPTR2 = 0x%016llx  PDPTR3 = 0x%016llx\n",
9662                        vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
9663         }
9664         pr_err("RSP = 0x%016lx  RIP = 0x%016lx\n",
9665                vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
9666         pr_err("RFLAGS=0x%08lx         DR7 = 0x%016lx\n",
9667                vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
9668         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
9669                vmcs_readl(GUEST_SYSENTER_ESP),
9670                vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
9671         vmx_dump_sel("CS:  ", GUEST_CS_SELECTOR);
9672         vmx_dump_sel("DS:  ", GUEST_DS_SELECTOR);
9673         vmx_dump_sel("SS:  ", GUEST_SS_SELECTOR);
9674         vmx_dump_sel("ES:  ", GUEST_ES_SELECTOR);
9675         vmx_dump_sel("FS:  ", GUEST_FS_SELECTOR);
9676         vmx_dump_sel("GS:  ", GUEST_GS_SELECTOR);
9677         vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
9678         vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
9679         vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
9680         vmx_dump_sel("TR:  ", GUEST_TR_SELECTOR);
9681         if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
9682             (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
9683                 pr_err("EFER =     0x%016llx  PAT = 0x%016llx\n",
9684                        efer, vmcs_read64(GUEST_IA32_PAT));
9685         pr_err("DebugCtl = 0x%016llx  DebugExceptions = 0x%016lx\n",
9686                vmcs_read64(GUEST_IA32_DEBUGCTL),
9687                vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
9688         if (cpu_has_load_perf_global_ctrl &&
9689             vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
9690                 pr_err("PerfGlobCtl = 0x%016llx\n",
9691                        vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
9692         if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
9693                 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
9694         pr_err("Interruptibility = %08x  ActivityState = %08x\n",
9695                vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
9696                vmcs_read32(GUEST_ACTIVITY_STATE));
9697         if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
9698                 pr_err("InterruptStatus = %04x\n",
9699                        vmcs_read16(GUEST_INTR_STATUS));
9700
9701         pr_err("*** Host State ***\n");
9702         pr_err("RIP = 0x%016lx  RSP = 0x%016lx\n",
9703                vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
9704         pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
9705                vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
9706                vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
9707                vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
9708                vmcs_read16(HOST_TR_SELECTOR));
9709         pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
9710                vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
9711                vmcs_readl(HOST_TR_BASE));
9712         pr_err("GDTBase=%016lx IDTBase=%016lx\n",
9713                vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
9714         pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
9715                vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
9716                vmcs_readl(HOST_CR4));
9717         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
9718                vmcs_readl(HOST_IA32_SYSENTER_ESP),
9719                vmcs_read32(HOST_IA32_SYSENTER_CS),
9720                vmcs_readl(HOST_IA32_SYSENTER_EIP));
9721         if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
9722                 pr_err("EFER = 0x%016llx  PAT = 0x%016llx\n",
9723                        vmcs_read64(HOST_IA32_EFER),
9724                        vmcs_read64(HOST_IA32_PAT));
9725         if (cpu_has_load_perf_global_ctrl &&
9726             vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
9727                 pr_err("PerfGlobCtl = 0x%016llx\n",
9728                        vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
9729
9730         pr_err("*** Control State ***\n");
9731         pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
9732                pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
9733         pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
9734         pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
9735                vmcs_read32(EXCEPTION_BITMAP),
9736                vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
9737                vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
9738         pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
9739                vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
9740                vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
9741                vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
9742         pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
9743                vmcs_read32(VM_EXIT_INTR_INFO),
9744                vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
9745                vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
9746         pr_err("        reason=%08x qualification=%016lx\n",
9747                vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
9748         pr_err("IDTVectoring: info=%08x errcode=%08x\n",
9749                vmcs_read32(IDT_VECTORING_INFO_FIELD),
9750                vmcs_read32(IDT_VECTORING_ERROR_CODE));
9751         pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
9752         if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
9753                 pr_err("TSC Multiplier = 0x%016llx\n",
9754                        vmcs_read64(TSC_MULTIPLIER));
9755         if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
9756                 pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
9757         if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
9758                 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
9759         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
9760                 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
9761         n = vmcs_read32(CR3_TARGET_COUNT);
9762         for (i = 0; i + 1 < n; i += 4)
9763                 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
9764                        i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
9765                        i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
9766         if (i < n)
9767                 pr_err("CR3 target%u=%016lx\n",
9768                        i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
9769         if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
9770                 pr_err("PLE Gap=%08x Window=%08x\n",
9771                        vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
9772         if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
9773                 pr_err("Virtual processor ID = 0x%04x\n",
9774                        vmcs_read16(VIRTUAL_PROCESSOR_ID));
9775 }
9776
9777 /*
9778  * The guest has exited.  See if we can fix it or if we need userspace
9779  * assistance.
9780  */
9781 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
9782 {
9783         struct vcpu_vmx *vmx = to_vmx(vcpu);
9784         u32 exit_reason = vmx->exit_reason;
9785         u32 vectoring_info = vmx->idt_vectoring_info;
9786
9787         trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
9788
9789         /*
9790          * Flush logged GPAs PML buffer, this will make dirty_bitmap more
9791          * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
9792          * querying dirty_bitmap, we only need to kick all vcpus out of guest
9793          * mode as if vcpus is in root mode, the PML buffer must has been
9794          * flushed already.
9795          */
9796         if (enable_pml)
9797                 vmx_flush_pml_buffer(vcpu);
9798
9799         /* If guest state is invalid, start emulating */
9800         if (vmx->emulation_required)
9801                 return handle_invalid_guest_state(vcpu);
9802
9803         if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
9804                 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
9805
9806         if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
9807                 dump_vmcs();
9808                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
9809                 vcpu->run->fail_entry.hardware_entry_failure_reason
9810                         = exit_reason;
9811                 return 0;
9812         }
9813
9814         if (unlikely(vmx->fail)) {
9815                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
9816                 vcpu->run->fail_entry.hardware_entry_failure_reason
9817                         = vmcs_read32(VM_INSTRUCTION_ERROR);
9818                 return 0;
9819         }
9820
9821         /*
9822          * Note:
9823          * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
9824          * delivery event since it indicates guest is accessing MMIO.
9825          * The vm-exit can be triggered again after return to guest that
9826          * will cause infinite loop.
9827          */
9828         if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
9829                         (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
9830                         exit_reason != EXIT_REASON_EPT_VIOLATION &&
9831                         exit_reason != EXIT_REASON_PML_FULL &&
9832                         exit_reason != EXIT_REASON_TASK_SWITCH)) {
9833                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9834                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
9835                 vcpu->run->internal.ndata = 3;
9836                 vcpu->run->internal.data[0] = vectoring_info;
9837                 vcpu->run->internal.data[1] = exit_reason;
9838                 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
9839                 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
9840                         vcpu->run->internal.ndata++;
9841                         vcpu->run->internal.data[3] =
9842                                 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
9843                 }
9844                 return 0;
9845         }
9846
9847         if (unlikely(!enable_vnmi &&
9848                      vmx->loaded_vmcs->soft_vnmi_blocked)) {
9849                 if (vmx_interrupt_allowed(vcpu)) {
9850                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
9851                 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
9852                            vcpu->arch.nmi_pending) {
9853                         /*
9854                          * This CPU don't support us in finding the end of an
9855                          * NMI-blocked window if the guest runs with IRQs
9856                          * disabled. So we pull the trigger after 1 s of
9857                          * futile waiting, but inform the user about this.
9858                          */
9859                         printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
9860                                "state on VCPU %d after 1 s timeout\n",
9861                                __func__, vcpu->vcpu_id);
9862                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
9863                 }
9864         }
9865
9866         if (exit_reason < kvm_vmx_max_exit_handlers
9867             && kvm_vmx_exit_handlers[exit_reason])
9868                 return kvm_vmx_exit_handlers[exit_reason](vcpu);
9869         else {
9870                 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
9871                                 exit_reason);
9872                 kvm_queue_exception(vcpu, UD_VECTOR);
9873                 return 1;
9874         }
9875 }
9876
9877 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
9878 {
9879         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9880
9881         if (is_guest_mode(vcpu) &&
9882                 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
9883                 return;
9884
9885         if (irr == -1 || tpr < irr) {
9886                 vmcs_write32(TPR_THRESHOLD, 0);
9887                 return;
9888         }
9889
9890         vmcs_write32(TPR_THRESHOLD, irr);
9891 }
9892
9893 static void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
9894 {
9895         u32 sec_exec_control;
9896
9897         if (!lapic_in_kernel(vcpu))
9898                 return;
9899
9900         /* Postpone execution until vmcs01 is the current VMCS. */
9901         if (is_guest_mode(vcpu)) {
9902                 to_vmx(vcpu)->nested.change_vmcs01_virtual_apic_mode = true;
9903                 return;
9904         }
9905
9906         if (!cpu_need_tpr_shadow(vcpu))
9907                 return;
9908
9909         sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
9910         sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
9911                               SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
9912
9913         switch (kvm_get_apic_mode(vcpu)) {
9914         case LAPIC_MODE_INVALID:
9915                 WARN_ONCE(true, "Invalid local APIC state");
9916         case LAPIC_MODE_DISABLED:
9917                 break;
9918         case LAPIC_MODE_XAPIC:
9919                 if (flexpriority_enabled) {
9920                         sec_exec_control |=
9921                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
9922                         vmx_flush_tlb(vcpu, true);
9923                 }
9924                 break;
9925         case LAPIC_MODE_X2APIC:
9926                 if (cpu_has_vmx_virtualize_x2apic_mode())
9927                         sec_exec_control |=
9928                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
9929                 break;
9930         }
9931         vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
9932
9933         vmx_update_msr_bitmap(vcpu);
9934 }
9935
9936 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
9937 {
9938         if (!is_guest_mode(vcpu)) {
9939                 vmcs_write64(APIC_ACCESS_ADDR, hpa);
9940                 vmx_flush_tlb(vcpu, true);
9941         }
9942 }
9943
9944 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
9945 {
9946         u16 status;
9947         u8 old;
9948
9949         if (max_isr == -1)
9950                 max_isr = 0;
9951
9952         status = vmcs_read16(GUEST_INTR_STATUS);
9953         old = status >> 8;
9954         if (max_isr != old) {
9955                 status &= 0xff;
9956                 status |= max_isr << 8;
9957                 vmcs_write16(GUEST_INTR_STATUS, status);
9958         }
9959 }
9960
9961 static void vmx_set_rvi(int vector)
9962 {
9963         u16 status;
9964         u8 old;
9965
9966         if (vector == -1)
9967                 vector = 0;
9968
9969         status = vmcs_read16(GUEST_INTR_STATUS);
9970         old = (u8)status & 0xff;
9971         if ((u8)vector != old) {
9972                 status &= ~0xff;
9973                 status |= (u8)vector;
9974                 vmcs_write16(GUEST_INTR_STATUS, status);
9975         }
9976 }
9977
9978 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
9979 {
9980         /*
9981          * When running L2, updating RVI is only relevant when
9982          * vmcs12 virtual-interrupt-delivery enabled.
9983          * However, it can be enabled only when L1 also
9984          * intercepts external-interrupts and in that case
9985          * we should not update vmcs02 RVI but instead intercept
9986          * interrupt. Therefore, do nothing when running L2.
9987          */
9988         if (!is_guest_mode(vcpu))
9989                 vmx_set_rvi(max_irr);
9990 }
9991
9992 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
9993 {
9994         struct vcpu_vmx *vmx = to_vmx(vcpu);
9995         int max_irr;
9996         bool max_irr_updated;
9997
9998         WARN_ON(!vcpu->arch.apicv_active);
9999         if (pi_test_on(&vmx->pi_desc)) {
10000                 pi_clear_on(&vmx->pi_desc);
10001                 /*
10002                  * IOMMU can write to PIR.ON, so the barrier matters even on UP.
10003                  * But on x86 this is just a compiler barrier anyway.
10004                  */
10005                 smp_mb__after_atomic();
10006                 max_irr_updated =
10007                         kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
10008
10009                 /*
10010                  * If we are running L2 and L1 has a new pending interrupt
10011                  * which can be injected, we should re-evaluate
10012                  * what should be done with this new L1 interrupt.
10013                  * If L1 intercepts external-interrupts, we should
10014                  * exit from L2 to L1. Otherwise, interrupt should be
10015                  * delivered directly to L2.
10016                  */
10017                 if (is_guest_mode(vcpu) && max_irr_updated) {
10018                         if (nested_exit_on_intr(vcpu))
10019                                 kvm_vcpu_exiting_guest_mode(vcpu);
10020                         else
10021                                 kvm_make_request(KVM_REQ_EVENT, vcpu);
10022                 }
10023         } else {
10024                 max_irr = kvm_lapic_find_highest_irr(vcpu);
10025         }
10026         vmx_hwapic_irr_update(vcpu, max_irr);
10027         return max_irr;
10028 }
10029
10030 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
10031 {
10032         if (!kvm_vcpu_apicv_active(vcpu))
10033                 return;
10034
10035         vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
10036         vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
10037         vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
10038         vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
10039 }
10040
10041 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
10042 {
10043         struct vcpu_vmx *vmx = to_vmx(vcpu);
10044
10045         pi_clear_on(&vmx->pi_desc);
10046         memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
10047 }
10048
10049 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
10050 {
10051         u32 exit_intr_info = 0;
10052         u16 basic_exit_reason = (u16)vmx->exit_reason;
10053
10054         if (!(basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
10055               || basic_exit_reason == EXIT_REASON_EXCEPTION_NMI))
10056                 return;
10057
10058         if (!(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
10059                 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10060         vmx->exit_intr_info = exit_intr_info;
10061
10062         /* if exit due to PF check for async PF */
10063         if (is_page_fault(exit_intr_info))
10064                 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
10065
10066         /* Handle machine checks before interrupts are enabled */
10067         if (basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY ||
10068             is_machine_check(exit_intr_info))
10069                 kvm_machine_check();
10070
10071         /* We need to handle NMIs before interrupts are enabled */
10072         if (is_nmi(exit_intr_info)) {
10073                 kvm_before_interrupt(&vmx->vcpu);
10074                 asm("int $2");
10075                 kvm_after_interrupt(&vmx->vcpu);
10076         }
10077 }
10078
10079 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
10080 {
10081         u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10082
10083         if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
10084                         == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
10085                 unsigned int vector;
10086                 unsigned long entry;
10087                 gate_desc *desc;
10088                 struct vcpu_vmx *vmx = to_vmx(vcpu);
10089 #ifdef CONFIG_X86_64
10090                 unsigned long tmp;
10091 #endif
10092
10093                 vector =  exit_intr_info & INTR_INFO_VECTOR_MASK;
10094                 desc = (gate_desc *)vmx->host_idt_base + vector;
10095                 entry = gate_offset(desc);
10096                 asm volatile(
10097 #ifdef CONFIG_X86_64
10098                         "mov %%" _ASM_SP ", %[sp]\n\t"
10099                         "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
10100                         "push $%c[ss]\n\t"
10101                         "push %[sp]\n\t"
10102 #endif
10103                         "pushf\n\t"
10104                         __ASM_SIZE(push) " $%c[cs]\n\t"
10105                         CALL_NOSPEC
10106                         :
10107 #ifdef CONFIG_X86_64
10108                         [sp]"=&r"(tmp),
10109 #endif
10110                         ASM_CALL_CONSTRAINT
10111                         :
10112                         THUNK_TARGET(entry),
10113                         [ss]"i"(__KERNEL_DS),
10114                         [cs]"i"(__KERNEL_CS)
10115                         );
10116         }
10117 }
10118 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
10119
10120 static bool vmx_has_emulated_msr(int index)
10121 {
10122         switch (index) {
10123         case MSR_IA32_SMBASE:
10124                 /*
10125                  * We cannot do SMM unless we can run the guest in big
10126                  * real mode.
10127                  */
10128                 return enable_unrestricted_guest || emulate_invalid_guest_state;
10129         case MSR_AMD64_VIRT_SPEC_CTRL:
10130                 /* This is AMD only.  */
10131                 return false;
10132         default:
10133                 return true;
10134         }
10135 }
10136
10137 static bool vmx_mpx_supported(void)
10138 {
10139         return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
10140                 (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
10141 }
10142
10143 static bool vmx_xsaves_supported(void)
10144 {
10145         return vmcs_config.cpu_based_2nd_exec_ctrl &
10146                 SECONDARY_EXEC_XSAVES;
10147 }
10148
10149 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
10150 {
10151         u32 exit_intr_info;
10152         bool unblock_nmi;
10153         u8 vector;
10154         bool idtv_info_valid;
10155
10156         idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
10157
10158         if (enable_vnmi) {
10159                 if (vmx->loaded_vmcs->nmi_known_unmasked)
10160                         return;
10161                 /*
10162                  * Can't use vmx->exit_intr_info since we're not sure what
10163                  * the exit reason is.
10164                  */
10165                 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10166                 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
10167                 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
10168                 /*
10169                  * SDM 3: 27.7.1.2 (September 2008)
10170                  * Re-set bit "block by NMI" before VM entry if vmexit caused by
10171                  * a guest IRET fault.
10172                  * SDM 3: 23.2.2 (September 2008)
10173                  * Bit 12 is undefined in any of the following cases:
10174                  *  If the VM exit sets the valid bit in the IDT-vectoring
10175                  *   information field.
10176                  *  If the VM exit is due to a double fault.
10177                  */
10178                 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
10179                     vector != DF_VECTOR && !idtv_info_valid)
10180                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
10181                                       GUEST_INTR_STATE_NMI);
10182                 else
10183                         vmx->loaded_vmcs->nmi_known_unmasked =
10184                                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
10185                                   & GUEST_INTR_STATE_NMI);
10186         } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
10187                 vmx->loaded_vmcs->vnmi_blocked_time +=
10188                         ktime_to_ns(ktime_sub(ktime_get(),
10189                                               vmx->loaded_vmcs->entry_time));
10190 }
10191
10192 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
10193                                       u32 idt_vectoring_info,
10194                                       int instr_len_field,
10195                                       int error_code_field)
10196 {
10197         u8 vector;
10198         int type;
10199         bool idtv_info_valid;
10200
10201         idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
10202
10203         vcpu->arch.nmi_injected = false;
10204         kvm_clear_exception_queue(vcpu);
10205         kvm_clear_interrupt_queue(vcpu);
10206
10207         if (!idtv_info_valid)
10208                 return;
10209
10210         kvm_make_request(KVM_REQ_EVENT, vcpu);
10211
10212         vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
10213         type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
10214
10215         switch (type) {
10216         case INTR_TYPE_NMI_INTR:
10217                 vcpu->arch.nmi_injected = true;
10218                 /*
10219                  * SDM 3: 27.7.1.2 (September 2008)
10220                  * Clear bit "block by NMI" before VM entry if a NMI
10221                  * delivery faulted.
10222                  */
10223                 vmx_set_nmi_mask(vcpu, false);
10224                 break;
10225         case INTR_TYPE_SOFT_EXCEPTION:
10226                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
10227                 /* fall through */
10228         case INTR_TYPE_HARD_EXCEPTION:
10229                 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
10230                         u32 err = vmcs_read32(error_code_field);
10231                         kvm_requeue_exception_e(vcpu, vector, err);
10232                 } else
10233                         kvm_requeue_exception(vcpu, vector);
10234                 break;
10235         case INTR_TYPE_SOFT_INTR:
10236                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
10237                 /* fall through */
10238         case INTR_TYPE_EXT_INTR:
10239                 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
10240                 break;
10241         default:
10242                 break;
10243         }
10244 }
10245
10246 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
10247 {
10248         __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
10249                                   VM_EXIT_INSTRUCTION_LEN,
10250                                   IDT_VECTORING_ERROR_CODE);
10251 }
10252
10253 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
10254 {
10255         __vmx_complete_interrupts(vcpu,
10256                                   vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
10257                                   VM_ENTRY_INSTRUCTION_LEN,
10258                                   VM_ENTRY_EXCEPTION_ERROR_CODE);
10259
10260         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
10261 }
10262
10263 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
10264 {
10265         int i, nr_msrs;
10266         struct perf_guest_switch_msr *msrs;
10267
10268         msrs = perf_guest_get_msrs(&nr_msrs);
10269
10270         if (!msrs)
10271                 return;
10272
10273         for (i = 0; i < nr_msrs; i++)
10274                 if (msrs[i].host == msrs[i].guest)
10275                         clear_atomic_switch_msr(vmx, msrs[i].msr);
10276                 else
10277                         add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
10278                                         msrs[i].host);
10279 }
10280
10281 static void vmx_arm_hv_timer(struct kvm_vcpu *vcpu)
10282 {
10283         struct vcpu_vmx *vmx = to_vmx(vcpu);
10284         u64 tscl;
10285         u32 delta_tsc;
10286
10287         if (vmx->hv_deadline_tsc == -1)
10288                 return;
10289
10290         tscl = rdtsc();
10291         if (vmx->hv_deadline_tsc > tscl)
10292                 /* sure to be 32 bit only because checked on set_hv_timer */
10293                 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
10294                         cpu_preemption_timer_multi);
10295         else
10296                 delta_tsc = 0;
10297
10298         vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
10299 }
10300
10301 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
10302 {
10303         struct vcpu_vmx *vmx = to_vmx(vcpu);
10304         unsigned long cr3, cr4, evmcs_rsp;
10305
10306         /* Record the guest's net vcpu time for enforced NMI injections. */
10307         if (unlikely(!enable_vnmi &&
10308                      vmx->loaded_vmcs->soft_vnmi_blocked))
10309                 vmx->loaded_vmcs->entry_time = ktime_get();
10310
10311         /* Don't enter VMX if guest state is invalid, let the exit handler
10312            start emulation until we arrive back to a valid state */
10313         if (vmx->emulation_required)
10314                 return;
10315
10316         if (vmx->ple_window_dirty) {
10317                 vmx->ple_window_dirty = false;
10318                 vmcs_write32(PLE_WINDOW, vmx->ple_window);
10319         }
10320
10321         if (vmx->nested.sync_shadow_vmcs) {
10322                 copy_vmcs12_to_shadow(vmx);
10323                 vmx->nested.sync_shadow_vmcs = false;
10324         }
10325
10326         if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
10327                 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
10328         if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
10329                 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
10330
10331         cr3 = __get_current_cr3_fast();
10332         if (unlikely(cr3 != vmx->loaded_vmcs->vmcs_host_cr3)) {
10333                 vmcs_writel(HOST_CR3, cr3);
10334                 vmx->loaded_vmcs->vmcs_host_cr3 = cr3;
10335         }
10336
10337         cr4 = cr4_read_shadow();
10338         if (unlikely(cr4 != vmx->loaded_vmcs->vmcs_host_cr4)) {
10339                 vmcs_writel(HOST_CR4, cr4);
10340                 vmx->loaded_vmcs->vmcs_host_cr4 = cr4;
10341         }
10342
10343         /* When single-stepping over STI and MOV SS, we must clear the
10344          * corresponding interruptibility bits in the guest state. Otherwise
10345          * vmentry fails as it then expects bit 14 (BS) in pending debug
10346          * exceptions being set, but that's not correct for the guest debugging
10347          * case. */
10348         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
10349                 vmx_set_interrupt_shadow(vcpu, 0);
10350
10351         if (static_cpu_has(X86_FEATURE_PKU) &&
10352             kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
10353             vcpu->arch.pkru != vmx->host_pkru)
10354                 __write_pkru(vcpu->arch.pkru);
10355
10356         atomic_switch_perf_msrs(vmx);
10357
10358         vmx_arm_hv_timer(vcpu);
10359
10360         /*
10361          * If this vCPU has touched SPEC_CTRL, restore the guest's value if
10362          * it's non-zero. Since vmentry is serialising on affected CPUs, there
10363          * is no need to worry about the conditional branch over the wrmsr
10364          * being speculatively taken.
10365          */
10366         x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
10367
10368         vmx->__launched = vmx->loaded_vmcs->launched;
10369
10370         evmcs_rsp = static_branch_unlikely(&enable_evmcs) ?
10371                 (unsigned long)&current_evmcs->host_rsp : 0;
10372
10373         asm(
10374                 /* Store host registers */
10375                 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
10376                 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
10377                 "push %%" _ASM_CX " \n\t"
10378                 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
10379                 "je 1f \n\t"
10380                 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
10381                 /* Avoid VMWRITE when Enlightened VMCS is in use */
10382                 "test %%" _ASM_SI ", %%" _ASM_SI " \n\t"
10383                 "jz 2f \n\t"
10384                 "mov %%" _ASM_SP ", (%%" _ASM_SI ") \n\t"
10385                 "jmp 1f \n\t"
10386                 "2: \n\t"
10387                 __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
10388                 "1: \n\t"
10389                 /* Reload cr2 if changed */
10390                 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
10391                 "mov %%cr2, %%" _ASM_DX " \n\t"
10392                 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
10393                 "je 3f \n\t"
10394                 "mov %%" _ASM_AX", %%cr2 \n\t"
10395                 "3: \n\t"
10396                 /* Check if vmlaunch of vmresume is needed */
10397                 "cmpl $0, %c[launched](%0) \n\t"
10398                 /* Load guest registers.  Don't clobber flags. */
10399                 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
10400                 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
10401                 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
10402                 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
10403                 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
10404                 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
10405 #ifdef CONFIG_X86_64
10406                 "mov %c[r8](%0),  %%r8  \n\t"
10407                 "mov %c[r9](%0),  %%r9  \n\t"
10408                 "mov %c[r10](%0), %%r10 \n\t"
10409                 "mov %c[r11](%0), %%r11 \n\t"
10410                 "mov %c[r12](%0), %%r12 \n\t"
10411                 "mov %c[r13](%0), %%r13 \n\t"
10412                 "mov %c[r14](%0), %%r14 \n\t"
10413                 "mov %c[r15](%0), %%r15 \n\t"
10414 #endif
10415                 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
10416
10417                 /* Enter guest mode */
10418                 "jne 1f \n\t"
10419                 __ex(ASM_VMX_VMLAUNCH) "\n\t"
10420                 "jmp 2f \n\t"
10421                 "1: " __ex(ASM_VMX_VMRESUME) "\n\t"
10422                 "2: "
10423                 /* Save guest registers, load host registers, keep flags */
10424                 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
10425                 "pop %0 \n\t"
10426                 "setbe %c[fail](%0)\n\t"
10427                 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
10428                 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
10429                 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
10430                 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
10431                 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
10432                 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
10433                 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
10434 #ifdef CONFIG_X86_64
10435                 "mov %%r8,  %c[r8](%0) \n\t"
10436                 "mov %%r9,  %c[r9](%0) \n\t"
10437                 "mov %%r10, %c[r10](%0) \n\t"
10438                 "mov %%r11, %c[r11](%0) \n\t"
10439                 "mov %%r12, %c[r12](%0) \n\t"
10440                 "mov %%r13, %c[r13](%0) \n\t"
10441                 "mov %%r14, %c[r14](%0) \n\t"
10442                 "mov %%r15, %c[r15](%0) \n\t"
10443                 "xor %%r8d,  %%r8d \n\t"
10444                 "xor %%r9d,  %%r9d \n\t"
10445                 "xor %%r10d, %%r10d \n\t"
10446                 "xor %%r11d, %%r11d \n\t"
10447                 "xor %%r12d, %%r12d \n\t"
10448                 "xor %%r13d, %%r13d \n\t"
10449                 "xor %%r14d, %%r14d \n\t"
10450                 "xor %%r15d, %%r15d \n\t"
10451 #endif
10452                 "mov %%cr2, %%" _ASM_AX "   \n\t"
10453                 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
10454
10455                 "xor %%eax, %%eax \n\t"
10456                 "xor %%ebx, %%ebx \n\t"
10457                 "xor %%esi, %%esi \n\t"
10458                 "xor %%edi, %%edi \n\t"
10459                 "pop  %%" _ASM_BP "; pop  %%" _ASM_DX " \n\t"
10460                 ".pushsection .rodata \n\t"
10461                 ".global vmx_return \n\t"
10462                 "vmx_return: " _ASM_PTR " 2b \n\t"
10463                 ".popsection"
10464               : : "c"(vmx), "d"((unsigned long)HOST_RSP), "S"(evmcs_rsp),
10465                 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
10466                 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
10467                 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
10468                 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
10469                 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
10470                 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
10471                 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
10472                 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
10473                 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
10474                 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
10475 #ifdef CONFIG_X86_64
10476                 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
10477                 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
10478                 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
10479                 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
10480                 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
10481                 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
10482                 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
10483                 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
10484 #endif
10485                 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
10486                 [wordsize]"i"(sizeof(ulong))
10487               : "cc", "memory"
10488 #ifdef CONFIG_X86_64
10489                 , "rax", "rbx", "rdi"
10490                 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
10491 #else
10492                 , "eax", "ebx", "edi"
10493 #endif
10494               );
10495
10496         /*
10497          * We do not use IBRS in the kernel. If this vCPU has used the
10498          * SPEC_CTRL MSR it may have left it on; save the value and
10499          * turn it off. This is much more efficient than blindly adding
10500          * it to the atomic save/restore list. Especially as the former
10501          * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
10502          *
10503          * For non-nested case:
10504          * If the L01 MSR bitmap does not intercept the MSR, then we need to
10505          * save it.
10506          *
10507          * For nested case:
10508          * If the L02 MSR bitmap does not intercept the MSR, then we need to
10509          * save it.
10510          */
10511         if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
10512                 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
10513
10514         x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
10515
10516         /* Eliminate branch target predictions from guest mode */
10517         vmexit_fill_RSB();
10518
10519         /* All fields are clean at this point */
10520         if (static_branch_unlikely(&enable_evmcs))
10521                 current_evmcs->hv_clean_fields |=
10522                         HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
10523
10524         /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
10525         if (vmx->host_debugctlmsr)
10526                 update_debugctlmsr(vmx->host_debugctlmsr);
10527
10528 #ifndef CONFIG_X86_64
10529         /*
10530          * The sysexit path does not restore ds/es, so we must set them to
10531          * a reasonable value ourselves.
10532          *
10533          * We can't defer this to vmx_load_host_state() since that function
10534          * may be executed in interrupt context, which saves and restore segments
10535          * around it, nullifying its effect.
10536          */
10537         loadsegment(ds, __USER_DS);
10538         loadsegment(es, __USER_DS);
10539 #endif
10540
10541         vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
10542                                   | (1 << VCPU_EXREG_RFLAGS)
10543                                   | (1 << VCPU_EXREG_PDPTR)
10544                                   | (1 << VCPU_EXREG_SEGMENTS)
10545                                   | (1 << VCPU_EXREG_CR3));
10546         vcpu->arch.regs_dirty = 0;
10547
10548         /*
10549          * eager fpu is enabled if PKEY is supported and CR4 is switched
10550          * back on host, so it is safe to read guest PKRU from current
10551          * XSAVE.
10552          */
10553         if (static_cpu_has(X86_FEATURE_PKU) &&
10554             kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
10555                 vcpu->arch.pkru = __read_pkru();
10556                 if (vcpu->arch.pkru != vmx->host_pkru)
10557                         __write_pkru(vmx->host_pkru);
10558         }
10559
10560         vmx->nested.nested_run_pending = 0;
10561         vmx->idt_vectoring_info = 0;
10562
10563         vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
10564         if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
10565                 return;
10566
10567         vmx->loaded_vmcs->launched = 1;
10568         vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
10569
10570         vmx_complete_atomic_exit(vmx);
10571         vmx_recover_nmi_blocking(vmx);
10572         vmx_complete_interrupts(vmx);
10573 }
10574 STACK_FRAME_NON_STANDARD(vmx_vcpu_run);
10575
10576 static struct kvm *vmx_vm_alloc(void)
10577 {
10578         struct kvm_vmx *kvm_vmx = vzalloc(sizeof(struct kvm_vmx));
10579         return &kvm_vmx->kvm;
10580 }
10581
10582 static void vmx_vm_free(struct kvm *kvm)
10583 {
10584         vfree(to_kvm_vmx(kvm));
10585 }
10586
10587 static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
10588 {
10589         struct vcpu_vmx *vmx = to_vmx(vcpu);
10590         int cpu;
10591
10592         if (vmx->loaded_vmcs == vmcs)
10593                 return;
10594
10595         cpu = get_cpu();
10596         vmx->loaded_vmcs = vmcs;
10597         vmx_vcpu_put(vcpu);
10598         vmx_vcpu_load(vcpu, cpu);
10599         put_cpu();
10600 }
10601
10602 /*
10603  * Ensure that the current vmcs of the logical processor is the
10604  * vmcs01 of the vcpu before calling free_nested().
10605  */
10606 static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu)
10607 {
10608        struct vcpu_vmx *vmx = to_vmx(vcpu);
10609
10610        vcpu_load(vcpu);
10611        vmx_switch_vmcs(vcpu, &vmx->vmcs01);
10612        free_nested(vmx);
10613        vcpu_put(vcpu);
10614 }
10615
10616 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
10617 {
10618         struct vcpu_vmx *vmx = to_vmx(vcpu);
10619
10620         if (enable_pml)
10621                 vmx_destroy_pml_buffer(vmx);
10622         free_vpid(vmx->vpid);
10623         leave_guest_mode(vcpu);
10624         vmx_free_vcpu_nested(vcpu);
10625         free_loaded_vmcs(vmx->loaded_vmcs);
10626         kfree(vmx->guest_msrs);
10627         kvm_vcpu_uninit(vcpu);
10628         kmem_cache_free(kvm_vcpu_cache, vmx);
10629 }
10630
10631 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
10632 {
10633         int err;
10634         struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
10635         unsigned long *msr_bitmap;
10636         int cpu;
10637
10638         if (!vmx)
10639                 return ERR_PTR(-ENOMEM);
10640
10641         vmx->vpid = allocate_vpid();
10642
10643         err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
10644         if (err)
10645                 goto free_vcpu;
10646
10647         err = -ENOMEM;
10648
10649         /*
10650          * If PML is turned on, failure on enabling PML just results in failure
10651          * of creating the vcpu, therefore we can simplify PML logic (by
10652          * avoiding dealing with cases, such as enabling PML partially on vcpus
10653          * for the guest, etc.
10654          */
10655         if (enable_pml) {
10656                 vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
10657                 if (!vmx->pml_pg)
10658                         goto uninit_vcpu;
10659         }
10660
10661         vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
10662         BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
10663                      > PAGE_SIZE);
10664
10665         if (!vmx->guest_msrs)
10666                 goto free_pml;
10667
10668         err = alloc_loaded_vmcs(&vmx->vmcs01);
10669         if (err < 0)
10670                 goto free_msrs;
10671
10672         msr_bitmap = vmx->vmcs01.msr_bitmap;
10673         vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
10674         vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
10675         vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
10676         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
10677         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
10678         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
10679         vmx->msr_bitmap_mode = 0;
10680
10681         vmx->loaded_vmcs = &vmx->vmcs01;
10682         cpu = get_cpu();
10683         vmx_vcpu_load(&vmx->vcpu, cpu);
10684         vmx->vcpu.cpu = cpu;
10685         vmx_vcpu_setup(vmx);
10686         vmx_vcpu_put(&vmx->vcpu);
10687         put_cpu();
10688         if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
10689                 err = alloc_apic_access_page(kvm);
10690                 if (err)
10691                         goto free_vmcs;
10692         }
10693
10694         if (enable_ept && !enable_unrestricted_guest) {
10695                 err = init_rmode_identity_map(kvm);
10696                 if (err)
10697                         goto free_vmcs;
10698         }
10699
10700         if (nested) {
10701                 nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
10702                                            kvm_vcpu_apicv_active(&vmx->vcpu));
10703                 vmx->nested.vpid02 = allocate_vpid();
10704         }
10705
10706         vmx->nested.posted_intr_nv = -1;
10707         vmx->nested.current_vmptr = -1ull;
10708
10709         vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
10710
10711         /*
10712          * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
10713          * or POSTED_INTR_WAKEUP_VECTOR.
10714          */
10715         vmx->pi_desc.nv = POSTED_INTR_VECTOR;
10716         vmx->pi_desc.sn = 1;
10717
10718         return &vmx->vcpu;
10719
10720 free_vmcs:
10721         free_vpid(vmx->nested.vpid02);
10722         free_loaded_vmcs(vmx->loaded_vmcs);
10723 free_msrs:
10724         kfree(vmx->guest_msrs);
10725 free_pml:
10726         vmx_destroy_pml_buffer(vmx);
10727 uninit_vcpu:
10728         kvm_vcpu_uninit(&vmx->vcpu);
10729 free_vcpu:
10730         free_vpid(vmx->vpid);
10731         kmem_cache_free(kvm_vcpu_cache, vmx);
10732         return ERR_PTR(err);
10733 }
10734
10735 static int vmx_vm_init(struct kvm *kvm)
10736 {
10737         spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
10738
10739         if (!ple_gap)
10740                 kvm->arch.pause_in_guest = true;
10741         return 0;
10742 }
10743
10744 static void __init vmx_check_processor_compat(void *rtn)
10745 {
10746         struct vmcs_config vmcs_conf;
10747
10748         *(int *)rtn = 0;
10749         if (setup_vmcs_config(&vmcs_conf) < 0)
10750                 *(int *)rtn = -EIO;
10751         nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, enable_apicv);
10752         if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
10753                 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
10754                                 smp_processor_id());
10755                 *(int *)rtn = -EIO;
10756         }
10757 }
10758
10759 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
10760 {
10761         u8 cache;
10762         u64 ipat = 0;
10763
10764         /* For VT-d and EPT combination
10765          * 1. MMIO: always map as UC
10766          * 2. EPT with VT-d:
10767          *   a. VT-d without snooping control feature: can't guarantee the
10768          *      result, try to trust guest.
10769          *   b. VT-d with snooping control feature: snooping control feature of
10770          *      VT-d engine can guarantee the cache correctness. Just set it
10771          *      to WB to keep consistent with host. So the same as item 3.
10772          * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
10773          *    consistent with host MTRR
10774          */
10775         if (is_mmio) {
10776                 cache = MTRR_TYPE_UNCACHABLE;
10777                 goto exit;
10778         }
10779
10780         if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
10781                 ipat = VMX_EPT_IPAT_BIT;
10782                 cache = MTRR_TYPE_WRBACK;
10783                 goto exit;
10784         }
10785
10786         if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
10787                 ipat = VMX_EPT_IPAT_BIT;
10788                 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
10789                         cache = MTRR_TYPE_WRBACK;
10790                 else
10791                         cache = MTRR_TYPE_UNCACHABLE;
10792                 goto exit;
10793         }
10794
10795         cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
10796
10797 exit:
10798         return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
10799 }
10800
10801 static int vmx_get_lpage_level(void)
10802 {
10803         if (enable_ept && !cpu_has_vmx_ept_1g_page())
10804                 return PT_DIRECTORY_LEVEL;
10805         else
10806                 /* For shadow and EPT supported 1GB page */
10807                 return PT_PDPE_LEVEL;
10808 }
10809
10810 static void vmcs_set_secondary_exec_control(u32 new_ctl)
10811 {
10812         /*
10813          * These bits in the secondary execution controls field
10814          * are dynamic, the others are mostly based on the hypervisor
10815          * architecture and the guest's CPUID.  Do not touch the
10816          * dynamic bits.
10817          */
10818         u32 mask =
10819                 SECONDARY_EXEC_SHADOW_VMCS |
10820                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
10821                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
10822                 SECONDARY_EXEC_DESC;
10823
10824         u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
10825
10826         vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
10827                      (new_ctl & ~mask) | (cur_ctl & mask));
10828 }
10829
10830 /*
10831  * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
10832  * (indicating "allowed-1") if they are supported in the guest's CPUID.
10833  */
10834 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
10835 {
10836         struct vcpu_vmx *vmx = to_vmx(vcpu);
10837         struct kvm_cpuid_entry2 *entry;
10838
10839         vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
10840         vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
10841
10842 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do {            \
10843         if (entry && (entry->_reg & (_cpuid_mask)))                     \
10844                 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask);     \
10845 } while (0)
10846
10847         entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
10848         cr4_fixed1_update(X86_CR4_VME,        edx, bit(X86_FEATURE_VME));
10849         cr4_fixed1_update(X86_CR4_PVI,        edx, bit(X86_FEATURE_VME));
10850         cr4_fixed1_update(X86_CR4_TSD,        edx, bit(X86_FEATURE_TSC));
10851         cr4_fixed1_update(X86_CR4_DE,         edx, bit(X86_FEATURE_DE));
10852         cr4_fixed1_update(X86_CR4_PSE,        edx, bit(X86_FEATURE_PSE));
10853         cr4_fixed1_update(X86_CR4_PAE,        edx, bit(X86_FEATURE_PAE));
10854         cr4_fixed1_update(X86_CR4_MCE,        edx, bit(X86_FEATURE_MCE));
10855         cr4_fixed1_update(X86_CR4_PGE,        edx, bit(X86_FEATURE_PGE));
10856         cr4_fixed1_update(X86_CR4_OSFXSR,     edx, bit(X86_FEATURE_FXSR));
10857         cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
10858         cr4_fixed1_update(X86_CR4_VMXE,       ecx, bit(X86_FEATURE_VMX));
10859         cr4_fixed1_update(X86_CR4_SMXE,       ecx, bit(X86_FEATURE_SMX));
10860         cr4_fixed1_update(X86_CR4_PCIDE,      ecx, bit(X86_FEATURE_PCID));
10861         cr4_fixed1_update(X86_CR4_OSXSAVE,    ecx, bit(X86_FEATURE_XSAVE));
10862
10863         entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
10864         cr4_fixed1_update(X86_CR4_FSGSBASE,   ebx, bit(X86_FEATURE_FSGSBASE));
10865         cr4_fixed1_update(X86_CR4_SMEP,       ebx, bit(X86_FEATURE_SMEP));
10866         cr4_fixed1_update(X86_CR4_SMAP,       ebx, bit(X86_FEATURE_SMAP));
10867         cr4_fixed1_update(X86_CR4_PKE,        ecx, bit(X86_FEATURE_PKU));
10868         cr4_fixed1_update(X86_CR4_UMIP,       ecx, bit(X86_FEATURE_UMIP));
10869
10870 #undef cr4_fixed1_update
10871 }
10872
10873 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
10874 {
10875         struct vcpu_vmx *vmx = to_vmx(vcpu);
10876
10877         if (cpu_has_secondary_exec_ctrls()) {
10878                 vmx_compute_secondary_exec_control(vmx);
10879                 vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
10880         }
10881
10882         if (nested_vmx_allowed(vcpu))
10883                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
10884                         FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
10885         else
10886                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
10887                         ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
10888
10889         if (nested_vmx_allowed(vcpu))
10890                 nested_vmx_cr_fixed1_bits_update(vcpu);
10891 }
10892
10893 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
10894 {
10895         if (func == 1 && nested)
10896                 entry->ecx |= bit(X86_FEATURE_VMX);
10897 }
10898
10899 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
10900                 struct x86_exception *fault)
10901 {
10902         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10903         struct vcpu_vmx *vmx = to_vmx(vcpu);
10904         u32 exit_reason;
10905         unsigned long exit_qualification = vcpu->arch.exit_qualification;
10906
10907         if (vmx->nested.pml_full) {
10908                 exit_reason = EXIT_REASON_PML_FULL;
10909                 vmx->nested.pml_full = false;
10910                 exit_qualification &= INTR_INFO_UNBLOCK_NMI;
10911         } else if (fault->error_code & PFERR_RSVD_MASK)
10912                 exit_reason = EXIT_REASON_EPT_MISCONFIG;
10913         else
10914                 exit_reason = EXIT_REASON_EPT_VIOLATION;
10915
10916         nested_vmx_vmexit(vcpu, exit_reason, 0, exit_qualification);
10917         vmcs12->guest_physical_address = fault->address;
10918 }
10919
10920 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu)
10921 {
10922         return nested_ept_get_cr3(vcpu) & VMX_EPTP_AD_ENABLE_BIT;
10923 }
10924
10925 /* Callbacks for nested_ept_init_mmu_context: */
10926
10927 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
10928 {
10929         /* return the page table to be shadowed - in our case, EPT12 */
10930         return get_vmcs12(vcpu)->ept_pointer;
10931 }
10932
10933 static int nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
10934 {
10935         WARN_ON(mmu_is_nested(vcpu));
10936         if (!valid_ept_address(vcpu, nested_ept_get_cr3(vcpu)))
10937                 return 1;
10938
10939         kvm_init_shadow_ept_mmu(vcpu,
10940                         to_vmx(vcpu)->nested.msrs.ept_caps &
10941                         VMX_EPT_EXECUTE_ONLY_BIT,
10942                         nested_ept_ad_enabled(vcpu),
10943                         nested_ept_get_cr3(vcpu));
10944         vcpu->arch.mmu.set_cr3           = vmx_set_cr3;
10945         vcpu->arch.mmu.get_cr3           = nested_ept_get_cr3;
10946         vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault;
10947
10948         vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
10949         return 0;
10950 }
10951
10952 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
10953 {
10954         vcpu->arch.walk_mmu = &vcpu->arch.mmu;
10955 }
10956
10957 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
10958                                             u16 error_code)
10959 {
10960         bool inequality, bit;
10961
10962         bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
10963         inequality =
10964                 (error_code & vmcs12->page_fault_error_code_mask) !=
10965                  vmcs12->page_fault_error_code_match;
10966         return inequality ^ bit;
10967 }
10968
10969 static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
10970                 struct x86_exception *fault)
10971 {
10972         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10973
10974         WARN_ON(!is_guest_mode(vcpu));
10975
10976         if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code) &&
10977                 !to_vmx(vcpu)->nested.nested_run_pending) {
10978                 vmcs12->vm_exit_intr_error_code = fault->error_code;
10979                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
10980                                   PF_VECTOR | INTR_TYPE_HARD_EXCEPTION |
10981                                   INTR_INFO_DELIVER_CODE_MASK | INTR_INFO_VALID_MASK,
10982                                   fault->address);
10983         } else {
10984                 kvm_inject_page_fault(vcpu, fault);
10985         }
10986 }
10987
10988 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
10989                                                  struct vmcs12 *vmcs12);
10990
10991 static void nested_get_vmcs12_pages(struct kvm_vcpu *vcpu)
10992 {
10993         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10994         struct vcpu_vmx *vmx = to_vmx(vcpu);
10995         struct page *page;
10996         u64 hpa;
10997
10998         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
10999                 /*
11000                  * Translate L1 physical address to host physical
11001                  * address for vmcs02. Keep the page pinned, so this
11002                  * physical address remains valid. We keep a reference
11003                  * to it so we can release it later.
11004                  */
11005                 if (vmx->nested.apic_access_page) { /* shouldn't happen */
11006                         kvm_release_page_dirty(vmx->nested.apic_access_page);
11007                         vmx->nested.apic_access_page = NULL;
11008                 }
11009                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->apic_access_addr);
11010                 /*
11011                  * If translation failed, no matter: This feature asks
11012                  * to exit when accessing the given address, and if it
11013                  * can never be accessed, this feature won't do
11014                  * anything anyway.
11015                  */
11016                 if (!is_error_page(page)) {
11017                         vmx->nested.apic_access_page = page;
11018                         hpa = page_to_phys(vmx->nested.apic_access_page);
11019                         vmcs_write64(APIC_ACCESS_ADDR, hpa);
11020                 } else {
11021                         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
11022                                         SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
11023                 }
11024         }
11025
11026         if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
11027                 if (vmx->nested.virtual_apic_page) { /* shouldn't happen */
11028                         kvm_release_page_dirty(vmx->nested.virtual_apic_page);
11029                         vmx->nested.virtual_apic_page = NULL;
11030                 }
11031                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->virtual_apic_page_addr);
11032
11033                 /*
11034                  * If translation failed, VM entry will fail because
11035                  * prepare_vmcs02 set VIRTUAL_APIC_PAGE_ADDR to -1ull.
11036                  * Failing the vm entry is _not_ what the processor
11037                  * does but it's basically the only possibility we
11038                  * have.  We could still enter the guest if CR8 load
11039                  * exits are enabled, CR8 store exits are enabled, and
11040                  * virtualize APIC access is disabled; in this case
11041                  * the processor would never use the TPR shadow and we
11042                  * could simply clear the bit from the execution
11043                  * control.  But such a configuration is useless, so
11044                  * let's keep the code simple.
11045                  */
11046                 if (!is_error_page(page)) {
11047                         vmx->nested.virtual_apic_page = page;
11048                         hpa = page_to_phys(vmx->nested.virtual_apic_page);
11049                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, hpa);
11050                 }
11051         }
11052
11053         if (nested_cpu_has_posted_intr(vmcs12)) {
11054                 if (vmx->nested.pi_desc_page) { /* shouldn't happen */
11055                         kunmap(vmx->nested.pi_desc_page);
11056                         kvm_release_page_dirty(vmx->nested.pi_desc_page);
11057                         vmx->nested.pi_desc_page = NULL;
11058                 }
11059                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->posted_intr_desc_addr);
11060                 if (is_error_page(page))
11061                         return;
11062                 vmx->nested.pi_desc_page = page;
11063                 vmx->nested.pi_desc = kmap(vmx->nested.pi_desc_page);
11064                 vmx->nested.pi_desc =
11065                         (struct pi_desc *)((void *)vmx->nested.pi_desc +
11066                         (unsigned long)(vmcs12->posted_intr_desc_addr &
11067                         (PAGE_SIZE - 1)));
11068                 vmcs_write64(POSTED_INTR_DESC_ADDR,
11069                         page_to_phys(vmx->nested.pi_desc_page) +
11070                         (unsigned long)(vmcs12->posted_intr_desc_addr &
11071                         (PAGE_SIZE - 1)));
11072         }
11073         if (nested_vmx_prepare_msr_bitmap(vcpu, vmcs12))
11074                 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
11075                               CPU_BASED_USE_MSR_BITMAPS);
11076         else
11077                 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
11078                                 CPU_BASED_USE_MSR_BITMAPS);
11079 }
11080
11081 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
11082 {
11083         u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
11084         struct vcpu_vmx *vmx = to_vmx(vcpu);
11085
11086         if (vcpu->arch.virtual_tsc_khz == 0)
11087                 return;
11088
11089         /* Make sure short timeouts reliably trigger an immediate vmexit.
11090          * hrtimer_start does not guarantee this. */
11091         if (preemption_timeout <= 1) {
11092                 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
11093                 return;
11094         }
11095
11096         preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
11097         preemption_timeout *= 1000000;
11098         do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
11099         hrtimer_start(&vmx->nested.preemption_timer,
11100                       ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
11101 }
11102
11103 static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,
11104                                                struct vmcs12 *vmcs12)
11105 {
11106         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
11107                 return 0;
11108
11109         if (!page_address_valid(vcpu, vmcs12->io_bitmap_a) ||
11110             !page_address_valid(vcpu, vmcs12->io_bitmap_b))
11111                 return -EINVAL;
11112
11113         return 0;
11114 }
11115
11116 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
11117                                                 struct vmcs12 *vmcs12)
11118 {
11119         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
11120                 return 0;
11121
11122         if (!page_address_valid(vcpu, vmcs12->msr_bitmap))
11123                 return -EINVAL;
11124
11125         return 0;
11126 }
11127
11128 static int nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu *vcpu,
11129                                                 struct vmcs12 *vmcs12)
11130 {
11131         if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
11132                 return 0;
11133
11134         if (!page_address_valid(vcpu, vmcs12->virtual_apic_page_addr))
11135                 return -EINVAL;
11136
11137         return 0;
11138 }
11139
11140 /*
11141  * Merge L0's and L1's MSR bitmap, return false to indicate that
11142  * we do not use the hardware.
11143  */
11144 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
11145                                                  struct vmcs12 *vmcs12)
11146 {
11147         int msr;
11148         struct page *page;
11149         unsigned long *msr_bitmap_l1;
11150         unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.vmcs02.msr_bitmap;
11151         /*
11152          * pred_cmd & spec_ctrl are trying to verify two things:
11153          *
11154          * 1. L0 gave a permission to L1 to actually passthrough the MSR. This
11155          *    ensures that we do not accidentally generate an L02 MSR bitmap
11156          *    from the L12 MSR bitmap that is too permissive.
11157          * 2. That L1 or L2s have actually used the MSR. This avoids
11158          *    unnecessarily merging of the bitmap if the MSR is unused. This
11159          *    works properly because we only update the L01 MSR bitmap lazily.
11160          *    So even if L0 should pass L1 these MSRs, the L01 bitmap is only
11161          *    updated to reflect this when L1 (or its L2s) actually write to
11162          *    the MSR.
11163          */
11164         bool pred_cmd = !msr_write_intercepted_l01(vcpu, MSR_IA32_PRED_CMD);
11165         bool spec_ctrl = !msr_write_intercepted_l01(vcpu, MSR_IA32_SPEC_CTRL);
11166
11167         /* Nothing to do if the MSR bitmap is not in use.  */
11168         if (!cpu_has_vmx_msr_bitmap() ||
11169             !nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
11170                 return false;
11171
11172         if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
11173             !pred_cmd && !spec_ctrl)
11174                 return false;
11175
11176         page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->msr_bitmap);
11177         if (is_error_page(page))
11178                 return false;
11179
11180         msr_bitmap_l1 = (unsigned long *)kmap(page);
11181         if (nested_cpu_has_apic_reg_virt(vmcs12)) {
11182                 /*
11183                  * L0 need not intercept reads for MSRs between 0x800 and 0x8ff, it
11184                  * just lets the processor take the value from the virtual-APIC page;
11185                  * take those 256 bits directly from the L1 bitmap.
11186                  */
11187                 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
11188                         unsigned word = msr / BITS_PER_LONG;
11189                         msr_bitmap_l0[word] = msr_bitmap_l1[word];
11190                         msr_bitmap_l0[word + (0x800 / sizeof(long))] = ~0;
11191                 }
11192         } else {
11193                 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
11194                         unsigned word = msr / BITS_PER_LONG;
11195                         msr_bitmap_l0[word] = ~0;
11196                         msr_bitmap_l0[word + (0x800 / sizeof(long))] = ~0;
11197                 }
11198         }
11199
11200         nested_vmx_disable_intercept_for_msr(
11201                 msr_bitmap_l1, msr_bitmap_l0,
11202                 X2APIC_MSR(APIC_TASKPRI),
11203                 MSR_TYPE_W);
11204
11205         if (nested_cpu_has_vid(vmcs12)) {
11206                 nested_vmx_disable_intercept_for_msr(
11207                         msr_bitmap_l1, msr_bitmap_l0,
11208                         X2APIC_MSR(APIC_EOI),
11209                         MSR_TYPE_W);
11210                 nested_vmx_disable_intercept_for_msr(
11211                         msr_bitmap_l1, msr_bitmap_l0,
11212                         X2APIC_MSR(APIC_SELF_IPI),
11213                         MSR_TYPE_W);
11214         }
11215
11216         if (spec_ctrl)
11217                 nested_vmx_disable_intercept_for_msr(
11218                                         msr_bitmap_l1, msr_bitmap_l0,
11219                                         MSR_IA32_SPEC_CTRL,
11220                                         MSR_TYPE_R | MSR_TYPE_W);
11221
11222         if (pred_cmd)
11223                 nested_vmx_disable_intercept_for_msr(
11224                                         msr_bitmap_l1, msr_bitmap_l0,
11225                                         MSR_IA32_PRED_CMD,
11226                                         MSR_TYPE_W);
11227
11228         kunmap(page);
11229         kvm_release_page_clean(page);
11230
11231         return true;
11232 }
11233
11234 static void nested_cache_shadow_vmcs12(struct kvm_vcpu *vcpu,
11235                                        struct vmcs12 *vmcs12)
11236 {
11237         struct vmcs12 *shadow;
11238         struct page *page;
11239
11240         if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
11241             vmcs12->vmcs_link_pointer == -1ull)
11242                 return;
11243
11244         shadow = get_shadow_vmcs12(vcpu);
11245         page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->vmcs_link_pointer);
11246
11247         memcpy(shadow, kmap(page), VMCS12_SIZE);
11248
11249         kunmap(page);
11250         kvm_release_page_clean(page);
11251 }
11252
11253 static void nested_flush_cached_shadow_vmcs12(struct kvm_vcpu *vcpu,
11254                                               struct vmcs12 *vmcs12)
11255 {
11256         struct vcpu_vmx *vmx = to_vmx(vcpu);
11257
11258         if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
11259             vmcs12->vmcs_link_pointer == -1ull)
11260                 return;
11261
11262         kvm_write_guest(vmx->vcpu.kvm, vmcs12->vmcs_link_pointer,
11263                         get_shadow_vmcs12(vcpu), VMCS12_SIZE);
11264 }
11265
11266 static int nested_vmx_check_apic_access_controls(struct kvm_vcpu *vcpu,
11267                                           struct vmcs12 *vmcs12)
11268 {
11269         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
11270             !page_address_valid(vcpu, vmcs12->apic_access_addr))
11271                 return -EINVAL;
11272         else
11273                 return 0;
11274 }
11275
11276 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
11277                                            struct vmcs12 *vmcs12)
11278 {
11279         if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
11280             !nested_cpu_has_apic_reg_virt(vmcs12) &&
11281             !nested_cpu_has_vid(vmcs12) &&
11282             !nested_cpu_has_posted_intr(vmcs12))
11283                 return 0;
11284
11285         /*
11286          * If virtualize x2apic mode is enabled,
11287          * virtualize apic access must be disabled.
11288          */
11289         if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
11290             nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
11291                 return -EINVAL;
11292
11293         /*
11294          * If virtual interrupt delivery is enabled,
11295          * we must exit on external interrupts.
11296          */
11297         if (nested_cpu_has_vid(vmcs12) &&
11298            !nested_exit_on_intr(vcpu))
11299                 return -EINVAL;
11300
11301         /*
11302          * bits 15:8 should be zero in posted_intr_nv,
11303          * the descriptor address has been already checked
11304          * in nested_get_vmcs12_pages.
11305          */
11306         if (nested_cpu_has_posted_intr(vmcs12) &&
11307            (!nested_cpu_has_vid(vmcs12) ||
11308             !nested_exit_intr_ack_set(vcpu) ||
11309             vmcs12->posted_intr_nv & 0xff00))
11310                 return -EINVAL;
11311
11312         /* tpr shadow is needed by all apicv features. */
11313         if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
11314                 return -EINVAL;
11315
11316         return 0;
11317 }
11318
11319 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
11320                                        unsigned long count_field,
11321                                        unsigned long addr_field)
11322 {
11323         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11324         int maxphyaddr;
11325         u64 count, addr;
11326
11327         if (vmcs12_read_any(vmcs12, count_field, &count) ||
11328             vmcs12_read_any(vmcs12, addr_field, &addr)) {
11329                 WARN_ON(1);
11330                 return -EINVAL;
11331         }
11332         if (count == 0)
11333                 return 0;
11334         maxphyaddr = cpuid_maxphyaddr(vcpu);
11335         if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
11336             (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
11337                 pr_debug_ratelimited(
11338                         "nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
11339                         addr_field, maxphyaddr, count, addr);
11340                 return -EINVAL;
11341         }
11342         return 0;
11343 }
11344
11345 static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
11346                                                 struct vmcs12 *vmcs12)
11347 {
11348         if (vmcs12->vm_exit_msr_load_count == 0 &&
11349             vmcs12->vm_exit_msr_store_count == 0 &&
11350             vmcs12->vm_entry_msr_load_count == 0)
11351                 return 0; /* Fast path */
11352         if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
11353                                         VM_EXIT_MSR_LOAD_ADDR) ||
11354             nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
11355                                         VM_EXIT_MSR_STORE_ADDR) ||
11356             nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
11357                                         VM_ENTRY_MSR_LOAD_ADDR))
11358                 return -EINVAL;
11359         return 0;
11360 }
11361
11362 static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
11363                                          struct vmcs12 *vmcs12)
11364 {
11365         u64 address = vmcs12->pml_address;
11366         int maxphyaddr = cpuid_maxphyaddr(vcpu);
11367
11368         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML)) {
11369                 if (!nested_cpu_has_ept(vmcs12) ||
11370                     !IS_ALIGNED(address, 4096)  ||
11371                     address >> maxphyaddr)
11372                         return -EINVAL;
11373         }
11374
11375         return 0;
11376 }
11377
11378 static int nested_vmx_check_shadow_vmcs_controls(struct kvm_vcpu *vcpu,
11379                                                  struct vmcs12 *vmcs12)
11380 {
11381         if (!nested_cpu_has_shadow_vmcs(vmcs12))
11382                 return 0;
11383
11384         if (!page_address_valid(vcpu, vmcs12->vmread_bitmap) ||
11385             !page_address_valid(vcpu, vmcs12->vmwrite_bitmap))
11386                 return -EINVAL;
11387
11388         return 0;
11389 }
11390
11391 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
11392                                        struct vmx_msr_entry *e)
11393 {
11394         /* x2APIC MSR accesses are not allowed */
11395         if (vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8)
11396                 return -EINVAL;
11397         if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
11398             e->index == MSR_IA32_UCODE_REV)
11399                 return -EINVAL;
11400         if (e->reserved != 0)
11401                 return -EINVAL;
11402         return 0;
11403 }
11404
11405 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
11406                                      struct vmx_msr_entry *e)
11407 {
11408         if (e->index == MSR_FS_BASE ||
11409             e->index == MSR_GS_BASE ||
11410             e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
11411             nested_vmx_msr_check_common(vcpu, e))
11412                 return -EINVAL;
11413         return 0;
11414 }
11415
11416 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
11417                                       struct vmx_msr_entry *e)
11418 {
11419         if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
11420             nested_vmx_msr_check_common(vcpu, e))
11421                 return -EINVAL;
11422         return 0;
11423 }
11424
11425 /*
11426  * Load guest's/host's msr at nested entry/exit.
11427  * return 0 for success, entry index for failure.
11428  */
11429 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
11430 {
11431         u32 i;
11432         struct vmx_msr_entry e;
11433         struct msr_data msr;
11434
11435         msr.host_initiated = false;
11436         for (i = 0; i < count; i++) {
11437                 if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
11438                                         &e, sizeof(e))) {
11439                         pr_debug_ratelimited(
11440                                 "%s cannot read MSR entry (%u, 0x%08llx)\n",
11441                                 __func__, i, gpa + i * sizeof(e));
11442                         goto fail;
11443                 }
11444                 if (nested_vmx_load_msr_check(vcpu, &e)) {
11445                         pr_debug_ratelimited(
11446                                 "%s check failed (%u, 0x%x, 0x%x)\n",
11447                                 __func__, i, e.index, e.reserved);
11448                         goto fail;
11449                 }
11450                 msr.index = e.index;
11451                 msr.data = e.value;
11452                 if (kvm_set_msr(vcpu, &msr)) {
11453                         pr_debug_ratelimited(
11454                                 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
11455                                 __func__, i, e.index, e.value);
11456                         goto fail;
11457                 }
11458         }
11459         return 0;
11460 fail:
11461         return i + 1;
11462 }
11463
11464 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
11465 {
11466         u32 i;
11467         struct vmx_msr_entry e;
11468
11469         for (i = 0; i < count; i++) {
11470                 struct msr_data msr_info;
11471                 if (kvm_vcpu_read_guest(vcpu,
11472                                         gpa + i * sizeof(e),
11473                                         &e, 2 * sizeof(u32))) {
11474                         pr_debug_ratelimited(
11475                                 "%s cannot read MSR entry (%u, 0x%08llx)\n",
11476                                 __func__, i, gpa + i * sizeof(e));
11477                         return -EINVAL;
11478                 }
11479                 if (nested_vmx_store_msr_check(vcpu, &e)) {
11480                         pr_debug_ratelimited(
11481                                 "%s check failed (%u, 0x%x, 0x%x)\n",
11482                                 __func__, i, e.index, e.reserved);
11483                         return -EINVAL;
11484                 }
11485                 msr_info.host_initiated = false;
11486                 msr_info.index = e.index;
11487                 if (kvm_get_msr(vcpu, &msr_info)) {
11488                         pr_debug_ratelimited(
11489                                 "%s cannot read MSR (%u, 0x%x)\n",
11490                                 __func__, i, e.index);
11491                         return -EINVAL;
11492                 }
11493                 if (kvm_vcpu_write_guest(vcpu,
11494                                          gpa + i * sizeof(e) +
11495                                              offsetof(struct vmx_msr_entry, value),
11496                                          &msr_info.data, sizeof(msr_info.data))) {
11497                         pr_debug_ratelimited(
11498                                 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
11499                                 __func__, i, e.index, msr_info.data);
11500                         return -EINVAL;
11501                 }
11502         }
11503         return 0;
11504 }
11505
11506 static bool nested_cr3_valid(struct kvm_vcpu *vcpu, unsigned long val)
11507 {
11508         unsigned long invalid_mask;
11509
11510         invalid_mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
11511         return (val & invalid_mask) == 0;
11512 }
11513
11514 /*
11515  * Load guest's/host's cr3 at nested entry/exit. nested_ept is true if we are
11516  * emulating VM entry into a guest with EPT enabled.
11517  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
11518  * is assigned to entry_failure_code on failure.
11519  */
11520 static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool nested_ept,
11521                                u32 *entry_failure_code)
11522 {
11523         if (cr3 != kvm_read_cr3(vcpu) || (!nested_ept && pdptrs_changed(vcpu))) {
11524                 if (!nested_cr3_valid(vcpu, cr3)) {
11525                         *entry_failure_code = ENTRY_FAIL_DEFAULT;
11526                         return 1;
11527                 }
11528
11529                 /*
11530                  * If PAE paging and EPT are both on, CR3 is not used by the CPU and
11531                  * must not be dereferenced.
11532                  */
11533                 if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu) &&
11534                     !nested_ept) {
11535                         if (!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)) {
11536                                 *entry_failure_code = ENTRY_FAIL_PDPTE;
11537                                 return 1;
11538                         }
11539                 }
11540         }
11541
11542         if (!nested_ept)
11543                 kvm_mmu_new_cr3(vcpu, cr3, false);
11544
11545         vcpu->arch.cr3 = cr3;
11546         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
11547
11548         kvm_init_mmu(vcpu, false);
11549
11550         return 0;
11551 }
11552
11553 static void prepare_vmcs02_full(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11554 {
11555         struct vcpu_vmx *vmx = to_vmx(vcpu);
11556
11557         vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
11558         vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
11559         vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
11560         vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
11561         vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
11562         vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
11563         vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
11564         vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
11565         vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
11566         vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
11567         vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
11568         vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
11569         vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
11570         vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
11571         vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
11572         vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
11573         vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
11574         vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
11575         vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
11576         vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
11577         vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
11578         vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
11579         vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
11580         vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
11581         vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
11582         vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
11583         vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
11584         vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
11585         vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
11586         vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
11587         vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
11588
11589         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
11590         vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
11591                 vmcs12->guest_pending_dbg_exceptions);
11592         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
11593         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
11594
11595         if (nested_cpu_has_xsaves(vmcs12))
11596                 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
11597         vmcs_write64(VMCS_LINK_POINTER, -1ull);
11598
11599         if (cpu_has_vmx_posted_intr())
11600                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
11601
11602         /*
11603          * Whether page-faults are trapped is determined by a combination of
11604          * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
11605          * If enable_ept, L0 doesn't care about page faults and we should
11606          * set all of these to L1's desires. However, if !enable_ept, L0 does
11607          * care about (at least some) page faults, and because it is not easy
11608          * (if at all possible?) to merge L0 and L1's desires, we simply ask
11609          * to exit on each and every L2 page fault. This is done by setting
11610          * MASK=MATCH=0 and (see below) EB.PF=1.
11611          * Note that below we don't need special code to set EB.PF beyond the
11612          * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
11613          * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
11614          * !enable_ept, EB.PF is 1, so the "or" will always be 1.
11615          */
11616         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
11617                 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
11618         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
11619                 enable_ept ? vmcs12->page_fault_error_code_match : 0);
11620
11621         /* All VMFUNCs are currently emulated through L0 vmexits.  */
11622         if (cpu_has_vmx_vmfunc())
11623                 vmcs_write64(VM_FUNCTION_CONTROL, 0);
11624
11625         if (cpu_has_vmx_apicv()) {
11626                 vmcs_write64(EOI_EXIT_BITMAP0, vmcs12->eoi_exit_bitmap0);
11627                 vmcs_write64(EOI_EXIT_BITMAP1, vmcs12->eoi_exit_bitmap1);
11628                 vmcs_write64(EOI_EXIT_BITMAP2, vmcs12->eoi_exit_bitmap2);
11629                 vmcs_write64(EOI_EXIT_BITMAP3, vmcs12->eoi_exit_bitmap3);
11630         }
11631
11632         /*
11633          * Set host-state according to L0's settings (vmcs12 is irrelevant here)
11634          * Some constant fields are set here by vmx_set_constant_host_state().
11635          * Other fields are different per CPU, and will be set later when
11636          * vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
11637          */
11638         vmx_set_constant_host_state(vmx);
11639
11640         /*
11641          * Set the MSR load/store lists to match L0's settings.
11642          */
11643         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
11644         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
11645         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
11646         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
11647         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
11648
11649         set_cr4_guest_host_mask(vmx);
11650
11651         if (vmx_mpx_supported())
11652                 vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
11653
11654         if (enable_vpid) {
11655                 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02)
11656                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
11657                 else
11658                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
11659         }
11660
11661         /*
11662          * L1 may access the L2's PDPTR, so save them to construct vmcs12
11663          */
11664         if (enable_ept) {
11665                 vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
11666                 vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
11667                 vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
11668                 vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
11669         }
11670
11671         if (cpu_has_vmx_msr_bitmap())
11672                 vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
11673 }
11674
11675 /*
11676  * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
11677  * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
11678  * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
11679  * guest in a way that will both be appropriate to L1's requests, and our
11680  * needs. In addition to modifying the active vmcs (which is vmcs02), this
11681  * function also has additional necessary side-effects, like setting various
11682  * vcpu->arch fields.
11683  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
11684  * is assigned to entry_failure_code on failure.
11685  */
11686 static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
11687                           u32 *entry_failure_code)
11688 {
11689         struct vcpu_vmx *vmx = to_vmx(vcpu);
11690         u32 exec_control, vmcs12_exec_ctrl;
11691
11692         if (vmx->nested.dirty_vmcs12) {
11693                 prepare_vmcs02_full(vcpu, vmcs12);
11694                 vmx->nested.dirty_vmcs12 = false;
11695         }
11696
11697         /*
11698          * First, the fields that are shadowed.  This must be kept in sync
11699          * with vmx_shadow_fields.h.
11700          */
11701
11702         vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
11703         vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
11704         vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
11705         vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
11706         vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
11707
11708         /*
11709          * Not in vmcs02: GUEST_PML_INDEX, HOST_FS_SELECTOR, HOST_GS_SELECTOR,
11710          * HOST_FS_BASE, HOST_GS_BASE.
11711          */
11712
11713         if (vmx->nested.nested_run_pending &&
11714             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
11715                 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
11716                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
11717         } else {
11718                 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
11719                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
11720         }
11721         if (vmx->nested.nested_run_pending) {
11722                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
11723                              vmcs12->vm_entry_intr_info_field);
11724                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
11725                              vmcs12->vm_entry_exception_error_code);
11726                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
11727                              vmcs12->vm_entry_instruction_len);
11728                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
11729                              vmcs12->guest_interruptibility_info);
11730                 vmx->loaded_vmcs->nmi_known_unmasked =
11731                         !(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
11732         } else {
11733                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
11734         }
11735         vmx_set_rflags(vcpu, vmcs12->guest_rflags);
11736
11737         exec_control = vmcs12->pin_based_vm_exec_control;
11738
11739         /* Preemption timer setting is only taken from vmcs01.  */
11740         exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
11741         exec_control |= vmcs_config.pin_based_exec_ctrl;
11742         if (vmx->hv_deadline_tsc == -1)
11743                 exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
11744
11745         /* Posted interrupts setting is only taken from vmcs12.  */
11746         if (nested_cpu_has_posted_intr(vmcs12)) {
11747                 vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
11748                 vmx->nested.pi_pending = false;
11749         } else {
11750                 exec_control &= ~PIN_BASED_POSTED_INTR;
11751         }
11752
11753         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
11754
11755         vmx->nested.preemption_timer_expired = false;
11756         if (nested_cpu_has_preemption_timer(vmcs12))
11757                 vmx_start_preemption_timer(vcpu);
11758
11759         if (cpu_has_secondary_exec_ctrls()) {
11760                 exec_control = vmx->secondary_exec_control;
11761
11762                 /* Take the following fields only from vmcs12 */
11763                 exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
11764                                   SECONDARY_EXEC_ENABLE_INVPCID |
11765                                   SECONDARY_EXEC_RDTSCP |
11766                                   SECONDARY_EXEC_XSAVES |
11767                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
11768                                   SECONDARY_EXEC_APIC_REGISTER_VIRT |
11769                                   SECONDARY_EXEC_ENABLE_VMFUNC);
11770                 if (nested_cpu_has(vmcs12,
11771                                    CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
11772                         vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
11773                                 ~SECONDARY_EXEC_ENABLE_PML;
11774                         exec_control |= vmcs12_exec_ctrl;
11775                 }
11776
11777                 /* VMCS shadowing for L2 is emulated for now */
11778                 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
11779
11780                 if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
11781                         vmcs_write16(GUEST_INTR_STATUS,
11782                                 vmcs12->guest_intr_status);
11783
11784                 /*
11785                  * Write an illegal value to APIC_ACCESS_ADDR. Later,
11786                  * nested_get_vmcs12_pages will either fix it up or
11787                  * remove the VM execution control.
11788                  */
11789                 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
11790                         vmcs_write64(APIC_ACCESS_ADDR, -1ull);
11791
11792                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
11793         }
11794
11795         /*
11796          * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
11797          * entry, but only if the current (host) sp changed from the value
11798          * we wrote last (vmx->host_rsp). This cache is no longer relevant
11799          * if we switch vmcs, and rather than hold a separate cache per vmcs,
11800          * here we just force the write to happen on entry.
11801          */
11802         vmx->host_rsp = 0;
11803
11804         exec_control = vmx_exec_control(vmx); /* L0's desires */
11805         exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
11806         exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
11807         exec_control &= ~CPU_BASED_TPR_SHADOW;
11808         exec_control |= vmcs12->cpu_based_vm_exec_control;
11809
11810         /*
11811          * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR. Later, if
11812          * nested_get_vmcs12_pages can't fix it up, the illegal value
11813          * will result in a VM entry failure.
11814          */
11815         if (exec_control & CPU_BASED_TPR_SHADOW) {
11816                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
11817                 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
11818         } else {
11819 #ifdef CONFIG_X86_64
11820                 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
11821                                 CPU_BASED_CR8_STORE_EXITING;
11822 #endif
11823         }
11824
11825         /*
11826          * A vmexit (to either L1 hypervisor or L0 userspace) is always needed
11827          * for I/O port accesses.
11828          */
11829         exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
11830         exec_control |= CPU_BASED_UNCOND_IO_EXITING;
11831
11832         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
11833
11834         /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
11835          * bitwise-or of what L1 wants to trap for L2, and what we want to
11836          * trap. Note that CR0.TS also needs updating - we do this later.
11837          */
11838         update_exception_bitmap(vcpu);
11839         vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
11840         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
11841
11842         /* L2->L1 exit controls are emulated - the hardware exit is to L0 so
11843          * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
11844          * bits are further modified by vmx_set_efer() below.
11845          */
11846         vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
11847
11848         /* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
11849          * emulated by vmx_set_efer(), below.
11850          */
11851         vm_entry_controls_init(vmx, 
11852                 (vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
11853                         ~VM_ENTRY_IA32E_MODE) |
11854                 (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
11855
11856         if (vmx->nested.nested_run_pending &&
11857             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
11858                 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
11859                 vcpu->arch.pat = vmcs12->guest_ia32_pat;
11860         } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
11861                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
11862         }
11863
11864         vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
11865
11866         if (kvm_has_tsc_control)
11867                 decache_tsc_multiplier(vmx);
11868
11869         if (enable_vpid) {
11870                 /*
11871                  * There is no direct mapping between vpid02 and vpid12, the
11872                  * vpid02 is per-vCPU for L0 and reused while the value of
11873                  * vpid12 is changed w/ one invvpid during nested vmentry.
11874                  * The vpid12 is allocated by L1 for L2, so it will not
11875                  * influence global bitmap(for vpid01 and vpid02 allocation)
11876                  * even if spawn a lot of nested vCPUs.
11877                  */
11878                 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02) {
11879                         if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
11880                                 vmx->nested.last_vpid = vmcs12->virtual_processor_id;
11881                                 __vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
11882                         }
11883                 } else {
11884                         vmx_flush_tlb(vcpu, true);
11885                 }
11886         }
11887
11888         if (enable_pml) {
11889                 /*
11890                  * Conceptually we want to copy the PML address and index from
11891                  * vmcs01 here, and then back to vmcs01 on nested vmexit. But,
11892                  * since we always flush the log on each vmexit, this happens
11893                  * to be equivalent to simply resetting the fields in vmcs02.
11894                  */
11895                 ASSERT(vmx->pml_pg);
11896                 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
11897                 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
11898         }
11899
11900         if (nested_cpu_has_ept(vmcs12)) {
11901                 if (nested_ept_init_mmu_context(vcpu)) {
11902                         *entry_failure_code = ENTRY_FAIL_DEFAULT;
11903                         return 1;
11904                 }
11905         } else if (nested_cpu_has2(vmcs12,
11906                                    SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
11907                 vmx_flush_tlb(vcpu, true);
11908         }
11909
11910         /*
11911          * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
11912          * bits which we consider mandatory enabled.
11913          * The CR0_READ_SHADOW is what L2 should have expected to read given
11914          * the specifications by L1; It's not enough to take
11915          * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
11916          * have more bits than L1 expected.
11917          */
11918         vmx_set_cr0(vcpu, vmcs12->guest_cr0);
11919         vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
11920
11921         vmx_set_cr4(vcpu, vmcs12->guest_cr4);
11922         vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
11923
11924         if (vmx->nested.nested_run_pending &&
11925             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
11926                 vcpu->arch.efer = vmcs12->guest_ia32_efer;
11927         else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
11928                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
11929         else
11930                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
11931         /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
11932         vmx_set_efer(vcpu, vcpu->arch.efer);
11933
11934         /*
11935          * Guest state is invalid and unrestricted guest is disabled,
11936          * which means L1 attempted VMEntry to L2 with invalid state.
11937          * Fail the VMEntry.
11938          */
11939         if (vmx->emulation_required) {
11940                 *entry_failure_code = ENTRY_FAIL_DEFAULT;
11941                 return 1;
11942         }
11943
11944         /* Shadow page tables on either EPT or shadow page tables. */
11945         if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
11946                                 entry_failure_code))
11947                 return 1;
11948
11949         if (!enable_ept)
11950                 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
11951
11952         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
11953         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
11954         return 0;
11955 }
11956
11957 static int nested_vmx_check_nmi_controls(struct vmcs12 *vmcs12)
11958 {
11959         if (!nested_cpu_has_nmi_exiting(vmcs12) &&
11960             nested_cpu_has_virtual_nmis(vmcs12))
11961                 return -EINVAL;
11962
11963         if (!nested_cpu_has_virtual_nmis(vmcs12) &&
11964             nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING))
11965                 return -EINVAL;
11966
11967         return 0;
11968 }
11969
11970 static int check_vmentry_prereqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11971 {
11972         struct vcpu_vmx *vmx = to_vmx(vcpu);
11973
11974         if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
11975             vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT)
11976                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11977
11978         if (nested_vmx_check_io_bitmap_controls(vcpu, vmcs12))
11979                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11980
11981         if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12))
11982                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11983
11984         if (nested_vmx_check_apic_access_controls(vcpu, vmcs12))
11985                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11986
11987         if (nested_vmx_check_tpr_shadow_controls(vcpu, vmcs12))
11988                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11989
11990         if (nested_vmx_check_apicv_controls(vcpu, vmcs12))
11991                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11992
11993         if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12))
11994                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11995
11996         if (nested_vmx_check_pml_controls(vcpu, vmcs12))
11997                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11998
11999         if (nested_vmx_check_shadow_vmcs_controls(vcpu, vmcs12))
12000                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12001
12002         if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
12003                                 vmx->nested.msrs.procbased_ctls_low,
12004                                 vmx->nested.msrs.procbased_ctls_high) ||
12005             (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
12006              !vmx_control_verify(vmcs12->secondary_vm_exec_control,
12007                                  vmx->nested.msrs.secondary_ctls_low,
12008                                  vmx->nested.msrs.secondary_ctls_high)) ||
12009             !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
12010                                 vmx->nested.msrs.pinbased_ctls_low,
12011                                 vmx->nested.msrs.pinbased_ctls_high) ||
12012             !vmx_control_verify(vmcs12->vm_exit_controls,
12013                                 vmx->nested.msrs.exit_ctls_low,
12014                                 vmx->nested.msrs.exit_ctls_high) ||
12015             !vmx_control_verify(vmcs12->vm_entry_controls,
12016                                 vmx->nested.msrs.entry_ctls_low,
12017                                 vmx->nested.msrs.entry_ctls_high))
12018                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12019
12020         if (nested_vmx_check_nmi_controls(vmcs12))
12021                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12022
12023         if (nested_cpu_has_vmfunc(vmcs12)) {
12024                 if (vmcs12->vm_function_control &
12025                     ~vmx->nested.msrs.vmfunc_controls)
12026                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12027
12028                 if (nested_cpu_has_eptp_switching(vmcs12)) {
12029                         if (!nested_cpu_has_ept(vmcs12) ||
12030                             !page_address_valid(vcpu, vmcs12->eptp_list_address))
12031                                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12032                 }
12033         }
12034
12035         if (vmcs12->cr3_target_count > nested_cpu_vmx_misc_cr3_count(vcpu))
12036                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12037
12038         if (!nested_host_cr0_valid(vcpu, vmcs12->host_cr0) ||
12039             !nested_host_cr4_valid(vcpu, vmcs12->host_cr4) ||
12040             !nested_cr3_valid(vcpu, vmcs12->host_cr3))
12041                 return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
12042
12043         /*
12044          * From the Intel SDM, volume 3:
12045          * Fields relevant to VM-entry event injection must be set properly.
12046          * These fields are the VM-entry interruption-information field, the
12047          * VM-entry exception error code, and the VM-entry instruction length.
12048          */
12049         if (vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) {
12050                 u32 intr_info = vmcs12->vm_entry_intr_info_field;
12051                 u8 vector = intr_info & INTR_INFO_VECTOR_MASK;
12052                 u32 intr_type = intr_info & INTR_INFO_INTR_TYPE_MASK;
12053                 bool has_error_code = intr_info & INTR_INFO_DELIVER_CODE_MASK;
12054                 bool should_have_error_code;
12055                 bool urg = nested_cpu_has2(vmcs12,
12056                                            SECONDARY_EXEC_UNRESTRICTED_GUEST);
12057                 bool prot_mode = !urg || vmcs12->guest_cr0 & X86_CR0_PE;
12058
12059                 /* VM-entry interruption-info field: interruption type */
12060                 if (intr_type == INTR_TYPE_RESERVED ||
12061                     (intr_type == INTR_TYPE_OTHER_EVENT &&
12062                      !nested_cpu_supports_monitor_trap_flag(vcpu)))
12063                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12064
12065                 /* VM-entry interruption-info field: vector */
12066                 if ((intr_type == INTR_TYPE_NMI_INTR && vector != NMI_VECTOR) ||
12067                     (intr_type == INTR_TYPE_HARD_EXCEPTION && vector > 31) ||
12068                     (intr_type == INTR_TYPE_OTHER_EVENT && vector != 0))
12069                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12070
12071                 /* VM-entry interruption-info field: deliver error code */
12072                 should_have_error_code =
12073                         intr_type == INTR_TYPE_HARD_EXCEPTION && prot_mode &&
12074                         x86_exception_has_error_code(vector);
12075                 if (has_error_code != should_have_error_code)
12076                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12077
12078                 /* VM-entry exception error code */
12079                 if (has_error_code &&
12080                     vmcs12->vm_entry_exception_error_code & GENMASK(31, 15))
12081                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12082
12083                 /* VM-entry interruption-info field: reserved bits */
12084                 if (intr_info & INTR_INFO_RESVD_BITS_MASK)
12085                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12086
12087                 /* VM-entry instruction length */
12088                 switch (intr_type) {
12089                 case INTR_TYPE_SOFT_EXCEPTION:
12090                 case INTR_TYPE_SOFT_INTR:
12091                 case INTR_TYPE_PRIV_SW_EXCEPTION:
12092                         if ((vmcs12->vm_entry_instruction_len > 15) ||
12093                             (vmcs12->vm_entry_instruction_len == 0 &&
12094                              !nested_cpu_has_zero_length_injection(vcpu)))
12095                                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12096                 }
12097         }
12098
12099         return 0;
12100 }
12101
12102 static int nested_vmx_check_vmcs_link_ptr(struct kvm_vcpu *vcpu,
12103                                           struct vmcs12 *vmcs12)
12104 {
12105         int r;
12106         struct page *page;
12107         struct vmcs12 *shadow;
12108
12109         if (vmcs12->vmcs_link_pointer == -1ull)
12110                 return 0;
12111
12112         if (!page_address_valid(vcpu, vmcs12->vmcs_link_pointer))
12113                 return -EINVAL;
12114
12115         page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->vmcs_link_pointer);
12116         if (is_error_page(page))
12117                 return -EINVAL;
12118
12119         r = 0;
12120         shadow = kmap(page);
12121         if (shadow->hdr.revision_id != VMCS12_REVISION ||
12122             shadow->hdr.shadow_vmcs != nested_cpu_has_shadow_vmcs(vmcs12))
12123                 r = -EINVAL;
12124         kunmap(page);
12125         kvm_release_page_clean(page);
12126         return r;
12127 }
12128
12129 static int check_vmentry_postreqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12130                                   u32 *exit_qual)
12131 {
12132         bool ia32e;
12133
12134         *exit_qual = ENTRY_FAIL_DEFAULT;
12135
12136         if (!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0) ||
12137             !nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4))
12138                 return 1;
12139
12140         if (nested_vmx_check_vmcs_link_ptr(vcpu, vmcs12)) {
12141                 *exit_qual = ENTRY_FAIL_VMCS_LINK_PTR;
12142                 return 1;
12143         }
12144
12145         /*
12146          * If the load IA32_EFER VM-entry control is 1, the following checks
12147          * are performed on the field for the IA32_EFER MSR:
12148          * - Bits reserved in the IA32_EFER MSR must be 0.
12149          * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
12150          *   the IA-32e mode guest VM-exit control. It must also be identical
12151          *   to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
12152          *   CR0.PG) is 1.
12153          */
12154         if (to_vmx(vcpu)->nested.nested_run_pending &&
12155             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {
12156                 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
12157                 if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
12158                     ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
12159                     ((vmcs12->guest_cr0 & X86_CR0_PG) &&
12160                      ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME)))
12161                         return 1;
12162         }
12163
12164         /*
12165          * If the load IA32_EFER VM-exit control is 1, bits reserved in the
12166          * IA32_EFER MSR must be 0 in the field for that register. In addition,
12167          * the values of the LMA and LME bits in the field must each be that of
12168          * the host address-space size VM-exit control.
12169          */
12170         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
12171                 ia32e = (vmcs12->vm_exit_controls &
12172                          VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
12173                 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
12174                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
12175                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LME))
12176                         return 1;
12177         }
12178
12179         if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS) &&
12180                 (is_noncanonical_address(vmcs12->guest_bndcfgs & PAGE_MASK, vcpu) ||
12181                 (vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD)))
12182                         return 1;
12183
12184         return 0;
12185 }
12186
12187 /*
12188  * If exit_qual is NULL, this is being called from state restore (either RSM
12189  * or KVM_SET_NESTED_STATE).  Otherwise it's called from vmlaunch/vmresume.
12190  */
12191 static int enter_vmx_non_root_mode(struct kvm_vcpu *vcpu, u32 *exit_qual)
12192 {
12193         struct vcpu_vmx *vmx = to_vmx(vcpu);
12194         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
12195         bool from_vmentry = !!exit_qual;
12196         u32 dummy_exit_qual;
12197         int r = 0;
12198
12199         enter_guest_mode(vcpu);
12200
12201         if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
12202                 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
12203
12204         vmx_switch_vmcs(vcpu, &vmx->nested.vmcs02);
12205         vmx_segment_cache_clear(vmx);
12206
12207         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
12208                 vcpu->arch.tsc_offset += vmcs12->tsc_offset;
12209
12210         r = EXIT_REASON_INVALID_STATE;
12211         if (prepare_vmcs02(vcpu, vmcs12, from_vmentry ? exit_qual : &dummy_exit_qual))
12212                 goto fail;
12213
12214         if (from_vmentry) {
12215                 nested_get_vmcs12_pages(vcpu);
12216
12217                 r = EXIT_REASON_MSR_LOAD_FAIL;
12218                 *exit_qual = nested_vmx_load_msr(vcpu,
12219                                                  vmcs12->vm_entry_msr_load_addr,
12220                                                  vmcs12->vm_entry_msr_load_count);
12221                 if (*exit_qual)
12222                         goto fail;
12223         } else {
12224                 /*
12225                  * The MMU is not initialized to point at the right entities yet and
12226                  * "get pages" would need to read data from the guest (i.e. we will
12227                  * need to perform gpa to hpa translation). Request a call
12228                  * to nested_get_vmcs12_pages before the next VM-entry.  The MSRs
12229                  * have already been set at vmentry time and should not be reset.
12230                  */
12231                 kvm_make_request(KVM_REQ_GET_VMCS12_PAGES, vcpu);
12232         }
12233
12234         /*
12235          * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
12236          * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
12237          * returned as far as L1 is concerned. It will only return (and set
12238          * the success flag) when L2 exits (see nested_vmx_vmexit()).
12239          */
12240         return 0;
12241
12242 fail:
12243         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
12244                 vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
12245         leave_guest_mode(vcpu);
12246         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
12247         return r;
12248 }
12249
12250 /*
12251  * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
12252  * for running an L2 nested guest.
12253  */
12254 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
12255 {
12256         struct vmcs12 *vmcs12;
12257         struct vcpu_vmx *vmx = to_vmx(vcpu);
12258         u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
12259         u32 exit_qual;
12260         int ret;
12261
12262         if (!nested_vmx_check_permission(vcpu))
12263                 return 1;
12264
12265         if (!nested_vmx_check_vmcs12(vcpu))
12266                 goto out;
12267
12268         vmcs12 = get_vmcs12(vcpu);
12269
12270         /*
12271          * Can't VMLAUNCH or VMRESUME a shadow VMCS. Despite the fact
12272          * that there *is* a valid VMCS pointer, RFLAGS.CF is set
12273          * rather than RFLAGS.ZF, and no error number is stored to the
12274          * VM-instruction error field.
12275          */
12276         if (vmcs12->hdr.shadow_vmcs) {
12277                 nested_vmx_failInvalid(vcpu);
12278                 goto out;
12279         }
12280
12281         if (enable_shadow_vmcs)
12282                 copy_shadow_to_vmcs12(vmx);
12283
12284         /*
12285          * The nested entry process starts with enforcing various prerequisites
12286          * on vmcs12 as required by the Intel SDM, and act appropriately when
12287          * they fail: As the SDM explains, some conditions should cause the
12288          * instruction to fail, while others will cause the instruction to seem
12289          * to succeed, but return an EXIT_REASON_INVALID_STATE.
12290          * To speed up the normal (success) code path, we should avoid checking
12291          * for misconfigurations which will anyway be caught by the processor
12292          * when using the merged vmcs02.
12293          */
12294         if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS) {
12295                 nested_vmx_failValid(vcpu,
12296                                      VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
12297                 goto out;
12298         }
12299
12300         if (vmcs12->launch_state == launch) {
12301                 nested_vmx_failValid(vcpu,
12302                         launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
12303                                : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
12304                 goto out;
12305         }
12306
12307         ret = check_vmentry_prereqs(vcpu, vmcs12);
12308         if (ret) {
12309                 nested_vmx_failValid(vcpu, ret);
12310                 goto out;
12311         }
12312
12313         /*
12314          * After this point, the trap flag no longer triggers a singlestep trap
12315          * on the vm entry instructions; don't call kvm_skip_emulated_instruction.
12316          * This is not 100% correct; for performance reasons, we delegate most
12317          * of the checks on host state to the processor.  If those fail,
12318          * the singlestep trap is missed.
12319          */
12320         skip_emulated_instruction(vcpu);
12321
12322         ret = check_vmentry_postreqs(vcpu, vmcs12, &exit_qual);
12323         if (ret) {
12324                 nested_vmx_entry_failure(vcpu, vmcs12,
12325                                          EXIT_REASON_INVALID_STATE, exit_qual);
12326                 return 1;
12327         }
12328
12329         /*
12330          * We're finally done with prerequisite checking, and can start with
12331          * the nested entry.
12332          */
12333
12334         vmx->nested.nested_run_pending = 1;
12335         ret = enter_vmx_non_root_mode(vcpu, &exit_qual);
12336         if (ret) {
12337                 nested_vmx_entry_failure(vcpu, vmcs12, ret, exit_qual);
12338                 vmx->nested.nested_run_pending = 0;
12339                 return 1;
12340         }
12341
12342         /*
12343          * Must happen outside of enter_vmx_non_root_mode() as it will
12344          * also be used as part of restoring nVMX state for
12345          * snapshot restore (migration).
12346          *
12347          * In this flow, it is assumed that vmcs12 cache was
12348          * trasferred as part of captured nVMX state and should
12349          * therefore not be read from guest memory (which may not
12350          * exist on destination host yet).
12351          */
12352         nested_cache_shadow_vmcs12(vcpu, vmcs12);
12353
12354         /*
12355          * If we're entering a halted L2 vcpu and the L2 vcpu won't be woken
12356          * by event injection, halt vcpu.
12357          */
12358         if ((vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT) &&
12359             !(vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK)) {
12360                 vmx->nested.nested_run_pending = 0;
12361                 return kvm_vcpu_halt(vcpu);
12362         }
12363         return 1;
12364
12365 out:
12366         return kvm_skip_emulated_instruction(vcpu);
12367 }
12368
12369 /*
12370  * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
12371  * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
12372  * This function returns the new value we should put in vmcs12.guest_cr0.
12373  * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
12374  *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
12375  *     available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
12376  *     didn't trap the bit, because if L1 did, so would L0).
12377  *  2. Bits that L1 asked to trap (and therefore L0 also did) could not have
12378  *     been modified by L2, and L1 knows it. So just leave the old value of
12379  *     the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
12380  *     isn't relevant, because if L0 traps this bit it can set it to anything.
12381  *  3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
12382  *     changed these bits, and therefore they need to be updated, but L0
12383  *     didn't necessarily allow them to be changed in GUEST_CR0 - and rather
12384  *     put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
12385  */
12386 static inline unsigned long
12387 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12388 {
12389         return
12390         /*1*/   (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
12391         /*2*/   (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
12392         /*3*/   (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
12393                         vcpu->arch.cr0_guest_owned_bits));
12394 }
12395
12396 static inline unsigned long
12397 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12398 {
12399         return
12400         /*1*/   (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
12401         /*2*/   (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
12402         /*3*/   (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
12403                         vcpu->arch.cr4_guest_owned_bits));
12404 }
12405
12406 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
12407                                        struct vmcs12 *vmcs12)
12408 {
12409         u32 idt_vectoring;
12410         unsigned int nr;
12411
12412         if (vcpu->arch.exception.injected) {
12413                 nr = vcpu->arch.exception.nr;
12414                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
12415
12416                 if (kvm_exception_is_soft(nr)) {
12417                         vmcs12->vm_exit_instruction_len =
12418                                 vcpu->arch.event_exit_inst_len;
12419                         idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
12420                 } else
12421                         idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
12422
12423                 if (vcpu->arch.exception.has_error_code) {
12424                         idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
12425                         vmcs12->idt_vectoring_error_code =
12426                                 vcpu->arch.exception.error_code;
12427                 }
12428
12429                 vmcs12->idt_vectoring_info_field = idt_vectoring;
12430         } else if (vcpu->arch.nmi_injected) {
12431                 vmcs12->idt_vectoring_info_field =
12432                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
12433         } else if (vcpu->arch.interrupt.injected) {
12434                 nr = vcpu->arch.interrupt.nr;
12435                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
12436
12437                 if (vcpu->arch.interrupt.soft) {
12438                         idt_vectoring |= INTR_TYPE_SOFT_INTR;
12439                         vmcs12->vm_entry_instruction_len =
12440                                 vcpu->arch.event_exit_inst_len;
12441                 } else
12442                         idt_vectoring |= INTR_TYPE_EXT_INTR;
12443
12444                 vmcs12->idt_vectoring_info_field = idt_vectoring;
12445         }
12446 }
12447
12448 static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
12449 {
12450         struct vcpu_vmx *vmx = to_vmx(vcpu);
12451         unsigned long exit_qual;
12452         bool block_nested_events =
12453             vmx->nested.nested_run_pending || kvm_event_needs_reinjection(vcpu);
12454
12455         if (vcpu->arch.exception.pending &&
12456                 nested_vmx_check_exception(vcpu, &exit_qual)) {
12457                 if (block_nested_events)
12458                         return -EBUSY;
12459                 nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
12460                 return 0;
12461         }
12462
12463         if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
12464             vmx->nested.preemption_timer_expired) {
12465                 if (block_nested_events)
12466                         return -EBUSY;
12467                 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
12468                 return 0;
12469         }
12470
12471         if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
12472                 if (block_nested_events)
12473                         return -EBUSY;
12474                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
12475                                   NMI_VECTOR | INTR_TYPE_NMI_INTR |
12476                                   INTR_INFO_VALID_MASK, 0);
12477                 /*
12478                  * The NMI-triggered VM exit counts as injection:
12479                  * clear this one and block further NMIs.
12480                  */
12481                 vcpu->arch.nmi_pending = 0;
12482                 vmx_set_nmi_mask(vcpu, true);
12483                 return 0;
12484         }
12485
12486         if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
12487             nested_exit_on_intr(vcpu)) {
12488                 if (block_nested_events)
12489                         return -EBUSY;
12490                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
12491                 return 0;
12492         }
12493
12494         vmx_complete_nested_posted_interrupt(vcpu);
12495         return 0;
12496 }
12497
12498 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
12499 {
12500         ktime_t remaining =
12501                 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
12502         u64 value;
12503
12504         if (ktime_to_ns(remaining) <= 0)
12505                 return 0;
12506
12507         value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
12508         do_div(value, 1000000);
12509         return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
12510 }
12511
12512 /*
12513  * Update the guest state fields of vmcs12 to reflect changes that
12514  * occurred while L2 was running. (The "IA-32e mode guest" bit of the
12515  * VM-entry controls is also updated, since this is really a guest
12516  * state bit.)
12517  */
12518 static void sync_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12519 {
12520         vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
12521         vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
12522
12523         vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
12524         vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
12525         vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
12526
12527         vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
12528         vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
12529         vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
12530         vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
12531         vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
12532         vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
12533         vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
12534         vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
12535         vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
12536         vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
12537         vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
12538         vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
12539         vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
12540         vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
12541         vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
12542         vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
12543         vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
12544         vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
12545         vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
12546         vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
12547         vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
12548         vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
12549         vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
12550         vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
12551         vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
12552         vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
12553         vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
12554         vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
12555         vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
12556         vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
12557         vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
12558         vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
12559         vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
12560         vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
12561         vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
12562         vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
12563
12564         vmcs12->guest_interruptibility_info =
12565                 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
12566         vmcs12->guest_pending_dbg_exceptions =
12567                 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
12568         if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
12569                 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
12570         else
12571                 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
12572
12573         if (nested_cpu_has_preemption_timer(vmcs12)) {
12574                 if (vmcs12->vm_exit_controls &
12575                     VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
12576                         vmcs12->vmx_preemption_timer_value =
12577                                 vmx_get_preemption_timer_value(vcpu);
12578                 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
12579         }
12580
12581         /*
12582          * In some cases (usually, nested EPT), L2 is allowed to change its
12583          * own CR3 without exiting. If it has changed it, we must keep it.
12584          * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
12585          * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
12586          *
12587          * Additionally, restore L2's PDPTR to vmcs12.
12588          */
12589         if (enable_ept) {
12590                 vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
12591                 vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
12592                 vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
12593                 vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
12594                 vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
12595         }
12596
12597         vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
12598
12599         if (nested_cpu_has_vid(vmcs12))
12600                 vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
12601
12602         vmcs12->vm_entry_controls =
12603                 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
12604                 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
12605
12606         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
12607                 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
12608                 vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
12609         }
12610
12611         /* TODO: These cannot have changed unless we have MSR bitmaps and
12612          * the relevant bit asks not to trap the change */
12613         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
12614                 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
12615         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
12616                 vmcs12->guest_ia32_efer = vcpu->arch.efer;
12617         vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
12618         vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
12619         vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
12620         if (kvm_mpx_supported())
12621                 vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
12622 }
12623
12624 /*
12625  * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
12626  * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
12627  * and this function updates it to reflect the changes to the guest state while
12628  * L2 was running (and perhaps made some exits which were handled directly by L0
12629  * without going back to L1), and to reflect the exit reason.
12630  * Note that we do not have to copy here all VMCS fields, just those that
12631  * could have changed by the L2 guest or the exit - i.e., the guest-state and
12632  * exit-information fields only. Other fields are modified by L1 with VMWRITE,
12633  * which already writes to vmcs12 directly.
12634  */
12635 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12636                            u32 exit_reason, u32 exit_intr_info,
12637                            unsigned long exit_qualification)
12638 {
12639         /* update guest state fields: */
12640         sync_vmcs12(vcpu, vmcs12);
12641
12642         /* update exit information fields: */
12643
12644         vmcs12->vm_exit_reason = exit_reason;
12645         vmcs12->exit_qualification = exit_qualification;
12646         vmcs12->vm_exit_intr_info = exit_intr_info;
12647
12648         vmcs12->idt_vectoring_info_field = 0;
12649         vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
12650         vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
12651
12652         if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
12653                 vmcs12->launch_state = 1;
12654
12655                 /* vm_entry_intr_info_field is cleared on exit. Emulate this
12656                  * instead of reading the real value. */
12657                 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
12658
12659                 /*
12660                  * Transfer the event that L0 or L1 may wanted to inject into
12661                  * L2 to IDT_VECTORING_INFO_FIELD.
12662                  */
12663                 vmcs12_save_pending_event(vcpu, vmcs12);
12664         }
12665
12666         /*
12667          * Drop what we picked up for L2 via vmx_complete_interrupts. It is
12668          * preserved above and would only end up incorrectly in L1.
12669          */
12670         vcpu->arch.nmi_injected = false;
12671         kvm_clear_exception_queue(vcpu);
12672         kvm_clear_interrupt_queue(vcpu);
12673 }
12674
12675 static void load_vmcs12_mmu_host_state(struct kvm_vcpu *vcpu,
12676                         struct vmcs12 *vmcs12)
12677 {
12678         u32 entry_failure_code;
12679
12680         nested_ept_uninit_mmu_context(vcpu);
12681
12682         /*
12683          * Only PDPTE load can fail as the value of cr3 was checked on entry and
12684          * couldn't have changed.
12685          */
12686         if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
12687                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
12688
12689         if (!enable_ept)
12690                 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
12691 }
12692
12693 /*
12694  * A part of what we need to when the nested L2 guest exits and we want to
12695  * run its L1 parent, is to reset L1's guest state to the host state specified
12696  * in vmcs12.
12697  * This function is to be called not only on normal nested exit, but also on
12698  * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
12699  * Failures During or After Loading Guest State").
12700  * This function should be called when the active VMCS is L1's (vmcs01).
12701  */
12702 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
12703                                    struct vmcs12 *vmcs12)
12704 {
12705         struct kvm_segment seg;
12706
12707         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
12708                 vcpu->arch.efer = vmcs12->host_ia32_efer;
12709         else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
12710                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
12711         else
12712                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
12713         vmx_set_efer(vcpu, vcpu->arch.efer);
12714
12715         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
12716         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
12717         vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
12718         /*
12719          * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
12720          * actually changed, because vmx_set_cr0 refers to efer set above.
12721          *
12722          * CR0_GUEST_HOST_MASK is already set in the original vmcs01
12723          * (KVM doesn't change it);
12724          */
12725         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
12726         vmx_set_cr0(vcpu, vmcs12->host_cr0);
12727
12728         /* Same as above - no reason to call set_cr4_guest_host_mask().  */
12729         vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
12730         vmx_set_cr4(vcpu, vmcs12->host_cr4);
12731
12732         load_vmcs12_mmu_host_state(vcpu, vmcs12);
12733
12734         /*
12735          * If vmcs01 don't use VPID, CPU flushes TLB on every
12736          * VMEntry/VMExit. Thus, no need to flush TLB.
12737          *
12738          * If vmcs12 uses VPID, TLB entries populated by L2 are
12739          * tagged with vmx->nested.vpid02 while L1 entries are tagged
12740          * with vmx->vpid. Thus, no need to flush TLB.
12741          *
12742          * Therefore, flush TLB only in case vmcs01 uses VPID and
12743          * vmcs12 don't use VPID as in this case L1 & L2 TLB entries
12744          * are both tagged with vmx->vpid.
12745          */
12746         if (enable_vpid &&
12747             !(nested_cpu_has_vpid(vmcs12) && to_vmx(vcpu)->nested.vpid02)) {
12748                 vmx_flush_tlb(vcpu, true);
12749         }
12750
12751         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
12752         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
12753         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
12754         vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
12755         vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
12756         vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
12757         vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
12758
12759         /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1.  */
12760         if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
12761                 vmcs_write64(GUEST_BNDCFGS, 0);
12762
12763         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
12764                 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
12765                 vcpu->arch.pat = vmcs12->host_ia32_pat;
12766         }
12767         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
12768                 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
12769                         vmcs12->host_ia32_perf_global_ctrl);
12770
12771         /* Set L1 segment info according to Intel SDM
12772             27.5.2 Loading Host Segment and Descriptor-Table Registers */
12773         seg = (struct kvm_segment) {
12774                 .base = 0,
12775                 .limit = 0xFFFFFFFF,
12776                 .selector = vmcs12->host_cs_selector,
12777                 .type = 11,
12778                 .present = 1,
12779                 .s = 1,
12780                 .g = 1
12781         };
12782         if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
12783                 seg.l = 1;
12784         else
12785                 seg.db = 1;
12786         vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
12787         seg = (struct kvm_segment) {
12788                 .base = 0,
12789                 .limit = 0xFFFFFFFF,
12790                 .type = 3,
12791                 .present = 1,
12792                 .s = 1,
12793                 .db = 1,
12794                 .g = 1
12795         };
12796         seg.selector = vmcs12->host_ds_selector;
12797         vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
12798         seg.selector = vmcs12->host_es_selector;
12799         vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
12800         seg.selector = vmcs12->host_ss_selector;
12801         vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
12802         seg.selector = vmcs12->host_fs_selector;
12803         seg.base = vmcs12->host_fs_base;
12804         vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
12805         seg.selector = vmcs12->host_gs_selector;
12806         seg.base = vmcs12->host_gs_base;
12807         vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
12808         seg = (struct kvm_segment) {
12809                 .base = vmcs12->host_tr_base,
12810                 .limit = 0x67,
12811                 .selector = vmcs12->host_tr_selector,
12812                 .type = 11,
12813                 .present = 1
12814         };
12815         vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
12816
12817         kvm_set_dr(vcpu, 7, 0x400);
12818         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
12819
12820         if (cpu_has_vmx_msr_bitmap())
12821                 vmx_update_msr_bitmap(vcpu);
12822
12823         if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
12824                                 vmcs12->vm_exit_msr_load_count))
12825                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
12826 }
12827
12828 /*
12829  * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
12830  * and modify vmcs12 to make it see what it would expect to see there if
12831  * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
12832  */
12833 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
12834                               u32 exit_intr_info,
12835                               unsigned long exit_qualification)
12836 {
12837         struct vcpu_vmx *vmx = to_vmx(vcpu);
12838         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
12839
12840         /* trying to cancel vmlaunch/vmresume is a bug */
12841         WARN_ON_ONCE(vmx->nested.nested_run_pending);
12842
12843         /*
12844          * The only expected VM-instruction error is "VM entry with
12845          * invalid control field(s)." Anything else indicates a
12846          * problem with L0.
12847          */
12848         WARN_ON_ONCE(vmx->fail && (vmcs_read32(VM_INSTRUCTION_ERROR) !=
12849                                    VMXERR_ENTRY_INVALID_CONTROL_FIELD));
12850
12851         leave_guest_mode(vcpu);
12852
12853         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
12854                 vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
12855
12856         if (likely(!vmx->fail)) {
12857                 if (exit_reason == -1)
12858                         sync_vmcs12(vcpu, vmcs12);
12859                 else
12860                         prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
12861                                        exit_qualification);
12862
12863                 /*
12864                  * Must happen outside of sync_vmcs12() as it will
12865                  * also be used to capture vmcs12 cache as part of
12866                  * capturing nVMX state for snapshot (migration).
12867                  *
12868                  * Otherwise, this flush will dirty guest memory at a
12869                  * point it is already assumed by user-space to be
12870                  * immutable.
12871                  */
12872                 nested_flush_cached_shadow_vmcs12(vcpu, vmcs12);
12873
12874                 if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
12875                                          vmcs12->vm_exit_msr_store_count))
12876                         nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
12877         }
12878
12879         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
12880         vm_entry_controls_reset_shadow(vmx);
12881         vm_exit_controls_reset_shadow(vmx);
12882         vmx_segment_cache_clear(vmx);
12883
12884         /* Update any VMCS fields that might have changed while L2 ran */
12885         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
12886         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
12887         vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
12888         if (vmx->hv_deadline_tsc == -1)
12889                 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
12890                                 PIN_BASED_VMX_PREEMPTION_TIMER);
12891         else
12892                 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
12893                               PIN_BASED_VMX_PREEMPTION_TIMER);
12894         if (kvm_has_tsc_control)
12895                 decache_tsc_multiplier(vmx);
12896
12897         if (vmx->nested.change_vmcs01_virtual_apic_mode) {
12898                 vmx->nested.change_vmcs01_virtual_apic_mode = false;
12899                 vmx_set_virtual_apic_mode(vcpu);
12900         } else if (!nested_cpu_has_ept(vmcs12) &&
12901                    nested_cpu_has2(vmcs12,
12902                                    SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
12903                 vmx_flush_tlb(vcpu, true);
12904         }
12905
12906         /* This is needed for same reason as it was needed in prepare_vmcs02 */
12907         vmx->host_rsp = 0;
12908
12909         /* Unpin physical memory we referred to in vmcs02 */
12910         if (vmx->nested.apic_access_page) {
12911                 kvm_release_page_dirty(vmx->nested.apic_access_page);
12912                 vmx->nested.apic_access_page = NULL;
12913         }
12914         if (vmx->nested.virtual_apic_page) {
12915                 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
12916                 vmx->nested.virtual_apic_page = NULL;
12917         }
12918         if (vmx->nested.pi_desc_page) {
12919                 kunmap(vmx->nested.pi_desc_page);
12920                 kvm_release_page_dirty(vmx->nested.pi_desc_page);
12921                 vmx->nested.pi_desc_page = NULL;
12922                 vmx->nested.pi_desc = NULL;
12923         }
12924
12925         /*
12926          * We are now running in L2, mmu_notifier will force to reload the
12927          * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
12928          */
12929         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
12930
12931         if (enable_shadow_vmcs && exit_reason != -1)
12932                 vmx->nested.sync_shadow_vmcs = true;
12933
12934         /* in case we halted in L2 */
12935         vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
12936
12937         if (likely(!vmx->fail)) {
12938                 /*
12939                  * TODO: SDM says that with acknowledge interrupt on
12940                  * exit, bit 31 of the VM-exit interrupt information
12941                  * (valid interrupt) is always set to 1 on
12942                  * EXIT_REASON_EXTERNAL_INTERRUPT, so we shouldn't
12943                  * need kvm_cpu_has_interrupt().  See the commit
12944                  * message for details.
12945                  */
12946                 if (nested_exit_intr_ack_set(vcpu) &&
12947                     exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT &&
12948                     kvm_cpu_has_interrupt(vcpu)) {
12949                         int irq = kvm_cpu_get_interrupt(vcpu);
12950                         WARN_ON(irq < 0);
12951                         vmcs12->vm_exit_intr_info = irq |
12952                                 INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
12953                 }
12954
12955                 if (exit_reason != -1)
12956                         trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
12957                                                        vmcs12->exit_qualification,
12958                                                        vmcs12->idt_vectoring_info_field,
12959                                                        vmcs12->vm_exit_intr_info,
12960                                                        vmcs12->vm_exit_intr_error_code,
12961                                                        KVM_ISA_VMX);
12962
12963                 load_vmcs12_host_state(vcpu, vmcs12);
12964
12965                 return;
12966         }
12967         
12968         /*
12969          * After an early L2 VM-entry failure, we're now back
12970          * in L1 which thinks it just finished a VMLAUNCH or
12971          * VMRESUME instruction, so we need to set the failure
12972          * flag and the VM-instruction error field of the VMCS
12973          * accordingly.
12974          */
12975         nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
12976
12977         load_vmcs12_mmu_host_state(vcpu, vmcs12);
12978
12979         /*
12980          * The emulated instruction was already skipped in
12981          * nested_vmx_run, but the updated RIP was never
12982          * written back to the vmcs01.
12983          */
12984         skip_emulated_instruction(vcpu);
12985         vmx->fail = 0;
12986 }
12987
12988 /*
12989  * Forcibly leave nested mode in order to be able to reset the VCPU later on.
12990  */
12991 static void vmx_leave_nested(struct kvm_vcpu *vcpu)
12992 {
12993         if (is_guest_mode(vcpu)) {
12994                 to_vmx(vcpu)->nested.nested_run_pending = 0;
12995                 nested_vmx_vmexit(vcpu, -1, 0, 0);
12996         }
12997         free_nested(to_vmx(vcpu));
12998 }
12999
13000 /*
13001  * L1's failure to enter L2 is a subset of a normal exit, as explained in
13002  * 23.7 "VM-entry failures during or after loading guest state" (this also
13003  * lists the acceptable exit-reason and exit-qualification parameters).
13004  * It should only be called before L2 actually succeeded to run, and when
13005  * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
13006  */
13007 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
13008                         struct vmcs12 *vmcs12,
13009                         u32 reason, unsigned long qualification)
13010 {
13011         load_vmcs12_host_state(vcpu, vmcs12);
13012         vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
13013         vmcs12->exit_qualification = qualification;
13014         nested_vmx_succeed(vcpu);
13015         if (enable_shadow_vmcs)
13016                 to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
13017 }
13018
13019 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
13020                                struct x86_instruction_info *info,
13021                                enum x86_intercept_stage stage)
13022 {
13023         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
13024         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
13025
13026         /*
13027          * RDPID causes #UD if disabled through secondary execution controls.
13028          * Because it is marked as EmulateOnUD, we need to intercept it here.
13029          */
13030         if (info->intercept == x86_intercept_rdtscp &&
13031             !nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
13032                 ctxt->exception.vector = UD_VECTOR;
13033                 ctxt->exception.error_code_valid = false;
13034                 return X86EMUL_PROPAGATE_FAULT;
13035         }
13036
13037         /* TODO: check more intercepts... */
13038         return X86EMUL_CONTINUE;
13039 }
13040
13041 #ifdef CONFIG_X86_64
13042 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
13043 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
13044                                   u64 divisor, u64 *result)
13045 {
13046         u64 low = a << shift, high = a >> (64 - shift);
13047
13048         /* To avoid the overflow on divq */
13049         if (high >= divisor)
13050                 return 1;
13051
13052         /* Low hold the result, high hold rem which is discarded */
13053         asm("divq %2\n\t" : "=a" (low), "=d" (high) :
13054             "rm" (divisor), "0" (low), "1" (high));
13055         *result = low;
13056
13057         return 0;
13058 }
13059
13060 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
13061 {
13062         struct vcpu_vmx *vmx;
13063         u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
13064
13065         if (kvm_mwait_in_guest(vcpu->kvm))
13066                 return -EOPNOTSUPP;
13067
13068         vmx = to_vmx(vcpu);
13069         tscl = rdtsc();
13070         guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
13071         delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
13072         lapic_timer_advance_cycles = nsec_to_cycles(vcpu, lapic_timer_advance_ns);
13073
13074         if (delta_tsc > lapic_timer_advance_cycles)
13075                 delta_tsc -= lapic_timer_advance_cycles;
13076         else
13077                 delta_tsc = 0;
13078
13079         /* Convert to host delta tsc if tsc scaling is enabled */
13080         if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
13081                         u64_shl_div_u64(delta_tsc,
13082                                 kvm_tsc_scaling_ratio_frac_bits,
13083                                 vcpu->arch.tsc_scaling_ratio,
13084                                 &delta_tsc))
13085                 return -ERANGE;
13086
13087         /*
13088          * If the delta tsc can't fit in the 32 bit after the multi shift,
13089          * we can't use the preemption timer.
13090          * It's possible that it fits on later vmentries, but checking
13091          * on every vmentry is costly so we just use an hrtimer.
13092          */
13093         if (delta_tsc >> (cpu_preemption_timer_multi + 32))
13094                 return -ERANGE;
13095
13096         vmx->hv_deadline_tsc = tscl + delta_tsc;
13097         vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
13098                         PIN_BASED_VMX_PREEMPTION_TIMER);
13099
13100         return delta_tsc == 0;
13101 }
13102
13103 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
13104 {
13105         struct vcpu_vmx *vmx = to_vmx(vcpu);
13106         vmx->hv_deadline_tsc = -1;
13107         vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
13108                         PIN_BASED_VMX_PREEMPTION_TIMER);
13109 }
13110 #endif
13111
13112 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
13113 {
13114         if (!kvm_pause_in_guest(vcpu->kvm))
13115                 shrink_ple_window(vcpu);
13116 }
13117
13118 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
13119                                      struct kvm_memory_slot *slot)
13120 {
13121         kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
13122         kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
13123 }
13124
13125 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
13126                                        struct kvm_memory_slot *slot)
13127 {
13128         kvm_mmu_slot_set_dirty(kvm, slot);
13129 }
13130
13131 static void vmx_flush_log_dirty(struct kvm *kvm)
13132 {
13133         kvm_flush_pml_buffers(kvm);
13134 }
13135
13136 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
13137 {
13138         struct vmcs12 *vmcs12;
13139         struct vcpu_vmx *vmx = to_vmx(vcpu);
13140         gpa_t gpa;
13141         struct page *page = NULL;
13142         u64 *pml_address;
13143
13144         if (is_guest_mode(vcpu)) {
13145                 WARN_ON_ONCE(vmx->nested.pml_full);
13146
13147                 /*
13148                  * Check if PML is enabled for the nested guest.
13149                  * Whether eptp bit 6 is set is already checked
13150                  * as part of A/D emulation.
13151                  */
13152                 vmcs12 = get_vmcs12(vcpu);
13153                 if (!nested_cpu_has_pml(vmcs12))
13154                         return 0;
13155
13156                 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
13157                         vmx->nested.pml_full = true;
13158                         return 1;
13159                 }
13160
13161                 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
13162
13163                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->pml_address);
13164                 if (is_error_page(page))
13165                         return 0;
13166
13167                 pml_address = kmap(page);
13168                 pml_address[vmcs12->guest_pml_index--] = gpa;
13169                 kunmap(page);
13170                 kvm_release_page_clean(page);
13171         }
13172
13173         return 0;
13174 }
13175
13176 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
13177                                            struct kvm_memory_slot *memslot,
13178                                            gfn_t offset, unsigned long mask)
13179 {
13180         kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
13181 }
13182
13183 static void __pi_post_block(struct kvm_vcpu *vcpu)
13184 {
13185         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
13186         struct pi_desc old, new;
13187         unsigned int dest;
13188
13189         do {
13190                 old.control = new.control = pi_desc->control;
13191                 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
13192                      "Wakeup handler not enabled while the VCPU is blocked\n");
13193
13194                 dest = cpu_physical_id(vcpu->cpu);
13195
13196                 if (x2apic_enabled())
13197                         new.ndst = dest;
13198                 else
13199                         new.ndst = (dest << 8) & 0xFF00;
13200
13201                 /* set 'NV' to 'notification vector' */
13202                 new.nv = POSTED_INTR_VECTOR;
13203         } while (cmpxchg64(&pi_desc->control, old.control,
13204                            new.control) != old.control);
13205
13206         if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
13207                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
13208                 list_del(&vcpu->blocked_vcpu_list);
13209                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
13210                 vcpu->pre_pcpu = -1;
13211         }
13212 }
13213
13214 /*
13215  * This routine does the following things for vCPU which is going
13216  * to be blocked if VT-d PI is enabled.
13217  * - Store the vCPU to the wakeup list, so when interrupts happen
13218  *   we can find the right vCPU to wake up.
13219  * - Change the Posted-interrupt descriptor as below:
13220  *      'NDST' <-- vcpu->pre_pcpu
13221  *      'NV' <-- POSTED_INTR_WAKEUP_VECTOR
13222  * - If 'ON' is set during this process, which means at least one
13223  *   interrupt is posted for this vCPU, we cannot block it, in
13224  *   this case, return 1, otherwise, return 0.
13225  *
13226  */
13227 static int pi_pre_block(struct kvm_vcpu *vcpu)
13228 {
13229         unsigned int dest;
13230         struct pi_desc old, new;
13231         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
13232
13233         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
13234                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
13235                 !kvm_vcpu_apicv_active(vcpu))
13236                 return 0;
13237
13238         WARN_ON(irqs_disabled());
13239         local_irq_disable();
13240         if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
13241                 vcpu->pre_pcpu = vcpu->cpu;
13242                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
13243                 list_add_tail(&vcpu->blocked_vcpu_list,
13244                               &per_cpu(blocked_vcpu_on_cpu,
13245                                        vcpu->pre_pcpu));
13246                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
13247         }
13248
13249         do {
13250                 old.control = new.control = pi_desc->control;
13251
13252                 WARN((pi_desc->sn == 1),
13253                      "Warning: SN field of posted-interrupts "
13254                      "is set before blocking\n");
13255
13256                 /*
13257                  * Since vCPU can be preempted during this process,
13258                  * vcpu->cpu could be different with pre_pcpu, we
13259                  * need to set pre_pcpu as the destination of wakeup
13260                  * notification event, then we can find the right vCPU
13261                  * to wakeup in wakeup handler if interrupts happen
13262                  * when the vCPU is in blocked state.
13263                  */
13264                 dest = cpu_physical_id(vcpu->pre_pcpu);
13265
13266                 if (x2apic_enabled())
13267                         new.ndst = dest;
13268                 else
13269                         new.ndst = (dest << 8) & 0xFF00;
13270
13271                 /* set 'NV' to 'wakeup vector' */
13272                 new.nv = POSTED_INTR_WAKEUP_VECTOR;
13273         } while (cmpxchg64(&pi_desc->control, old.control,
13274                            new.control) != old.control);
13275
13276         /* We should not block the vCPU if an interrupt is posted for it.  */
13277         if (pi_test_on(pi_desc) == 1)
13278                 __pi_post_block(vcpu);
13279
13280         local_irq_enable();
13281         return (vcpu->pre_pcpu == -1);
13282 }
13283
13284 static int vmx_pre_block(struct kvm_vcpu *vcpu)
13285 {
13286         if (pi_pre_block(vcpu))
13287                 return 1;
13288
13289         if (kvm_lapic_hv_timer_in_use(vcpu))
13290                 kvm_lapic_switch_to_sw_timer(vcpu);
13291
13292         return 0;
13293 }
13294
13295 static void pi_post_block(struct kvm_vcpu *vcpu)
13296 {
13297         if (vcpu->pre_pcpu == -1)
13298                 return;
13299
13300         WARN_ON(irqs_disabled());
13301         local_irq_disable();
13302         __pi_post_block(vcpu);
13303         local_irq_enable();
13304 }
13305
13306 static void vmx_post_block(struct kvm_vcpu *vcpu)
13307 {
13308         if (kvm_x86_ops->set_hv_timer)
13309                 kvm_lapic_switch_to_hv_timer(vcpu);
13310
13311         pi_post_block(vcpu);
13312 }
13313
13314 /*
13315  * vmx_update_pi_irte - set IRTE for Posted-Interrupts
13316  *
13317  * @kvm: kvm
13318  * @host_irq: host irq of the interrupt
13319  * @guest_irq: gsi of the interrupt
13320  * @set: set or unset PI
13321  * returns 0 on success, < 0 on failure
13322  */
13323 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
13324                               uint32_t guest_irq, bool set)
13325 {
13326         struct kvm_kernel_irq_routing_entry *e;
13327         struct kvm_irq_routing_table *irq_rt;
13328         struct kvm_lapic_irq irq;
13329         struct kvm_vcpu *vcpu;
13330         struct vcpu_data vcpu_info;
13331         int idx, ret = 0;
13332
13333         if (!kvm_arch_has_assigned_device(kvm) ||
13334                 !irq_remapping_cap(IRQ_POSTING_CAP) ||
13335                 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
13336                 return 0;
13337
13338         idx = srcu_read_lock(&kvm->irq_srcu);
13339         irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
13340         if (guest_irq >= irq_rt->nr_rt_entries ||
13341             hlist_empty(&irq_rt->map[guest_irq])) {
13342                 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
13343                              guest_irq, irq_rt->nr_rt_entries);
13344                 goto out;
13345         }
13346
13347         hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
13348                 if (e->type != KVM_IRQ_ROUTING_MSI)
13349                         continue;
13350                 /*
13351                  * VT-d PI cannot support posting multicast/broadcast
13352                  * interrupts to a vCPU, we still use interrupt remapping
13353                  * for these kind of interrupts.
13354                  *
13355                  * For lowest-priority interrupts, we only support
13356                  * those with single CPU as the destination, e.g. user
13357                  * configures the interrupts via /proc/irq or uses
13358                  * irqbalance to make the interrupts single-CPU.
13359                  *
13360                  * We will support full lowest-priority interrupt later.
13361                  */
13362
13363                 kvm_set_msi_irq(kvm, e, &irq);
13364                 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
13365                         /*
13366                          * Make sure the IRTE is in remapped mode if
13367                          * we don't handle it in posted mode.
13368                          */
13369                         ret = irq_set_vcpu_affinity(host_irq, NULL);
13370                         if (ret < 0) {
13371                                 printk(KERN_INFO
13372                                    "failed to back to remapped mode, irq: %u\n",
13373                                    host_irq);
13374                                 goto out;
13375                         }
13376
13377                         continue;
13378                 }
13379
13380                 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
13381                 vcpu_info.vector = irq.vector;
13382
13383                 trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
13384                                 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
13385
13386                 if (set)
13387                         ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
13388                 else
13389                         ret = irq_set_vcpu_affinity(host_irq, NULL);
13390
13391                 if (ret < 0) {
13392                         printk(KERN_INFO "%s: failed to update PI IRTE\n",
13393                                         __func__);
13394                         goto out;
13395                 }
13396         }
13397
13398         ret = 0;
13399 out:
13400         srcu_read_unlock(&kvm->irq_srcu, idx);
13401         return ret;
13402 }
13403
13404 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
13405 {
13406         if (vcpu->arch.mcg_cap & MCG_LMCE_P)
13407                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
13408                         FEATURE_CONTROL_LMCE;
13409         else
13410                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
13411                         ~FEATURE_CONTROL_LMCE;
13412 }
13413
13414 static int vmx_smi_allowed(struct kvm_vcpu *vcpu)
13415 {
13416         /* we need a nested vmexit to enter SMM, postpone if run is pending */
13417         if (to_vmx(vcpu)->nested.nested_run_pending)
13418                 return 0;
13419         return 1;
13420 }
13421
13422 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
13423 {
13424         struct vcpu_vmx *vmx = to_vmx(vcpu);
13425
13426         vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
13427         if (vmx->nested.smm.guest_mode)
13428                 nested_vmx_vmexit(vcpu, -1, 0, 0);
13429
13430         vmx->nested.smm.vmxon = vmx->nested.vmxon;
13431         vmx->nested.vmxon = false;
13432         vmx_clear_hlt(vcpu);
13433         return 0;
13434 }
13435
13436 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
13437 {
13438         struct vcpu_vmx *vmx = to_vmx(vcpu);
13439         int ret;
13440
13441         if (vmx->nested.smm.vmxon) {
13442                 vmx->nested.vmxon = true;
13443                 vmx->nested.smm.vmxon = false;
13444         }
13445
13446         if (vmx->nested.smm.guest_mode) {
13447                 vcpu->arch.hflags &= ~HF_SMM_MASK;
13448                 ret = enter_vmx_non_root_mode(vcpu, NULL);
13449                 vcpu->arch.hflags |= HF_SMM_MASK;
13450                 if (ret)
13451                         return ret;
13452
13453                 vmx->nested.smm.guest_mode = false;
13454         }
13455         return 0;
13456 }
13457
13458 static int enable_smi_window(struct kvm_vcpu *vcpu)
13459 {
13460         return 0;
13461 }
13462
13463 static int vmx_get_nested_state(struct kvm_vcpu *vcpu,
13464                                 struct kvm_nested_state __user *user_kvm_nested_state,
13465                                 u32 user_data_size)
13466 {
13467         struct vcpu_vmx *vmx;
13468         struct vmcs12 *vmcs12;
13469         struct kvm_nested_state kvm_state = {
13470                 .flags = 0,
13471                 .format = 0,
13472                 .size = sizeof(kvm_state),
13473                 .vmx.vmxon_pa = -1ull,
13474                 .vmx.vmcs_pa = -1ull,
13475         };
13476
13477         if (!vcpu)
13478                 return kvm_state.size + 2 * VMCS12_SIZE;
13479
13480         vmx = to_vmx(vcpu);
13481         vmcs12 = get_vmcs12(vcpu);
13482         if (nested_vmx_allowed(vcpu) &&
13483             (vmx->nested.vmxon || vmx->nested.smm.vmxon)) {
13484                 kvm_state.vmx.vmxon_pa = vmx->nested.vmxon_ptr;
13485                 kvm_state.vmx.vmcs_pa = vmx->nested.current_vmptr;
13486
13487                 if (vmx->nested.current_vmptr != -1ull) {
13488                         kvm_state.size += VMCS12_SIZE;
13489
13490                         if (is_guest_mode(vcpu) &&
13491                             nested_cpu_has_shadow_vmcs(vmcs12) &&
13492                             vmcs12->vmcs_link_pointer != -1ull)
13493                                 kvm_state.size += VMCS12_SIZE;
13494                 }
13495
13496                 if (vmx->nested.smm.vmxon)
13497                         kvm_state.vmx.smm.flags |= KVM_STATE_NESTED_SMM_VMXON;
13498
13499                 if (vmx->nested.smm.guest_mode)
13500                         kvm_state.vmx.smm.flags |= KVM_STATE_NESTED_SMM_GUEST_MODE;
13501
13502                 if (is_guest_mode(vcpu)) {
13503                         kvm_state.flags |= KVM_STATE_NESTED_GUEST_MODE;
13504
13505                         if (vmx->nested.nested_run_pending)
13506                                 kvm_state.flags |= KVM_STATE_NESTED_RUN_PENDING;
13507                 }
13508         }
13509
13510         if (user_data_size < kvm_state.size)
13511                 goto out;
13512
13513         if (copy_to_user(user_kvm_nested_state, &kvm_state, sizeof(kvm_state)))
13514                 return -EFAULT;
13515
13516         if (vmx->nested.current_vmptr == -1ull)
13517                 goto out;
13518
13519         /*
13520          * When running L2, the authoritative vmcs12 state is in the
13521          * vmcs02. When running L1, the authoritative vmcs12 state is
13522          * in the shadow vmcs linked to vmcs01, unless
13523          * sync_shadow_vmcs is set, in which case, the authoritative
13524          * vmcs12 state is in the vmcs12 already.
13525          */
13526         if (is_guest_mode(vcpu))
13527                 sync_vmcs12(vcpu, vmcs12);
13528         else if (enable_shadow_vmcs && !vmx->nested.sync_shadow_vmcs)
13529                 copy_shadow_to_vmcs12(vmx);
13530
13531         if (copy_to_user(user_kvm_nested_state->data, vmcs12, sizeof(*vmcs12)))
13532                 return -EFAULT;
13533
13534         if (nested_cpu_has_shadow_vmcs(vmcs12) &&
13535             vmcs12->vmcs_link_pointer != -1ull) {
13536                 if (copy_to_user(user_kvm_nested_state->data + VMCS12_SIZE,
13537                                  get_shadow_vmcs12(vcpu), sizeof(*vmcs12)))
13538                         return -EFAULT;
13539         }
13540
13541 out:
13542         return kvm_state.size;
13543 }
13544
13545 static int vmx_set_nested_state(struct kvm_vcpu *vcpu,
13546                                 struct kvm_nested_state __user *user_kvm_nested_state,
13547                                 struct kvm_nested_state *kvm_state)
13548 {
13549         struct vcpu_vmx *vmx = to_vmx(vcpu);
13550         struct vmcs12 *vmcs12;
13551         u32 exit_qual;
13552         int ret;
13553
13554         if (kvm_state->format != 0)
13555                 return -EINVAL;
13556
13557         if (!nested_vmx_allowed(vcpu))
13558                 return kvm_state->vmx.vmxon_pa == -1ull ? 0 : -EINVAL;
13559
13560         if (kvm_state->vmx.vmxon_pa == -1ull) {
13561                 if (kvm_state->vmx.smm.flags)
13562                         return -EINVAL;
13563
13564                 if (kvm_state->vmx.vmcs_pa != -1ull)
13565                         return -EINVAL;
13566
13567                 vmx_leave_nested(vcpu);
13568                 return 0;
13569         }
13570
13571         if (!page_address_valid(vcpu, kvm_state->vmx.vmxon_pa))
13572                 return -EINVAL;
13573
13574         if (kvm_state->size < sizeof(kvm_state) + sizeof(*vmcs12))
13575                 return -EINVAL;
13576
13577         if (kvm_state->vmx.vmcs_pa == kvm_state->vmx.vmxon_pa ||
13578             !page_address_valid(vcpu, kvm_state->vmx.vmcs_pa))
13579                 return -EINVAL;
13580
13581         if ((kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
13582             (kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
13583                 return -EINVAL;
13584
13585         if (kvm_state->vmx.smm.flags &
13586             ~(KVM_STATE_NESTED_SMM_GUEST_MODE | KVM_STATE_NESTED_SMM_VMXON))
13587                 return -EINVAL;
13588
13589         if ((kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
13590             !(kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON))
13591                 return -EINVAL;
13592
13593         vmx_leave_nested(vcpu);
13594         if (kvm_state->vmx.vmxon_pa == -1ull)
13595                 return 0;
13596
13597         vmx->nested.vmxon_ptr = kvm_state->vmx.vmxon_pa;
13598         ret = enter_vmx_operation(vcpu);
13599         if (ret)
13600                 return ret;
13601
13602         set_current_vmptr(vmx, kvm_state->vmx.vmcs_pa);
13603
13604         if (kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON) {
13605                 vmx->nested.smm.vmxon = true;
13606                 vmx->nested.vmxon = false;
13607
13608                 if (kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE)
13609                         vmx->nested.smm.guest_mode = true;
13610         }
13611
13612         vmcs12 = get_vmcs12(vcpu);
13613         if (copy_from_user(vmcs12, user_kvm_nested_state->data, sizeof(*vmcs12)))
13614                 return -EFAULT;
13615
13616         if (vmcs12->hdr.revision_id != VMCS12_REVISION)
13617                 return -EINVAL;
13618
13619         if (!(kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
13620                 return 0;
13621
13622         vmx->nested.nested_run_pending =
13623                 !!(kvm_state->flags & KVM_STATE_NESTED_RUN_PENDING);
13624
13625         if (nested_cpu_has_shadow_vmcs(vmcs12) &&
13626             vmcs12->vmcs_link_pointer != -1ull) {
13627                 struct vmcs12 *shadow_vmcs12 = get_shadow_vmcs12(vcpu);
13628                 if (kvm_state->size < sizeof(kvm_state) + 2 * sizeof(*vmcs12))
13629                         return -EINVAL;
13630
13631                 if (copy_from_user(shadow_vmcs12,
13632                                    user_kvm_nested_state->data + VMCS12_SIZE,
13633                                    sizeof(*vmcs12)))
13634                         return -EFAULT;
13635
13636                 if (shadow_vmcs12->hdr.revision_id != VMCS12_REVISION ||
13637                     !shadow_vmcs12->hdr.shadow_vmcs)
13638                         return -EINVAL;
13639         }
13640
13641         if (check_vmentry_prereqs(vcpu, vmcs12) ||
13642             check_vmentry_postreqs(vcpu, vmcs12, &exit_qual))
13643                 return -EINVAL;
13644
13645         if (kvm_state->flags & KVM_STATE_NESTED_RUN_PENDING)
13646                 vmx->nested.nested_run_pending = 1;
13647
13648         vmx->nested.dirty_vmcs12 = true;
13649         ret = enter_vmx_non_root_mode(vcpu, NULL);
13650         if (ret)
13651                 return -EINVAL;
13652
13653         return 0;
13654 }
13655
13656 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
13657         .cpu_has_kvm_support = cpu_has_kvm_support,
13658         .disabled_by_bios = vmx_disabled_by_bios,
13659         .hardware_setup = hardware_setup,
13660         .hardware_unsetup = hardware_unsetup,
13661         .check_processor_compatibility = vmx_check_processor_compat,
13662         .hardware_enable = hardware_enable,
13663         .hardware_disable = hardware_disable,
13664         .cpu_has_accelerated_tpr = report_flexpriority,
13665         .has_emulated_msr = vmx_has_emulated_msr,
13666
13667         .vm_init = vmx_vm_init,
13668         .vm_alloc = vmx_vm_alloc,
13669         .vm_free = vmx_vm_free,
13670
13671         .vcpu_create = vmx_create_vcpu,
13672         .vcpu_free = vmx_free_vcpu,
13673         .vcpu_reset = vmx_vcpu_reset,
13674
13675         .prepare_guest_switch = vmx_save_host_state,
13676         .vcpu_load = vmx_vcpu_load,
13677         .vcpu_put = vmx_vcpu_put,
13678
13679         .update_bp_intercept = update_exception_bitmap,
13680         .get_msr_feature = vmx_get_msr_feature,
13681         .get_msr = vmx_get_msr,
13682         .set_msr = vmx_set_msr,
13683         .get_segment_base = vmx_get_segment_base,
13684         .get_segment = vmx_get_segment,
13685         .set_segment = vmx_set_segment,
13686         .get_cpl = vmx_get_cpl,
13687         .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
13688         .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
13689         .decache_cr3 = vmx_decache_cr3,
13690         .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
13691         .set_cr0 = vmx_set_cr0,
13692         .set_cr3 = vmx_set_cr3,
13693         .set_cr4 = vmx_set_cr4,
13694         .set_efer = vmx_set_efer,
13695         .get_idt = vmx_get_idt,
13696         .set_idt = vmx_set_idt,
13697         .get_gdt = vmx_get_gdt,
13698         .set_gdt = vmx_set_gdt,
13699         .get_dr6 = vmx_get_dr6,
13700         .set_dr6 = vmx_set_dr6,
13701         .set_dr7 = vmx_set_dr7,
13702         .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
13703         .cache_reg = vmx_cache_reg,
13704         .get_rflags = vmx_get_rflags,
13705         .set_rflags = vmx_set_rflags,
13706
13707         .tlb_flush = vmx_flush_tlb,
13708         .tlb_flush_gva = vmx_flush_tlb_gva,
13709
13710         .run = vmx_vcpu_run,
13711         .handle_exit = vmx_handle_exit,
13712         .skip_emulated_instruction = skip_emulated_instruction,
13713         .set_interrupt_shadow = vmx_set_interrupt_shadow,
13714         .get_interrupt_shadow = vmx_get_interrupt_shadow,
13715         .patch_hypercall = vmx_patch_hypercall,
13716         .set_irq = vmx_inject_irq,
13717         .set_nmi = vmx_inject_nmi,
13718         .queue_exception = vmx_queue_exception,
13719         .cancel_injection = vmx_cancel_injection,
13720         .interrupt_allowed = vmx_interrupt_allowed,
13721         .nmi_allowed = vmx_nmi_allowed,
13722         .get_nmi_mask = vmx_get_nmi_mask,
13723         .set_nmi_mask = vmx_set_nmi_mask,
13724         .enable_nmi_window = enable_nmi_window,
13725         .enable_irq_window = enable_irq_window,
13726         .update_cr8_intercept = update_cr8_intercept,
13727         .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
13728         .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
13729         .get_enable_apicv = vmx_get_enable_apicv,
13730         .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
13731         .load_eoi_exitmap = vmx_load_eoi_exitmap,
13732         .apicv_post_state_restore = vmx_apicv_post_state_restore,
13733         .hwapic_irr_update = vmx_hwapic_irr_update,
13734         .hwapic_isr_update = vmx_hwapic_isr_update,
13735         .sync_pir_to_irr = vmx_sync_pir_to_irr,
13736         .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
13737
13738         .set_tss_addr = vmx_set_tss_addr,
13739         .set_identity_map_addr = vmx_set_identity_map_addr,
13740         .get_tdp_level = get_ept_level,
13741         .get_mt_mask = vmx_get_mt_mask,
13742
13743         .get_exit_info = vmx_get_exit_info,
13744
13745         .get_lpage_level = vmx_get_lpage_level,
13746
13747         .cpuid_update = vmx_cpuid_update,
13748
13749         .rdtscp_supported = vmx_rdtscp_supported,
13750         .invpcid_supported = vmx_invpcid_supported,
13751
13752         .set_supported_cpuid = vmx_set_supported_cpuid,
13753
13754         .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
13755
13756         .read_l1_tsc_offset = vmx_read_l1_tsc_offset,
13757         .write_tsc_offset = vmx_write_tsc_offset,
13758
13759         .set_tdp_cr3 = vmx_set_cr3,
13760
13761         .check_intercept = vmx_check_intercept,
13762         .handle_external_intr = vmx_handle_external_intr,
13763         .mpx_supported = vmx_mpx_supported,
13764         .xsaves_supported = vmx_xsaves_supported,
13765         .umip_emulated = vmx_umip_emulated,
13766
13767         .check_nested_events = vmx_check_nested_events,
13768
13769         .sched_in = vmx_sched_in,
13770
13771         .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
13772         .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
13773         .flush_log_dirty = vmx_flush_log_dirty,
13774         .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
13775         .write_log_dirty = vmx_write_pml_buffer,
13776
13777         .pre_block = vmx_pre_block,
13778         .post_block = vmx_post_block,
13779
13780         .pmu_ops = &intel_pmu_ops,
13781
13782         .update_pi_irte = vmx_update_pi_irte,
13783
13784 #ifdef CONFIG_X86_64
13785         .set_hv_timer = vmx_set_hv_timer,
13786         .cancel_hv_timer = vmx_cancel_hv_timer,
13787 #endif
13788
13789         .setup_mce = vmx_setup_mce,
13790
13791         .get_nested_state = vmx_get_nested_state,
13792         .set_nested_state = vmx_set_nested_state,
13793         .get_vmcs12_pages = nested_get_vmcs12_pages,
13794
13795         .smi_allowed = vmx_smi_allowed,
13796         .pre_enter_smm = vmx_pre_enter_smm,
13797         .pre_leave_smm = vmx_pre_leave_smm,
13798         .enable_smi_window = enable_smi_window,
13799 };
13800
13801 static int __init vmx_init(void)
13802 {
13803         int r;
13804
13805 #if IS_ENABLED(CONFIG_HYPERV)
13806         /*
13807          * Enlightened VMCS usage should be recommended and the host needs
13808          * to support eVMCS v1 or above. We can also disable eVMCS support
13809          * with module parameter.
13810          */
13811         if (enlightened_vmcs &&
13812             ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
13813             (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
13814             KVM_EVMCS_VERSION) {
13815                 int cpu;
13816
13817                 /* Check that we have assist pages on all online CPUs */
13818                 for_each_online_cpu(cpu) {
13819                         if (!hv_get_vp_assist_page(cpu)) {
13820                                 enlightened_vmcs = false;
13821                                 break;
13822                         }
13823                 }
13824
13825                 if (enlightened_vmcs) {
13826                         pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
13827                         static_branch_enable(&enable_evmcs);
13828                 }
13829         } else {
13830                 enlightened_vmcs = false;
13831         }
13832 #endif
13833
13834         r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
13835                      __alignof__(struct vcpu_vmx), THIS_MODULE);
13836         if (r)
13837                 return r;
13838
13839 #ifdef CONFIG_KEXEC_CORE
13840         rcu_assign_pointer(crash_vmclear_loaded_vmcss,
13841                            crash_vmclear_local_loaded_vmcss);
13842 #endif
13843         vmx_check_vmcs12_offsets();
13844
13845         return 0;
13846 }
13847
13848 static void __exit vmx_exit(void)
13849 {
13850 #ifdef CONFIG_KEXEC_CORE
13851         RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
13852         synchronize_rcu();
13853 #endif
13854
13855         kvm_exit();
13856
13857 #if IS_ENABLED(CONFIG_HYPERV)
13858         if (static_branch_unlikely(&enable_evmcs)) {
13859                 int cpu;
13860                 struct hv_vp_assist_page *vp_ap;
13861                 /*
13862                  * Reset everything to support using non-enlightened VMCS
13863                  * access later (e.g. when we reload the module with
13864                  * enlightened_vmcs=0)
13865                  */
13866                 for_each_online_cpu(cpu) {
13867                         vp_ap = hv_get_vp_assist_page(cpu);
13868
13869                         if (!vp_ap)
13870                                 continue;
13871
13872                         vp_ap->current_nested_vmcs = 0;
13873                         vp_ap->enlighten_vmentry = 0;
13874                 }
13875
13876                 static_branch_disable(&enable_evmcs);
13877         }
13878 #endif
13879 }
13880
13881 module_init(vmx_init)
13882 module_exit(vmx_exit)