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