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