KVM: nVMX: optimize prepare_vmcs02{,_full} for Enlightened VMCS case
[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 #include "hyperv.h"
24
25 #include <linux/kvm_host.h>
26 #include <linux/module.h>
27 #include <linux/kernel.h>
28 #include <linux/mm.h>
29 #include <linux/highmem.h>
30 #include <linux/sched.h>
31 #include <linux/moduleparam.h>
32 #include <linux/mod_devicetable.h>
33 #include <linux/trace_events.h>
34 #include <linux/slab.h>
35 #include <linux/tboot.h>
36 #include <linux/hrtimer.h>
37 #include <linux/frame.h>
38 #include <linux/nospec.h>
39 #include "kvm_cache_regs.h"
40 #include "x86.h"
41
42 #include <asm/asm.h>
43 #include <asm/cpu.h>
44 #include <asm/io.h>
45 #include <asm/desc.h>
46 #include <asm/vmx.h>
47 #include <asm/virtext.h>
48 #include <asm/mce.h>
49 #include <asm/fpu/internal.h>
50 #include <asm/perf_event.h>
51 #include <asm/debugreg.h>
52 #include <asm/kexec.h>
53 #include <asm/apic.h>
54 #include <asm/irq_remapping.h>
55 #include <asm/mmu_context.h>
56 #include <asm/spec-ctrl.h>
57 #include <asm/mshyperv.h>
58
59 #include "trace.h"
60 #include "pmu.h"
61 #include "vmx_evmcs.h"
62
63 #define __ex(x) __kvm_handle_fault_on_reboot(x)
64 #define __ex_clear(x, reg) \
65         ____kvm_handle_fault_on_reboot(x, "xorl " reg " , " reg)
66
67 MODULE_AUTHOR("Qumranet");
68 MODULE_LICENSE("GPL");
69
70 static const struct x86_cpu_id vmx_cpu_id[] = {
71         X86_FEATURE_MATCH(X86_FEATURE_VMX),
72         {}
73 };
74 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
75
76 static bool __read_mostly enable_vpid = 1;
77 module_param_named(vpid, enable_vpid, bool, 0444);
78
79 static bool __read_mostly enable_vnmi = 1;
80 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
81
82 static bool __read_mostly flexpriority_enabled = 1;
83 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
84
85 static bool __read_mostly enable_ept = 1;
86 module_param_named(ept, enable_ept, bool, S_IRUGO);
87
88 static bool __read_mostly enable_unrestricted_guest = 1;
89 module_param_named(unrestricted_guest,
90                         enable_unrestricted_guest, bool, S_IRUGO);
91
92 static bool __read_mostly enable_ept_ad_bits = 1;
93 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
94
95 static bool __read_mostly emulate_invalid_guest_state = true;
96 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
97
98 static bool __read_mostly fasteoi = 1;
99 module_param(fasteoi, bool, S_IRUGO);
100
101 static bool __read_mostly enable_apicv = 1;
102 module_param(enable_apicv, bool, S_IRUGO);
103
104 static bool __read_mostly enable_shadow_vmcs = 1;
105 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
106 /*
107  * If nested=1, nested virtualization is supported, i.e., guests may use
108  * VMX and be a hypervisor for its own guests. If nested=0, guests may not
109  * use VMX instructions.
110  */
111 static bool __read_mostly nested = 0;
112 module_param(nested, bool, S_IRUGO);
113
114 static bool __read_mostly nested_early_check = 0;
115 module_param(nested_early_check, bool, S_IRUGO);
116
117 static u64 __read_mostly host_xss;
118
119 static bool __read_mostly enable_pml = 1;
120 module_param_named(pml, enable_pml, bool, S_IRUGO);
121
122 #define MSR_TYPE_R      1
123 #define MSR_TYPE_W      2
124 #define MSR_TYPE_RW     3
125
126 #define MSR_BITMAP_MODE_X2APIC          1
127 #define MSR_BITMAP_MODE_X2APIC_APICV    2
128
129 #define KVM_VMX_TSC_MULTIPLIER_MAX     0xffffffffffffffffULL
130
131 /* Guest_tsc -> host_tsc conversion requires 64-bit division.  */
132 static int __read_mostly cpu_preemption_timer_multi;
133 static bool __read_mostly enable_preemption_timer = 1;
134 #ifdef CONFIG_X86_64
135 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
136 #endif
137
138 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
139 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
140 #define KVM_VM_CR0_ALWAYS_ON                            \
141         (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST |      \
142          X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
143 #define KVM_CR4_GUEST_OWNED_BITS                                      \
144         (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR      \
145          | X86_CR4_OSXMMEXCPT | X86_CR4_LA57 | X86_CR4_TSD)
146
147 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
148 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
149 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
150
151 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
152
153 #define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
154
155 /*
156  * Hyper-V requires all of these, so mark them as supported even though
157  * they are just treated the same as all-context.
158  */
159 #define VMX_VPID_EXTENT_SUPPORTED_MASK          \
160         (VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT |  \
161         VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT |    \
162         VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT |    \
163         VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
164
165 /*
166  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
167  * ple_gap:    upper bound on the amount of time between two successive
168  *             executions of PAUSE in a loop. Also indicate if ple enabled.
169  *             According to test, this time is usually smaller than 128 cycles.
170  * ple_window: upper bound on the amount of time a guest is allowed to execute
171  *             in a PAUSE loop. Tests indicate that most spinlocks are held for
172  *             less than 2^12 cycles
173  * Time is measured based on a counter that runs at the same rate as the TSC,
174  * refer SDM volume 3b section 21.6.13 & 22.1.3.
175  */
176 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
177
178 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
179 module_param(ple_window, uint, 0444);
180
181 /* Default doubles per-vcpu window every exit. */
182 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
183 module_param(ple_window_grow, uint, 0444);
184
185 /* Default resets per-vcpu window every exit to ple_window. */
186 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
187 module_param(ple_window_shrink, uint, 0444);
188
189 /* Default is to compute the maximum so we can never overflow. */
190 static unsigned int ple_window_max        = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
191 module_param(ple_window_max, uint, 0444);
192
193 extern const ulong vmx_return;
194 extern const ulong vmx_early_consistency_check_return;
195
196 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
197 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
198 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
199
200 /* Storage for pre module init parameter parsing */
201 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
202
203 static const struct {
204         const char *option;
205         bool for_parse;
206 } vmentry_l1d_param[] = {
207         [VMENTER_L1D_FLUSH_AUTO]         = {"auto", true},
208         [VMENTER_L1D_FLUSH_NEVER]        = {"never", true},
209         [VMENTER_L1D_FLUSH_COND]         = {"cond", true},
210         [VMENTER_L1D_FLUSH_ALWAYS]       = {"always", true},
211         [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
212         [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
213 };
214
215 #define L1D_CACHE_ORDER 4
216 static void *vmx_l1d_flush_pages;
217
218 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
219 {
220         struct page *page;
221         unsigned int i;
222
223         if (!enable_ept) {
224                 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
225                 return 0;
226         }
227
228         if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
229                 u64 msr;
230
231                 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
232                 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
233                         l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
234                         return 0;
235                 }
236         }
237
238         /* If set to auto use the default l1tf mitigation method */
239         if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
240                 switch (l1tf_mitigation) {
241                 case L1TF_MITIGATION_OFF:
242                         l1tf = VMENTER_L1D_FLUSH_NEVER;
243                         break;
244                 case L1TF_MITIGATION_FLUSH_NOWARN:
245                 case L1TF_MITIGATION_FLUSH:
246                 case L1TF_MITIGATION_FLUSH_NOSMT:
247                         l1tf = VMENTER_L1D_FLUSH_COND;
248                         break;
249                 case L1TF_MITIGATION_FULL:
250                 case L1TF_MITIGATION_FULL_FORCE:
251                         l1tf = VMENTER_L1D_FLUSH_ALWAYS;
252                         break;
253                 }
254         } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
255                 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
256         }
257
258         if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
259             !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
260                 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
261                 if (!page)
262                         return -ENOMEM;
263                 vmx_l1d_flush_pages = page_address(page);
264
265                 /*
266                  * Initialize each page with a different pattern in
267                  * order to protect against KSM in the nested
268                  * virtualization case.
269                  */
270                 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
271                         memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
272                                PAGE_SIZE);
273                 }
274         }
275
276         l1tf_vmx_mitigation = l1tf;
277
278         if (l1tf != VMENTER_L1D_FLUSH_NEVER)
279                 static_branch_enable(&vmx_l1d_should_flush);
280         else
281                 static_branch_disable(&vmx_l1d_should_flush);
282
283         if (l1tf == VMENTER_L1D_FLUSH_COND)
284                 static_branch_enable(&vmx_l1d_flush_cond);
285         else
286                 static_branch_disable(&vmx_l1d_flush_cond);
287         return 0;
288 }
289
290 static int vmentry_l1d_flush_parse(const char *s)
291 {
292         unsigned int i;
293
294         if (s) {
295                 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
296                         if (vmentry_l1d_param[i].for_parse &&
297                             sysfs_streq(s, vmentry_l1d_param[i].option))
298                                 return i;
299                 }
300         }
301         return -EINVAL;
302 }
303
304 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
305 {
306         int l1tf, ret;
307
308         l1tf = vmentry_l1d_flush_parse(s);
309         if (l1tf < 0)
310                 return l1tf;
311
312         if (!boot_cpu_has(X86_BUG_L1TF))
313                 return 0;
314
315         /*
316          * Has vmx_init() run already? If not then this is the pre init
317          * parameter parsing. In that case just store the value and let
318          * vmx_init() do the proper setup after enable_ept has been
319          * established.
320          */
321         if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
322                 vmentry_l1d_flush_param = l1tf;
323                 return 0;
324         }
325
326         mutex_lock(&vmx_l1d_flush_mutex);
327         ret = vmx_setup_l1d_flush(l1tf);
328         mutex_unlock(&vmx_l1d_flush_mutex);
329         return ret;
330 }
331
332 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
333 {
334         if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
335                 return sprintf(s, "???\n");
336
337         return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
338 }
339
340 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
341         .set = vmentry_l1d_flush_set,
342         .get = vmentry_l1d_flush_get,
343 };
344 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
345
346 enum ept_pointers_status {
347         EPT_POINTERS_CHECK = 0,
348         EPT_POINTERS_MATCH = 1,
349         EPT_POINTERS_MISMATCH = 2
350 };
351
352 struct kvm_vmx {
353         struct kvm kvm;
354
355         unsigned int tss_addr;
356         bool ept_identity_pagetable_done;
357         gpa_t ept_identity_map_addr;
358
359         enum ept_pointers_status ept_pointers_match;
360         spinlock_t ept_pointer_lock;
361 };
362
363 #define NR_AUTOLOAD_MSRS 8
364
365 struct vmcs_hdr {
366         u32 revision_id:31;
367         u32 shadow_vmcs:1;
368 };
369
370 struct vmcs {
371         struct vmcs_hdr hdr;
372         u32 abort;
373         char data[0];
374 };
375
376 /*
377  * vmcs_host_state tracks registers that are loaded from the VMCS on VMEXIT
378  * and whose values change infrequently, but are not constant.  I.e. this is
379  * used as a write-through cache of the corresponding VMCS fields.
380  */
381 struct vmcs_host_state {
382         unsigned long cr3;      /* May not match real cr3 */
383         unsigned long cr4;      /* May not match real cr4 */
384         unsigned long gs_base;
385         unsigned long fs_base;
386
387         u16           fs_sel, gs_sel, ldt_sel;
388 #ifdef CONFIG_X86_64
389         u16           ds_sel, es_sel;
390 #endif
391 };
392
393 /*
394  * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
395  * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
396  * loaded on this CPU (so we can clear them if the CPU goes down).
397  */
398 struct loaded_vmcs {
399         struct vmcs *vmcs;
400         struct vmcs *shadow_vmcs;
401         int cpu;
402         bool launched;
403         bool nmi_known_unmasked;
404         bool hv_timer_armed;
405         /* Support for vnmi-less CPUs */
406         int soft_vnmi_blocked;
407         ktime_t entry_time;
408         s64 vnmi_blocked_time;
409         unsigned long *msr_bitmap;
410         struct list_head loaded_vmcss_on_cpu_link;
411         struct vmcs_host_state host_state;
412 };
413
414 struct shared_msr_entry {
415         unsigned index;
416         u64 data;
417         u64 mask;
418 };
419
420 /*
421  * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
422  * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
423  * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
424  * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
425  * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
426  * More than one of these structures may exist, if L1 runs multiple L2 guests.
427  * nested_vmx_run() will use the data here to build the vmcs02: a VMCS for the
428  * underlying hardware which will be used to run L2.
429  * This structure is packed to ensure that its layout is identical across
430  * machines (necessary for live migration).
431  *
432  * IMPORTANT: Changing the layout of existing fields in this structure
433  * will break save/restore compatibility with older kvm releases. When
434  * adding new fields, either use space in the reserved padding* arrays
435  * or add the new fields to the end of the structure.
436  */
437 typedef u64 natural_width;
438 struct __packed vmcs12 {
439         /* According to the Intel spec, a VMCS region must start with the
440          * following two fields. Then follow implementation-specific data.
441          */
442         struct vmcs_hdr hdr;
443         u32 abort;
444
445         u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
446         u32 padding[7]; /* room for future expansion */
447
448         u64 io_bitmap_a;
449         u64 io_bitmap_b;
450         u64 msr_bitmap;
451         u64 vm_exit_msr_store_addr;
452         u64 vm_exit_msr_load_addr;
453         u64 vm_entry_msr_load_addr;
454         u64 tsc_offset;
455         u64 virtual_apic_page_addr;
456         u64 apic_access_addr;
457         u64 posted_intr_desc_addr;
458         u64 ept_pointer;
459         u64 eoi_exit_bitmap0;
460         u64 eoi_exit_bitmap1;
461         u64 eoi_exit_bitmap2;
462         u64 eoi_exit_bitmap3;
463         u64 xss_exit_bitmap;
464         u64 guest_physical_address;
465         u64 vmcs_link_pointer;
466         u64 guest_ia32_debugctl;
467         u64 guest_ia32_pat;
468         u64 guest_ia32_efer;
469         u64 guest_ia32_perf_global_ctrl;
470         u64 guest_pdptr0;
471         u64 guest_pdptr1;
472         u64 guest_pdptr2;
473         u64 guest_pdptr3;
474         u64 guest_bndcfgs;
475         u64 host_ia32_pat;
476         u64 host_ia32_efer;
477         u64 host_ia32_perf_global_ctrl;
478         u64 vmread_bitmap;
479         u64 vmwrite_bitmap;
480         u64 vm_function_control;
481         u64 eptp_list_address;
482         u64 pml_address;
483         u64 padding64[3]; /* room for future expansion */
484         /*
485          * To allow migration of L1 (complete with its L2 guests) between
486          * machines of different natural widths (32 or 64 bit), we cannot have
487          * unsigned long fields with no explict size. We use u64 (aliased
488          * natural_width) instead. Luckily, x86 is little-endian.
489          */
490         natural_width cr0_guest_host_mask;
491         natural_width cr4_guest_host_mask;
492         natural_width cr0_read_shadow;
493         natural_width cr4_read_shadow;
494         natural_width cr3_target_value0;
495         natural_width cr3_target_value1;
496         natural_width cr3_target_value2;
497         natural_width cr3_target_value3;
498         natural_width exit_qualification;
499         natural_width guest_linear_address;
500         natural_width guest_cr0;
501         natural_width guest_cr3;
502         natural_width guest_cr4;
503         natural_width guest_es_base;
504         natural_width guest_cs_base;
505         natural_width guest_ss_base;
506         natural_width guest_ds_base;
507         natural_width guest_fs_base;
508         natural_width guest_gs_base;
509         natural_width guest_ldtr_base;
510         natural_width guest_tr_base;
511         natural_width guest_gdtr_base;
512         natural_width guest_idtr_base;
513         natural_width guest_dr7;
514         natural_width guest_rsp;
515         natural_width guest_rip;
516         natural_width guest_rflags;
517         natural_width guest_pending_dbg_exceptions;
518         natural_width guest_sysenter_esp;
519         natural_width guest_sysenter_eip;
520         natural_width host_cr0;
521         natural_width host_cr3;
522         natural_width host_cr4;
523         natural_width host_fs_base;
524         natural_width host_gs_base;
525         natural_width host_tr_base;
526         natural_width host_gdtr_base;
527         natural_width host_idtr_base;
528         natural_width host_ia32_sysenter_esp;
529         natural_width host_ia32_sysenter_eip;
530         natural_width host_rsp;
531         natural_width host_rip;
532         natural_width paddingl[8]; /* room for future expansion */
533         u32 pin_based_vm_exec_control;
534         u32 cpu_based_vm_exec_control;
535         u32 exception_bitmap;
536         u32 page_fault_error_code_mask;
537         u32 page_fault_error_code_match;
538         u32 cr3_target_count;
539         u32 vm_exit_controls;
540         u32 vm_exit_msr_store_count;
541         u32 vm_exit_msr_load_count;
542         u32 vm_entry_controls;
543         u32 vm_entry_msr_load_count;
544         u32 vm_entry_intr_info_field;
545         u32 vm_entry_exception_error_code;
546         u32 vm_entry_instruction_len;
547         u32 tpr_threshold;
548         u32 secondary_vm_exec_control;
549         u32 vm_instruction_error;
550         u32 vm_exit_reason;
551         u32 vm_exit_intr_info;
552         u32 vm_exit_intr_error_code;
553         u32 idt_vectoring_info_field;
554         u32 idt_vectoring_error_code;
555         u32 vm_exit_instruction_len;
556         u32 vmx_instruction_info;
557         u32 guest_es_limit;
558         u32 guest_cs_limit;
559         u32 guest_ss_limit;
560         u32 guest_ds_limit;
561         u32 guest_fs_limit;
562         u32 guest_gs_limit;
563         u32 guest_ldtr_limit;
564         u32 guest_tr_limit;
565         u32 guest_gdtr_limit;
566         u32 guest_idtr_limit;
567         u32 guest_es_ar_bytes;
568         u32 guest_cs_ar_bytes;
569         u32 guest_ss_ar_bytes;
570         u32 guest_ds_ar_bytes;
571         u32 guest_fs_ar_bytes;
572         u32 guest_gs_ar_bytes;
573         u32 guest_ldtr_ar_bytes;
574         u32 guest_tr_ar_bytes;
575         u32 guest_interruptibility_info;
576         u32 guest_activity_state;
577         u32 guest_sysenter_cs;
578         u32 host_ia32_sysenter_cs;
579         u32 vmx_preemption_timer_value;
580         u32 padding32[7]; /* room for future expansion */
581         u16 virtual_processor_id;
582         u16 posted_intr_nv;
583         u16 guest_es_selector;
584         u16 guest_cs_selector;
585         u16 guest_ss_selector;
586         u16 guest_ds_selector;
587         u16 guest_fs_selector;
588         u16 guest_gs_selector;
589         u16 guest_ldtr_selector;
590         u16 guest_tr_selector;
591         u16 guest_intr_status;
592         u16 host_es_selector;
593         u16 host_cs_selector;
594         u16 host_ss_selector;
595         u16 host_ds_selector;
596         u16 host_fs_selector;
597         u16 host_gs_selector;
598         u16 host_tr_selector;
599         u16 guest_pml_index;
600 };
601
602 /*
603  * For save/restore compatibility, the vmcs12 field offsets must not change.
604  */
605 #define CHECK_OFFSET(field, loc)                                \
606         BUILD_BUG_ON_MSG(offsetof(struct vmcs12, field) != (loc),       \
607                 "Offset of " #field " in struct vmcs12 has changed.")
608
609 static inline void vmx_check_vmcs12_offsets(void) {
610         CHECK_OFFSET(hdr, 0);
611         CHECK_OFFSET(abort, 4);
612         CHECK_OFFSET(launch_state, 8);
613         CHECK_OFFSET(io_bitmap_a, 40);
614         CHECK_OFFSET(io_bitmap_b, 48);
615         CHECK_OFFSET(msr_bitmap, 56);
616         CHECK_OFFSET(vm_exit_msr_store_addr, 64);
617         CHECK_OFFSET(vm_exit_msr_load_addr, 72);
618         CHECK_OFFSET(vm_entry_msr_load_addr, 80);
619         CHECK_OFFSET(tsc_offset, 88);
620         CHECK_OFFSET(virtual_apic_page_addr, 96);
621         CHECK_OFFSET(apic_access_addr, 104);
622         CHECK_OFFSET(posted_intr_desc_addr, 112);
623         CHECK_OFFSET(ept_pointer, 120);
624         CHECK_OFFSET(eoi_exit_bitmap0, 128);
625         CHECK_OFFSET(eoi_exit_bitmap1, 136);
626         CHECK_OFFSET(eoi_exit_bitmap2, 144);
627         CHECK_OFFSET(eoi_exit_bitmap3, 152);
628         CHECK_OFFSET(xss_exit_bitmap, 160);
629         CHECK_OFFSET(guest_physical_address, 168);
630         CHECK_OFFSET(vmcs_link_pointer, 176);
631         CHECK_OFFSET(guest_ia32_debugctl, 184);
632         CHECK_OFFSET(guest_ia32_pat, 192);
633         CHECK_OFFSET(guest_ia32_efer, 200);
634         CHECK_OFFSET(guest_ia32_perf_global_ctrl, 208);
635         CHECK_OFFSET(guest_pdptr0, 216);
636         CHECK_OFFSET(guest_pdptr1, 224);
637         CHECK_OFFSET(guest_pdptr2, 232);
638         CHECK_OFFSET(guest_pdptr3, 240);
639         CHECK_OFFSET(guest_bndcfgs, 248);
640         CHECK_OFFSET(host_ia32_pat, 256);
641         CHECK_OFFSET(host_ia32_efer, 264);
642         CHECK_OFFSET(host_ia32_perf_global_ctrl, 272);
643         CHECK_OFFSET(vmread_bitmap, 280);
644         CHECK_OFFSET(vmwrite_bitmap, 288);
645         CHECK_OFFSET(vm_function_control, 296);
646         CHECK_OFFSET(eptp_list_address, 304);
647         CHECK_OFFSET(pml_address, 312);
648         CHECK_OFFSET(cr0_guest_host_mask, 344);
649         CHECK_OFFSET(cr4_guest_host_mask, 352);
650         CHECK_OFFSET(cr0_read_shadow, 360);
651         CHECK_OFFSET(cr4_read_shadow, 368);
652         CHECK_OFFSET(cr3_target_value0, 376);
653         CHECK_OFFSET(cr3_target_value1, 384);
654         CHECK_OFFSET(cr3_target_value2, 392);
655         CHECK_OFFSET(cr3_target_value3, 400);
656         CHECK_OFFSET(exit_qualification, 408);
657         CHECK_OFFSET(guest_linear_address, 416);
658         CHECK_OFFSET(guest_cr0, 424);
659         CHECK_OFFSET(guest_cr3, 432);
660         CHECK_OFFSET(guest_cr4, 440);
661         CHECK_OFFSET(guest_es_base, 448);
662         CHECK_OFFSET(guest_cs_base, 456);
663         CHECK_OFFSET(guest_ss_base, 464);
664         CHECK_OFFSET(guest_ds_base, 472);
665         CHECK_OFFSET(guest_fs_base, 480);
666         CHECK_OFFSET(guest_gs_base, 488);
667         CHECK_OFFSET(guest_ldtr_base, 496);
668         CHECK_OFFSET(guest_tr_base, 504);
669         CHECK_OFFSET(guest_gdtr_base, 512);
670         CHECK_OFFSET(guest_idtr_base, 520);
671         CHECK_OFFSET(guest_dr7, 528);
672         CHECK_OFFSET(guest_rsp, 536);
673         CHECK_OFFSET(guest_rip, 544);
674         CHECK_OFFSET(guest_rflags, 552);
675         CHECK_OFFSET(guest_pending_dbg_exceptions, 560);
676         CHECK_OFFSET(guest_sysenter_esp, 568);
677         CHECK_OFFSET(guest_sysenter_eip, 576);
678         CHECK_OFFSET(host_cr0, 584);
679         CHECK_OFFSET(host_cr3, 592);
680         CHECK_OFFSET(host_cr4, 600);
681         CHECK_OFFSET(host_fs_base, 608);
682         CHECK_OFFSET(host_gs_base, 616);
683         CHECK_OFFSET(host_tr_base, 624);
684         CHECK_OFFSET(host_gdtr_base, 632);
685         CHECK_OFFSET(host_idtr_base, 640);
686         CHECK_OFFSET(host_ia32_sysenter_esp, 648);
687         CHECK_OFFSET(host_ia32_sysenter_eip, 656);
688         CHECK_OFFSET(host_rsp, 664);
689         CHECK_OFFSET(host_rip, 672);
690         CHECK_OFFSET(pin_based_vm_exec_control, 744);
691         CHECK_OFFSET(cpu_based_vm_exec_control, 748);
692         CHECK_OFFSET(exception_bitmap, 752);
693         CHECK_OFFSET(page_fault_error_code_mask, 756);
694         CHECK_OFFSET(page_fault_error_code_match, 760);
695         CHECK_OFFSET(cr3_target_count, 764);
696         CHECK_OFFSET(vm_exit_controls, 768);
697         CHECK_OFFSET(vm_exit_msr_store_count, 772);
698         CHECK_OFFSET(vm_exit_msr_load_count, 776);
699         CHECK_OFFSET(vm_entry_controls, 780);
700         CHECK_OFFSET(vm_entry_msr_load_count, 784);
701         CHECK_OFFSET(vm_entry_intr_info_field, 788);
702         CHECK_OFFSET(vm_entry_exception_error_code, 792);
703         CHECK_OFFSET(vm_entry_instruction_len, 796);
704         CHECK_OFFSET(tpr_threshold, 800);
705         CHECK_OFFSET(secondary_vm_exec_control, 804);
706         CHECK_OFFSET(vm_instruction_error, 808);
707         CHECK_OFFSET(vm_exit_reason, 812);
708         CHECK_OFFSET(vm_exit_intr_info, 816);
709         CHECK_OFFSET(vm_exit_intr_error_code, 820);
710         CHECK_OFFSET(idt_vectoring_info_field, 824);
711         CHECK_OFFSET(idt_vectoring_error_code, 828);
712         CHECK_OFFSET(vm_exit_instruction_len, 832);
713         CHECK_OFFSET(vmx_instruction_info, 836);
714         CHECK_OFFSET(guest_es_limit, 840);
715         CHECK_OFFSET(guest_cs_limit, 844);
716         CHECK_OFFSET(guest_ss_limit, 848);
717         CHECK_OFFSET(guest_ds_limit, 852);
718         CHECK_OFFSET(guest_fs_limit, 856);
719         CHECK_OFFSET(guest_gs_limit, 860);
720         CHECK_OFFSET(guest_ldtr_limit, 864);
721         CHECK_OFFSET(guest_tr_limit, 868);
722         CHECK_OFFSET(guest_gdtr_limit, 872);
723         CHECK_OFFSET(guest_idtr_limit, 876);
724         CHECK_OFFSET(guest_es_ar_bytes, 880);
725         CHECK_OFFSET(guest_cs_ar_bytes, 884);
726         CHECK_OFFSET(guest_ss_ar_bytes, 888);
727         CHECK_OFFSET(guest_ds_ar_bytes, 892);
728         CHECK_OFFSET(guest_fs_ar_bytes, 896);
729         CHECK_OFFSET(guest_gs_ar_bytes, 900);
730         CHECK_OFFSET(guest_ldtr_ar_bytes, 904);
731         CHECK_OFFSET(guest_tr_ar_bytes, 908);
732         CHECK_OFFSET(guest_interruptibility_info, 912);
733         CHECK_OFFSET(guest_activity_state, 916);
734         CHECK_OFFSET(guest_sysenter_cs, 920);
735         CHECK_OFFSET(host_ia32_sysenter_cs, 924);
736         CHECK_OFFSET(vmx_preemption_timer_value, 928);
737         CHECK_OFFSET(virtual_processor_id, 960);
738         CHECK_OFFSET(posted_intr_nv, 962);
739         CHECK_OFFSET(guest_es_selector, 964);
740         CHECK_OFFSET(guest_cs_selector, 966);
741         CHECK_OFFSET(guest_ss_selector, 968);
742         CHECK_OFFSET(guest_ds_selector, 970);
743         CHECK_OFFSET(guest_fs_selector, 972);
744         CHECK_OFFSET(guest_gs_selector, 974);
745         CHECK_OFFSET(guest_ldtr_selector, 976);
746         CHECK_OFFSET(guest_tr_selector, 978);
747         CHECK_OFFSET(guest_intr_status, 980);
748         CHECK_OFFSET(host_es_selector, 982);
749         CHECK_OFFSET(host_cs_selector, 984);
750         CHECK_OFFSET(host_ss_selector, 986);
751         CHECK_OFFSET(host_ds_selector, 988);
752         CHECK_OFFSET(host_fs_selector, 990);
753         CHECK_OFFSET(host_gs_selector, 992);
754         CHECK_OFFSET(host_tr_selector, 994);
755         CHECK_OFFSET(guest_pml_index, 996);
756 }
757
758 /*
759  * VMCS12_REVISION is an arbitrary id that should be changed if the content or
760  * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
761  * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
762  *
763  * IMPORTANT: Changing this value will break save/restore compatibility with
764  * older kvm releases.
765  */
766 #define VMCS12_REVISION 0x11e57ed0
767
768 /*
769  * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
770  * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
771  * current implementation, 4K are reserved to avoid future complications.
772  */
773 #define VMCS12_SIZE 0x1000
774
775 /*
776  * VMCS12_MAX_FIELD_INDEX is the highest index value used in any
777  * supported VMCS12 field encoding.
778  */
779 #define VMCS12_MAX_FIELD_INDEX 0x17
780
781 struct nested_vmx_msrs {
782         /*
783          * We only store the "true" versions of the VMX capability MSRs. We
784          * generate the "non-true" versions by setting the must-be-1 bits
785          * according to the SDM.
786          */
787         u32 procbased_ctls_low;
788         u32 procbased_ctls_high;
789         u32 secondary_ctls_low;
790         u32 secondary_ctls_high;
791         u32 pinbased_ctls_low;
792         u32 pinbased_ctls_high;
793         u32 exit_ctls_low;
794         u32 exit_ctls_high;
795         u32 entry_ctls_low;
796         u32 entry_ctls_high;
797         u32 misc_low;
798         u32 misc_high;
799         u32 ept_caps;
800         u32 vpid_caps;
801         u64 basic;
802         u64 cr0_fixed0;
803         u64 cr0_fixed1;
804         u64 cr4_fixed0;
805         u64 cr4_fixed1;
806         u64 vmcs_enum;
807         u64 vmfunc_controls;
808 };
809
810 /*
811  * The nested_vmx structure is part of vcpu_vmx, and holds information we need
812  * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
813  */
814 struct nested_vmx {
815         /* Has the level1 guest done vmxon? */
816         bool vmxon;
817         gpa_t vmxon_ptr;
818         bool pml_full;
819
820         /* The guest-physical address of the current VMCS L1 keeps for L2 */
821         gpa_t current_vmptr;
822         /*
823          * Cache of the guest's VMCS, existing outside of guest memory.
824          * Loaded from guest memory during VMPTRLD. Flushed to guest
825          * memory during VMCLEAR and VMPTRLD.
826          */
827         struct vmcs12 *cached_vmcs12;
828         /*
829          * Cache of the guest's shadow VMCS, existing outside of guest
830          * memory. Loaded from guest memory during VM entry. Flushed
831          * to guest memory during VM exit.
832          */
833         struct vmcs12 *cached_shadow_vmcs12;
834         /*
835          * Indicates if the shadow vmcs or enlightened vmcs must be updated
836          * with the data held by struct vmcs12.
837          */
838         bool need_vmcs12_sync;
839         bool dirty_vmcs12;
840
841         /*
842          * vmcs02 has been initialized, i.e. state that is constant for
843          * vmcs02 has been written to the backing VMCS.  Initialization
844          * is delayed until L1 actually attempts to run a nested VM.
845          */
846         bool vmcs02_initialized;
847
848         bool change_vmcs01_virtual_apic_mode;
849
850         /*
851          * Enlightened VMCS has been enabled. It does not mean that L1 has to
852          * use it. However, VMX features available to L1 will be limited based
853          * on what the enlightened VMCS supports.
854          */
855         bool enlightened_vmcs_enabled;
856
857         /* L2 must run next, and mustn't decide to exit to L1. */
858         bool nested_run_pending;
859
860         struct loaded_vmcs vmcs02;
861
862         /*
863          * Guest pages referred to in the vmcs02 with host-physical
864          * pointers, so we must keep them pinned while L2 runs.
865          */
866         struct page *apic_access_page;
867         struct page *virtual_apic_page;
868         struct page *pi_desc_page;
869         struct pi_desc *pi_desc;
870         bool pi_pending;
871         u16 posted_intr_nv;
872
873         struct hrtimer preemption_timer;
874         bool preemption_timer_expired;
875
876         /* to migrate it to L2 if VM_ENTRY_LOAD_DEBUG_CONTROLS is off */
877         u64 vmcs01_debugctl;
878         u64 vmcs01_guest_bndcfgs;
879
880         u16 vpid02;
881         u16 last_vpid;
882
883         struct nested_vmx_msrs msrs;
884
885         /* SMM related state */
886         struct {
887                 /* in VMX operation on SMM entry? */
888                 bool vmxon;
889                 /* in guest mode on SMM entry? */
890                 bool guest_mode;
891         } smm;
892
893         gpa_t hv_evmcs_vmptr;
894         struct page *hv_evmcs_page;
895         struct hv_enlightened_vmcs *hv_evmcs;
896 };
897
898 #define POSTED_INTR_ON  0
899 #define POSTED_INTR_SN  1
900
901 /* Posted-Interrupt Descriptor */
902 struct pi_desc {
903         u32 pir[8];     /* Posted interrupt requested */
904         union {
905                 struct {
906                                 /* bit 256 - Outstanding Notification */
907                         u16     on      : 1,
908                                 /* bit 257 - Suppress Notification */
909                                 sn      : 1,
910                                 /* bit 271:258 - Reserved */
911                                 rsvd_1  : 14;
912                                 /* bit 279:272 - Notification Vector */
913                         u8      nv;
914                                 /* bit 287:280 - Reserved */
915                         u8      rsvd_2;
916                                 /* bit 319:288 - Notification Destination */
917                         u32     ndst;
918                 };
919                 u64 control;
920         };
921         u32 rsvd[6];
922 } __aligned(64);
923
924 static bool pi_test_and_set_on(struct pi_desc *pi_desc)
925 {
926         return test_and_set_bit(POSTED_INTR_ON,
927                         (unsigned long *)&pi_desc->control);
928 }
929
930 static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
931 {
932         return test_and_clear_bit(POSTED_INTR_ON,
933                         (unsigned long *)&pi_desc->control);
934 }
935
936 static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
937 {
938         return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
939 }
940
941 static inline void pi_clear_sn(struct pi_desc *pi_desc)
942 {
943         return clear_bit(POSTED_INTR_SN,
944                         (unsigned long *)&pi_desc->control);
945 }
946
947 static inline void pi_set_sn(struct pi_desc *pi_desc)
948 {
949         return set_bit(POSTED_INTR_SN,
950                         (unsigned long *)&pi_desc->control);
951 }
952
953 static inline void pi_clear_on(struct pi_desc *pi_desc)
954 {
955         clear_bit(POSTED_INTR_ON,
956                   (unsigned long *)&pi_desc->control);
957 }
958
959 static inline int pi_test_on(struct pi_desc *pi_desc)
960 {
961         return test_bit(POSTED_INTR_ON,
962                         (unsigned long *)&pi_desc->control);
963 }
964
965 static inline int pi_test_sn(struct pi_desc *pi_desc)
966 {
967         return test_bit(POSTED_INTR_SN,
968                         (unsigned long *)&pi_desc->control);
969 }
970
971 struct vmx_msrs {
972         unsigned int            nr;
973         struct vmx_msr_entry    val[NR_AUTOLOAD_MSRS];
974 };
975
976 struct vcpu_vmx {
977         struct kvm_vcpu       vcpu;
978         unsigned long         host_rsp;
979         u8                    fail;
980         u8                    msr_bitmap_mode;
981         u32                   exit_intr_info;
982         u32                   idt_vectoring_info;
983         ulong                 rflags;
984         struct shared_msr_entry *guest_msrs;
985         int                   nmsrs;
986         int                   save_nmsrs;
987         unsigned long         host_idt_base;
988 #ifdef CONFIG_X86_64
989         u64                   msr_host_kernel_gs_base;
990         u64                   msr_guest_kernel_gs_base;
991 #endif
992
993         u64                   arch_capabilities;
994         u64                   spec_ctrl;
995
996         u32 vm_entry_controls_shadow;
997         u32 vm_exit_controls_shadow;
998         u32 secondary_exec_control;
999
1000         /*
1001          * loaded_vmcs points to the VMCS currently used in this vcpu. For a
1002          * non-nested (L1) guest, it always points to vmcs01. For a nested
1003          * guest (L2), it points to a different VMCS.  loaded_cpu_state points
1004          * to the VMCS whose state is loaded into the CPU registers that only
1005          * need to be switched when transitioning to/from the kernel; a NULL
1006          * value indicates that host state is loaded.
1007          */
1008         struct loaded_vmcs    vmcs01;
1009         struct loaded_vmcs   *loaded_vmcs;
1010         struct loaded_vmcs   *loaded_cpu_state;
1011         bool                  __launched; /* temporary, used in vmx_vcpu_run */
1012         struct msr_autoload {
1013                 struct vmx_msrs guest;
1014                 struct vmx_msrs host;
1015         } msr_autoload;
1016
1017         struct {
1018                 int vm86_active;
1019                 ulong save_rflags;
1020                 struct kvm_segment segs[8];
1021         } rmode;
1022         struct {
1023                 u32 bitmask; /* 4 bits per segment (1 bit per field) */
1024                 struct kvm_save_segment {
1025                         u16 selector;
1026                         unsigned long base;
1027                         u32 limit;
1028                         u32 ar;
1029                 } seg[8];
1030         } segment_cache;
1031         int vpid;
1032         bool emulation_required;
1033
1034         u32 exit_reason;
1035
1036         /* Posted interrupt descriptor */
1037         struct pi_desc pi_desc;
1038
1039         /* Support for a guest hypervisor (nested VMX) */
1040         struct nested_vmx nested;
1041
1042         /* Dynamic PLE window. */
1043         int ple_window;
1044         bool ple_window_dirty;
1045
1046         bool req_immediate_exit;
1047
1048         /* Support for PML */
1049 #define PML_ENTITY_NUM          512
1050         struct page *pml_pg;
1051
1052         /* apic deadline value in host tsc */
1053         u64 hv_deadline_tsc;
1054
1055         u64 current_tsc_ratio;
1056
1057         u32 host_pkru;
1058
1059         unsigned long host_debugctlmsr;
1060
1061         /*
1062          * Only bits masked by msr_ia32_feature_control_valid_bits can be set in
1063          * msr_ia32_feature_control. FEATURE_CONTROL_LOCKED is always included
1064          * in msr_ia32_feature_control_valid_bits.
1065          */
1066         u64 msr_ia32_feature_control;
1067         u64 msr_ia32_feature_control_valid_bits;
1068         u64 ept_pointer;
1069 };
1070
1071 enum segment_cache_field {
1072         SEG_FIELD_SEL = 0,
1073         SEG_FIELD_BASE = 1,
1074         SEG_FIELD_LIMIT = 2,
1075         SEG_FIELD_AR = 3,
1076
1077         SEG_FIELD_NR = 4
1078 };
1079
1080 static inline struct kvm_vmx *to_kvm_vmx(struct kvm *kvm)
1081 {
1082         return container_of(kvm, struct kvm_vmx, kvm);
1083 }
1084
1085 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
1086 {
1087         return container_of(vcpu, struct vcpu_vmx, vcpu);
1088 }
1089
1090 static struct pi_desc *vcpu_to_pi_desc(struct kvm_vcpu *vcpu)
1091 {
1092         return &(to_vmx(vcpu)->pi_desc);
1093 }
1094
1095 #define ROL16(val, n) ((u16)(((u16)(val) << (n)) | ((u16)(val) >> (16 - (n)))))
1096 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
1097 #define FIELD(number, name)     [ROL16(number, 6)] = VMCS12_OFFSET(name)
1098 #define FIELD64(number, name)                                           \
1099         FIELD(number, name),                                            \
1100         [ROL16(number##_HIGH, 6)] = VMCS12_OFFSET(name) + sizeof(u32)
1101
1102
1103 static u16 shadow_read_only_fields[] = {
1104 #define SHADOW_FIELD_RO(x) x,
1105 #include "vmx_shadow_fields.h"
1106 };
1107 static int max_shadow_read_only_fields =
1108         ARRAY_SIZE(shadow_read_only_fields);
1109
1110 static u16 shadow_read_write_fields[] = {
1111 #define SHADOW_FIELD_RW(x) x,
1112 #include "vmx_shadow_fields.h"
1113 };
1114 static int max_shadow_read_write_fields =
1115         ARRAY_SIZE(shadow_read_write_fields);
1116
1117 static const unsigned short vmcs_field_to_offset_table[] = {
1118         FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
1119         FIELD(POSTED_INTR_NV, posted_intr_nv),
1120         FIELD(GUEST_ES_SELECTOR, guest_es_selector),
1121         FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
1122         FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
1123         FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
1124         FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
1125         FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
1126         FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
1127         FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
1128         FIELD(GUEST_INTR_STATUS, guest_intr_status),
1129         FIELD(GUEST_PML_INDEX, guest_pml_index),
1130         FIELD(HOST_ES_SELECTOR, host_es_selector),
1131         FIELD(HOST_CS_SELECTOR, host_cs_selector),
1132         FIELD(HOST_SS_SELECTOR, host_ss_selector),
1133         FIELD(HOST_DS_SELECTOR, host_ds_selector),
1134         FIELD(HOST_FS_SELECTOR, host_fs_selector),
1135         FIELD(HOST_GS_SELECTOR, host_gs_selector),
1136         FIELD(HOST_TR_SELECTOR, host_tr_selector),
1137         FIELD64(IO_BITMAP_A, io_bitmap_a),
1138         FIELD64(IO_BITMAP_B, io_bitmap_b),
1139         FIELD64(MSR_BITMAP, msr_bitmap),
1140         FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
1141         FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
1142         FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
1143         FIELD64(PML_ADDRESS, pml_address),
1144         FIELD64(TSC_OFFSET, tsc_offset),
1145         FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
1146         FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
1147         FIELD64(POSTED_INTR_DESC_ADDR, posted_intr_desc_addr),
1148         FIELD64(VM_FUNCTION_CONTROL, vm_function_control),
1149         FIELD64(EPT_POINTER, ept_pointer),
1150         FIELD64(EOI_EXIT_BITMAP0, eoi_exit_bitmap0),
1151         FIELD64(EOI_EXIT_BITMAP1, eoi_exit_bitmap1),
1152         FIELD64(EOI_EXIT_BITMAP2, eoi_exit_bitmap2),
1153         FIELD64(EOI_EXIT_BITMAP3, eoi_exit_bitmap3),
1154         FIELD64(EPTP_LIST_ADDRESS, eptp_list_address),
1155         FIELD64(VMREAD_BITMAP, vmread_bitmap),
1156         FIELD64(VMWRITE_BITMAP, vmwrite_bitmap),
1157         FIELD64(XSS_EXIT_BITMAP, xss_exit_bitmap),
1158         FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
1159         FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
1160         FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
1161         FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
1162         FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
1163         FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
1164         FIELD64(GUEST_PDPTR0, guest_pdptr0),
1165         FIELD64(GUEST_PDPTR1, guest_pdptr1),
1166         FIELD64(GUEST_PDPTR2, guest_pdptr2),
1167         FIELD64(GUEST_PDPTR3, guest_pdptr3),
1168         FIELD64(GUEST_BNDCFGS, guest_bndcfgs),
1169         FIELD64(HOST_IA32_PAT, host_ia32_pat),
1170         FIELD64(HOST_IA32_EFER, host_ia32_efer),
1171         FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
1172         FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
1173         FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
1174         FIELD(EXCEPTION_BITMAP, exception_bitmap),
1175         FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
1176         FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
1177         FIELD(CR3_TARGET_COUNT, cr3_target_count),
1178         FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
1179         FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
1180         FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
1181         FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
1182         FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
1183         FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
1184         FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
1185         FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
1186         FIELD(TPR_THRESHOLD, tpr_threshold),
1187         FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
1188         FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
1189         FIELD(VM_EXIT_REASON, vm_exit_reason),
1190         FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
1191         FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
1192         FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
1193         FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
1194         FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
1195         FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
1196         FIELD(GUEST_ES_LIMIT, guest_es_limit),
1197         FIELD(GUEST_CS_LIMIT, guest_cs_limit),
1198         FIELD(GUEST_SS_LIMIT, guest_ss_limit),
1199         FIELD(GUEST_DS_LIMIT, guest_ds_limit),
1200         FIELD(GUEST_FS_LIMIT, guest_fs_limit),
1201         FIELD(GUEST_GS_LIMIT, guest_gs_limit),
1202         FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
1203         FIELD(GUEST_TR_LIMIT, guest_tr_limit),
1204         FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
1205         FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
1206         FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
1207         FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
1208         FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
1209         FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
1210         FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
1211         FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
1212         FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
1213         FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
1214         FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
1215         FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
1216         FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
1217         FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
1218         FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
1219         FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
1220         FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
1221         FIELD(CR0_READ_SHADOW, cr0_read_shadow),
1222         FIELD(CR4_READ_SHADOW, cr4_read_shadow),
1223         FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
1224         FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
1225         FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
1226         FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
1227         FIELD(EXIT_QUALIFICATION, exit_qualification),
1228         FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
1229         FIELD(GUEST_CR0, guest_cr0),
1230         FIELD(GUEST_CR3, guest_cr3),
1231         FIELD(GUEST_CR4, guest_cr4),
1232         FIELD(GUEST_ES_BASE, guest_es_base),
1233         FIELD(GUEST_CS_BASE, guest_cs_base),
1234         FIELD(GUEST_SS_BASE, guest_ss_base),
1235         FIELD(GUEST_DS_BASE, guest_ds_base),
1236         FIELD(GUEST_FS_BASE, guest_fs_base),
1237         FIELD(GUEST_GS_BASE, guest_gs_base),
1238         FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
1239         FIELD(GUEST_TR_BASE, guest_tr_base),
1240         FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
1241         FIELD(GUEST_IDTR_BASE, guest_idtr_base),
1242         FIELD(GUEST_DR7, guest_dr7),
1243         FIELD(GUEST_RSP, guest_rsp),
1244         FIELD(GUEST_RIP, guest_rip),
1245         FIELD(GUEST_RFLAGS, guest_rflags),
1246         FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
1247         FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
1248         FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
1249         FIELD(HOST_CR0, host_cr0),
1250         FIELD(HOST_CR3, host_cr3),
1251         FIELD(HOST_CR4, host_cr4),
1252         FIELD(HOST_FS_BASE, host_fs_base),
1253         FIELD(HOST_GS_BASE, host_gs_base),
1254         FIELD(HOST_TR_BASE, host_tr_base),
1255         FIELD(HOST_GDTR_BASE, host_gdtr_base),
1256         FIELD(HOST_IDTR_BASE, host_idtr_base),
1257         FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
1258         FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
1259         FIELD(HOST_RSP, host_rsp),
1260         FIELD(HOST_RIP, host_rip),
1261 };
1262
1263 static inline short vmcs_field_to_offset(unsigned long field)
1264 {
1265         const size_t size = ARRAY_SIZE(vmcs_field_to_offset_table);
1266         unsigned short offset;
1267         unsigned index;
1268
1269         if (field >> 15)
1270                 return -ENOENT;
1271
1272         index = ROL16(field, 6);
1273         if (index >= size)
1274                 return -ENOENT;
1275
1276         index = array_index_nospec(index, size);
1277         offset = vmcs_field_to_offset_table[index];
1278         if (offset == 0)
1279                 return -ENOENT;
1280         return offset;
1281 }
1282
1283 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
1284 {
1285         return to_vmx(vcpu)->nested.cached_vmcs12;
1286 }
1287
1288 static inline struct vmcs12 *get_shadow_vmcs12(struct kvm_vcpu *vcpu)
1289 {
1290         return to_vmx(vcpu)->nested.cached_shadow_vmcs12;
1291 }
1292
1293 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu);
1294 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
1295 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa);
1296 static bool vmx_xsaves_supported(void);
1297 static void vmx_set_segment(struct kvm_vcpu *vcpu,
1298                             struct kvm_segment *var, int seg);
1299 static void vmx_get_segment(struct kvm_vcpu *vcpu,
1300                             struct kvm_segment *var, int seg);
1301 static bool guest_state_valid(struct kvm_vcpu *vcpu);
1302 static u32 vmx_segment_access_rights(struct kvm_segment *var);
1303 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
1304 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu);
1305 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked);
1306 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
1307                                             u16 error_code);
1308 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu);
1309 static void __always_inline vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
1310                                                           u32 msr, int type);
1311
1312 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
1313 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
1314 /*
1315  * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
1316  * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
1317  */
1318 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
1319
1320 /*
1321  * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
1322  * can find which vCPU should be waken up.
1323  */
1324 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
1325 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
1326
1327 enum {
1328         VMX_VMREAD_BITMAP,
1329         VMX_VMWRITE_BITMAP,
1330         VMX_BITMAP_NR
1331 };
1332
1333 static unsigned long *vmx_bitmap[VMX_BITMAP_NR];
1334
1335 #define vmx_vmread_bitmap                    (vmx_bitmap[VMX_VMREAD_BITMAP])
1336 #define vmx_vmwrite_bitmap                   (vmx_bitmap[VMX_VMWRITE_BITMAP])
1337
1338 static bool cpu_has_load_ia32_efer;
1339 static bool cpu_has_load_perf_global_ctrl;
1340
1341 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
1342 static DEFINE_SPINLOCK(vmx_vpid_lock);
1343
1344 static struct vmcs_config {
1345         int size;
1346         int order;
1347         u32 basic_cap;
1348         u32 revision_id;
1349         u32 pin_based_exec_ctrl;
1350         u32 cpu_based_exec_ctrl;
1351         u32 cpu_based_2nd_exec_ctrl;
1352         u32 vmexit_ctrl;
1353         u32 vmentry_ctrl;
1354         struct nested_vmx_msrs nested;
1355 } vmcs_config;
1356
1357 static struct vmx_capability {
1358         u32 ept;
1359         u32 vpid;
1360 } vmx_capability;
1361
1362 #define VMX_SEGMENT_FIELD(seg)                                  \
1363         [VCPU_SREG_##seg] = {                                   \
1364                 .selector = GUEST_##seg##_SELECTOR,             \
1365                 .base = GUEST_##seg##_BASE,                     \
1366                 .limit = GUEST_##seg##_LIMIT,                   \
1367                 .ar_bytes = GUEST_##seg##_AR_BYTES,             \
1368         }
1369
1370 static const struct kvm_vmx_segment_field {
1371         unsigned selector;
1372         unsigned base;
1373         unsigned limit;
1374         unsigned ar_bytes;
1375 } kvm_vmx_segment_fields[] = {
1376         VMX_SEGMENT_FIELD(CS),
1377         VMX_SEGMENT_FIELD(DS),
1378         VMX_SEGMENT_FIELD(ES),
1379         VMX_SEGMENT_FIELD(FS),
1380         VMX_SEGMENT_FIELD(GS),
1381         VMX_SEGMENT_FIELD(SS),
1382         VMX_SEGMENT_FIELD(TR),
1383         VMX_SEGMENT_FIELD(LDTR),
1384 };
1385
1386 static u64 host_efer;
1387
1388 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
1389
1390 /*
1391  * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
1392  * away by decrementing the array size.
1393  */
1394 static const u32 vmx_msr_index[] = {
1395 #ifdef CONFIG_X86_64
1396         MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
1397 #endif
1398         MSR_EFER, MSR_TSC_AUX, MSR_STAR,
1399 };
1400
1401 DEFINE_STATIC_KEY_FALSE(enable_evmcs);
1402
1403 #define current_evmcs ((struct hv_enlightened_vmcs *)this_cpu_read(current_vmcs))
1404
1405 #define KVM_EVMCS_VERSION 1
1406
1407 /*
1408  * Enlightened VMCSv1 doesn't support these:
1409  *
1410  *      POSTED_INTR_NV                  = 0x00000002,
1411  *      GUEST_INTR_STATUS               = 0x00000810,
1412  *      APIC_ACCESS_ADDR                = 0x00002014,
1413  *      POSTED_INTR_DESC_ADDR           = 0x00002016,
1414  *      EOI_EXIT_BITMAP0                = 0x0000201c,
1415  *      EOI_EXIT_BITMAP1                = 0x0000201e,
1416  *      EOI_EXIT_BITMAP2                = 0x00002020,
1417  *      EOI_EXIT_BITMAP3                = 0x00002022,
1418  *      GUEST_PML_INDEX                 = 0x00000812,
1419  *      PML_ADDRESS                     = 0x0000200e,
1420  *      VM_FUNCTION_CONTROL             = 0x00002018,
1421  *      EPTP_LIST_ADDRESS               = 0x00002024,
1422  *      VMREAD_BITMAP                   = 0x00002026,
1423  *      VMWRITE_BITMAP                  = 0x00002028,
1424  *
1425  *      TSC_MULTIPLIER                  = 0x00002032,
1426  *      PLE_GAP                         = 0x00004020,
1427  *      PLE_WINDOW                      = 0x00004022,
1428  *      VMX_PREEMPTION_TIMER_VALUE      = 0x0000482E,
1429  *      GUEST_IA32_PERF_GLOBAL_CTRL     = 0x00002808,
1430  *      HOST_IA32_PERF_GLOBAL_CTRL      = 0x00002c04,
1431  *
1432  * Currently unsupported in KVM:
1433  *      GUEST_IA32_RTIT_CTL             = 0x00002814,
1434  */
1435 #define EVMCS1_UNSUPPORTED_PINCTRL (PIN_BASED_POSTED_INTR | \
1436                                     PIN_BASED_VMX_PREEMPTION_TIMER)
1437 #define EVMCS1_UNSUPPORTED_2NDEXEC                                      \
1438         (SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |                         \
1439          SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |                      \
1440          SECONDARY_EXEC_APIC_REGISTER_VIRT |                            \
1441          SECONDARY_EXEC_ENABLE_PML |                                    \
1442          SECONDARY_EXEC_ENABLE_VMFUNC |                                 \
1443          SECONDARY_EXEC_SHADOW_VMCS |                                   \
1444          SECONDARY_EXEC_TSC_SCALING |                                   \
1445          SECONDARY_EXEC_PAUSE_LOOP_EXITING)
1446 #define EVMCS1_UNSUPPORTED_VMEXIT_CTRL (VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
1447 #define EVMCS1_UNSUPPORTED_VMENTRY_CTRL (VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
1448 #define EVMCS1_UNSUPPORTED_VMFUNC (VMX_VMFUNC_EPTP_SWITCHING)
1449
1450 #if IS_ENABLED(CONFIG_HYPERV)
1451 static bool __read_mostly enlightened_vmcs = true;
1452 module_param(enlightened_vmcs, bool, 0444);
1453
1454 static inline void evmcs_write64(unsigned long field, u64 value)
1455 {
1456         u16 clean_field;
1457         int offset = get_evmcs_offset(field, &clean_field);
1458
1459         if (offset < 0)
1460                 return;
1461
1462         *(u64 *)((char *)current_evmcs + offset) = value;
1463
1464         current_evmcs->hv_clean_fields &= ~clean_field;
1465 }
1466
1467 static inline void evmcs_write32(unsigned long field, u32 value)
1468 {
1469         u16 clean_field;
1470         int offset = get_evmcs_offset(field, &clean_field);
1471
1472         if (offset < 0)
1473                 return;
1474
1475         *(u32 *)((char *)current_evmcs + offset) = value;
1476         current_evmcs->hv_clean_fields &= ~clean_field;
1477 }
1478
1479 static inline void evmcs_write16(unsigned long field, u16 value)
1480 {
1481         u16 clean_field;
1482         int offset = get_evmcs_offset(field, &clean_field);
1483
1484         if (offset < 0)
1485                 return;
1486
1487         *(u16 *)((char *)current_evmcs + offset) = value;
1488         current_evmcs->hv_clean_fields &= ~clean_field;
1489 }
1490
1491 static inline u64 evmcs_read64(unsigned long field)
1492 {
1493         int offset = get_evmcs_offset(field, NULL);
1494
1495         if (offset < 0)
1496                 return 0;
1497
1498         return *(u64 *)((char *)current_evmcs + offset);
1499 }
1500
1501 static inline u32 evmcs_read32(unsigned long field)
1502 {
1503         int offset = get_evmcs_offset(field, NULL);
1504
1505         if (offset < 0)
1506                 return 0;
1507
1508         return *(u32 *)((char *)current_evmcs + offset);
1509 }
1510
1511 static inline u16 evmcs_read16(unsigned long field)
1512 {
1513         int offset = get_evmcs_offset(field, NULL);
1514
1515         if (offset < 0)
1516                 return 0;
1517
1518         return *(u16 *)((char *)current_evmcs + offset);
1519 }
1520
1521 static inline void evmcs_touch_msr_bitmap(void)
1522 {
1523         if (unlikely(!current_evmcs))
1524                 return;
1525
1526         if (current_evmcs->hv_enlightenments_control.msr_bitmap)
1527                 current_evmcs->hv_clean_fields &=
1528                         ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP;
1529 }
1530
1531 static void evmcs_load(u64 phys_addr)
1532 {
1533         struct hv_vp_assist_page *vp_ap =
1534                 hv_get_vp_assist_page(smp_processor_id());
1535
1536         vp_ap->current_nested_vmcs = phys_addr;
1537         vp_ap->enlighten_vmentry = 1;
1538 }
1539
1540 static void evmcs_sanitize_exec_ctrls(struct vmcs_config *vmcs_conf)
1541 {
1542         vmcs_conf->pin_based_exec_ctrl &= ~EVMCS1_UNSUPPORTED_PINCTRL;
1543         vmcs_conf->cpu_based_2nd_exec_ctrl &= ~EVMCS1_UNSUPPORTED_2NDEXEC;
1544
1545         vmcs_conf->vmexit_ctrl &= ~EVMCS1_UNSUPPORTED_VMEXIT_CTRL;
1546         vmcs_conf->vmentry_ctrl &= ~EVMCS1_UNSUPPORTED_VMENTRY_CTRL;
1547
1548 }
1549
1550 /* check_ept_pointer() should be under protection of ept_pointer_lock. */
1551 static void check_ept_pointer_match(struct kvm *kvm)
1552 {
1553         struct kvm_vcpu *vcpu;
1554         u64 tmp_eptp = INVALID_PAGE;
1555         int i;
1556
1557         kvm_for_each_vcpu(i, vcpu, kvm) {
1558                 if (!VALID_PAGE(tmp_eptp)) {
1559                         tmp_eptp = to_vmx(vcpu)->ept_pointer;
1560                 } else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
1561                         to_kvm_vmx(kvm)->ept_pointers_match
1562                                 = EPT_POINTERS_MISMATCH;
1563                         return;
1564                 }
1565         }
1566
1567         to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
1568 }
1569
1570 static int vmx_hv_remote_flush_tlb(struct kvm *kvm)
1571 {
1572         struct kvm_vcpu *vcpu;
1573         int ret = -ENOTSUPP, i;
1574
1575         spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
1576
1577         if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
1578                 check_ept_pointer_match(kvm);
1579
1580         if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
1581                 kvm_for_each_vcpu(i, vcpu, kvm)
1582                         ret |= hyperv_flush_guest_mapping(
1583                                 to_vmx(kvm_get_vcpu(kvm, i))->ept_pointer);
1584         } else {
1585                 ret = hyperv_flush_guest_mapping(
1586                                 to_vmx(kvm_get_vcpu(kvm, 0))->ept_pointer);
1587         }
1588
1589         spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
1590         return ret;
1591 }
1592 #else /* !IS_ENABLED(CONFIG_HYPERV) */
1593 static inline void evmcs_write64(unsigned long field, u64 value) {}
1594 static inline void evmcs_write32(unsigned long field, u32 value) {}
1595 static inline void evmcs_write16(unsigned long field, u16 value) {}
1596 static inline u64 evmcs_read64(unsigned long field) { return 0; }
1597 static inline u32 evmcs_read32(unsigned long field) { return 0; }
1598 static inline u16 evmcs_read16(unsigned long field) { return 0; }
1599 static inline void evmcs_load(u64 phys_addr) {}
1600 static inline void evmcs_sanitize_exec_ctrls(struct vmcs_config *vmcs_conf) {}
1601 static inline void evmcs_touch_msr_bitmap(void) {}
1602 #endif /* IS_ENABLED(CONFIG_HYPERV) */
1603
1604 static int nested_enable_evmcs(struct kvm_vcpu *vcpu,
1605                                uint16_t *vmcs_version)
1606 {
1607         struct vcpu_vmx *vmx = to_vmx(vcpu);
1608
1609         /* We don't support disabling the feature for simplicity. */
1610         if (vmx->nested.enlightened_vmcs_enabled)
1611                 return 0;
1612
1613         vmx->nested.enlightened_vmcs_enabled = true;
1614
1615         /*
1616          * vmcs_version represents the range of supported Enlightened VMCS
1617          * versions: lower 8 bits is the minimal version, higher 8 bits is the
1618          * maximum supported version. KVM supports versions from 1 to
1619          * KVM_EVMCS_VERSION.
1620          */
1621         *vmcs_version = (KVM_EVMCS_VERSION << 8) | 1;
1622
1623         vmx->nested.msrs.pinbased_ctls_high &= ~EVMCS1_UNSUPPORTED_PINCTRL;
1624         vmx->nested.msrs.entry_ctls_high &= ~EVMCS1_UNSUPPORTED_VMENTRY_CTRL;
1625         vmx->nested.msrs.exit_ctls_high &= ~EVMCS1_UNSUPPORTED_VMEXIT_CTRL;
1626         vmx->nested.msrs.secondary_ctls_high &= ~EVMCS1_UNSUPPORTED_2NDEXEC;
1627         vmx->nested.msrs.vmfunc_controls &= ~EVMCS1_UNSUPPORTED_VMFUNC;
1628
1629         return 0;
1630 }
1631
1632 static inline bool is_exception_n(u32 intr_info, u8 vector)
1633 {
1634         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1635                              INTR_INFO_VALID_MASK)) ==
1636                 (INTR_TYPE_HARD_EXCEPTION | vector | INTR_INFO_VALID_MASK);
1637 }
1638
1639 static inline bool is_debug(u32 intr_info)
1640 {
1641         return is_exception_n(intr_info, DB_VECTOR);
1642 }
1643
1644 static inline bool is_breakpoint(u32 intr_info)
1645 {
1646         return is_exception_n(intr_info, BP_VECTOR);
1647 }
1648
1649 static inline bool is_page_fault(u32 intr_info)
1650 {
1651         return is_exception_n(intr_info, PF_VECTOR);
1652 }
1653
1654 static inline bool is_invalid_opcode(u32 intr_info)
1655 {
1656         return is_exception_n(intr_info, UD_VECTOR);
1657 }
1658
1659 static inline bool is_gp_fault(u32 intr_info)
1660 {
1661         return is_exception_n(intr_info, GP_VECTOR);
1662 }
1663
1664 static inline bool is_machine_check(u32 intr_info)
1665 {
1666         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1667                              INTR_INFO_VALID_MASK)) ==
1668                 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
1669 }
1670
1671 /* Undocumented: icebp/int1 */
1672 static inline bool is_icebp(u32 intr_info)
1673 {
1674         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1675                 == (INTR_TYPE_PRIV_SW_EXCEPTION | INTR_INFO_VALID_MASK);
1676 }
1677
1678 static inline bool cpu_has_vmx_msr_bitmap(void)
1679 {
1680         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
1681 }
1682
1683 static inline bool cpu_has_vmx_tpr_shadow(void)
1684 {
1685         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
1686 }
1687
1688 static inline bool cpu_need_tpr_shadow(struct kvm_vcpu *vcpu)
1689 {
1690         return cpu_has_vmx_tpr_shadow() && lapic_in_kernel(vcpu);
1691 }
1692
1693 static inline bool cpu_has_secondary_exec_ctrls(void)
1694 {
1695         return vmcs_config.cpu_based_exec_ctrl &
1696                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1697 }
1698
1699 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
1700 {
1701         return vmcs_config.cpu_based_2nd_exec_ctrl &
1702                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1703 }
1704
1705 static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
1706 {
1707         return vmcs_config.cpu_based_2nd_exec_ctrl &
1708                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
1709 }
1710
1711 static inline bool cpu_has_vmx_apic_register_virt(void)
1712 {
1713         return vmcs_config.cpu_based_2nd_exec_ctrl &
1714                 SECONDARY_EXEC_APIC_REGISTER_VIRT;
1715 }
1716
1717 static inline bool cpu_has_vmx_virtual_intr_delivery(void)
1718 {
1719         return vmcs_config.cpu_based_2nd_exec_ctrl &
1720                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1721 }
1722
1723 static inline bool cpu_has_vmx_encls_vmexit(void)
1724 {
1725         return vmcs_config.cpu_based_2nd_exec_ctrl &
1726                 SECONDARY_EXEC_ENCLS_EXITING;
1727 }
1728
1729 /*
1730  * Comment's format: document - errata name - stepping - processor name.
1731  * Refer from
1732  * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
1733  */
1734 static u32 vmx_preemption_cpu_tfms[] = {
1735 /* 323344.pdf - BA86   - D0 - Xeon 7500 Series */
1736 0x000206E6,
1737 /* 323056.pdf - AAX65  - C2 - Xeon L3406 */
1738 /* 322814.pdf - AAT59  - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
1739 /* 322911.pdf - AAU65  - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
1740 0x00020652,
1741 /* 322911.pdf - AAU65  - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
1742 0x00020655,
1743 /* 322373.pdf - AAO95  - B1 - Xeon 3400 Series */
1744 /* 322166.pdf - AAN92  - B1 - i7-800 and i5-700 Desktop */
1745 /*
1746  * 320767.pdf - AAP86  - B1 -
1747  * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
1748  */
1749 0x000106E5,
1750 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
1751 0x000106A0,
1752 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
1753 0x000106A1,
1754 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
1755 0x000106A4,
1756  /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
1757  /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
1758  /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
1759 0x000106A5,
1760 };
1761
1762 static inline bool cpu_has_broken_vmx_preemption_timer(void)
1763 {
1764         u32 eax = cpuid_eax(0x00000001), i;
1765
1766         /* Clear the reserved bits */
1767         eax &= ~(0x3U << 14 | 0xfU << 28);
1768         for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
1769                 if (eax == vmx_preemption_cpu_tfms[i])
1770                         return true;
1771
1772         return false;
1773 }
1774
1775 static inline bool cpu_has_vmx_preemption_timer(void)
1776 {
1777         return vmcs_config.pin_based_exec_ctrl &
1778                 PIN_BASED_VMX_PREEMPTION_TIMER;
1779 }
1780
1781 static inline bool cpu_has_vmx_posted_intr(void)
1782 {
1783         return IS_ENABLED(CONFIG_X86_LOCAL_APIC) &&
1784                 vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
1785 }
1786
1787 static inline bool cpu_has_vmx_apicv(void)
1788 {
1789         return cpu_has_vmx_apic_register_virt() &&
1790                 cpu_has_vmx_virtual_intr_delivery() &&
1791                 cpu_has_vmx_posted_intr();
1792 }
1793
1794 static inline bool cpu_has_vmx_flexpriority(void)
1795 {
1796         return cpu_has_vmx_tpr_shadow() &&
1797                 cpu_has_vmx_virtualize_apic_accesses();
1798 }
1799
1800 static inline bool cpu_has_vmx_ept_execute_only(void)
1801 {
1802         return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
1803 }
1804
1805 static inline bool cpu_has_vmx_ept_2m_page(void)
1806 {
1807         return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
1808 }
1809
1810 static inline bool cpu_has_vmx_ept_1g_page(void)
1811 {
1812         return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
1813 }
1814
1815 static inline bool cpu_has_vmx_ept_4levels(void)
1816 {
1817         return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
1818 }
1819
1820 static inline bool cpu_has_vmx_ept_mt_wb(void)
1821 {
1822         return vmx_capability.ept & VMX_EPTP_WB_BIT;
1823 }
1824
1825 static inline bool cpu_has_vmx_ept_5levels(void)
1826 {
1827         return vmx_capability.ept & VMX_EPT_PAGE_WALK_5_BIT;
1828 }
1829
1830 static inline bool cpu_has_vmx_ept_ad_bits(void)
1831 {
1832         return vmx_capability.ept & VMX_EPT_AD_BIT;
1833 }
1834
1835 static inline bool cpu_has_vmx_invept_context(void)
1836 {
1837         return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
1838 }
1839
1840 static inline bool cpu_has_vmx_invept_global(void)
1841 {
1842         return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
1843 }
1844
1845 static inline bool cpu_has_vmx_invvpid_individual_addr(void)
1846 {
1847         return vmx_capability.vpid & VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT;
1848 }
1849
1850 static inline bool cpu_has_vmx_invvpid_single(void)
1851 {
1852         return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
1853 }
1854
1855 static inline bool cpu_has_vmx_invvpid_global(void)
1856 {
1857         return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
1858 }
1859
1860 static inline bool cpu_has_vmx_invvpid(void)
1861 {
1862         return vmx_capability.vpid & VMX_VPID_INVVPID_BIT;
1863 }
1864
1865 static inline bool cpu_has_vmx_ept(void)
1866 {
1867         return vmcs_config.cpu_based_2nd_exec_ctrl &
1868                 SECONDARY_EXEC_ENABLE_EPT;
1869 }
1870
1871 static inline bool cpu_has_vmx_unrestricted_guest(void)
1872 {
1873         return vmcs_config.cpu_based_2nd_exec_ctrl &
1874                 SECONDARY_EXEC_UNRESTRICTED_GUEST;
1875 }
1876
1877 static inline bool cpu_has_vmx_ple(void)
1878 {
1879         return vmcs_config.cpu_based_2nd_exec_ctrl &
1880                 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1881 }
1882
1883 static inline bool cpu_has_vmx_basic_inout(void)
1884 {
1885         return  (((u64)vmcs_config.basic_cap << 32) & VMX_BASIC_INOUT);
1886 }
1887
1888 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
1889 {
1890         return flexpriority_enabled && lapic_in_kernel(vcpu);
1891 }
1892
1893 static inline bool cpu_has_vmx_vpid(void)
1894 {
1895         return vmcs_config.cpu_based_2nd_exec_ctrl &
1896                 SECONDARY_EXEC_ENABLE_VPID;
1897 }
1898
1899 static inline bool cpu_has_vmx_rdtscp(void)
1900 {
1901         return vmcs_config.cpu_based_2nd_exec_ctrl &
1902                 SECONDARY_EXEC_RDTSCP;
1903 }
1904
1905 static inline bool cpu_has_vmx_invpcid(void)
1906 {
1907         return vmcs_config.cpu_based_2nd_exec_ctrl &
1908                 SECONDARY_EXEC_ENABLE_INVPCID;
1909 }
1910
1911 static inline bool cpu_has_virtual_nmis(void)
1912 {
1913         return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1914 }
1915
1916 static inline bool cpu_has_vmx_wbinvd_exit(void)
1917 {
1918         return vmcs_config.cpu_based_2nd_exec_ctrl &
1919                 SECONDARY_EXEC_WBINVD_EXITING;
1920 }
1921
1922 static inline bool cpu_has_vmx_shadow_vmcs(void)
1923 {
1924         u64 vmx_msr;
1925         rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1926         /* check if the cpu supports writing r/o exit information fields */
1927         if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1928                 return false;
1929
1930         return vmcs_config.cpu_based_2nd_exec_ctrl &
1931                 SECONDARY_EXEC_SHADOW_VMCS;
1932 }
1933
1934 static inline bool cpu_has_vmx_pml(void)
1935 {
1936         return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_PML;
1937 }
1938
1939 static inline bool cpu_has_vmx_tsc_scaling(void)
1940 {
1941         return vmcs_config.cpu_based_2nd_exec_ctrl &
1942                 SECONDARY_EXEC_TSC_SCALING;
1943 }
1944
1945 static inline bool cpu_has_vmx_vmfunc(void)
1946 {
1947         return vmcs_config.cpu_based_2nd_exec_ctrl &
1948                 SECONDARY_EXEC_ENABLE_VMFUNC;
1949 }
1950
1951 static bool vmx_umip_emulated(void)
1952 {
1953         return vmcs_config.cpu_based_2nd_exec_ctrl &
1954                 SECONDARY_EXEC_DESC;
1955 }
1956
1957 static inline bool report_flexpriority(void)
1958 {
1959         return flexpriority_enabled;
1960 }
1961
1962 static inline unsigned nested_cpu_vmx_misc_cr3_count(struct kvm_vcpu *vcpu)
1963 {
1964         return vmx_misc_cr3_count(to_vmx(vcpu)->nested.msrs.misc_low);
1965 }
1966
1967 /*
1968  * Do the virtual VMX capability MSRs specify that L1 can use VMWRITE
1969  * to modify any valid field of the VMCS, or are the VM-exit
1970  * information fields read-only?
1971  */
1972 static inline bool nested_cpu_has_vmwrite_any_field(struct kvm_vcpu *vcpu)
1973 {
1974         return to_vmx(vcpu)->nested.msrs.misc_low &
1975                 MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS;
1976 }
1977
1978 static inline bool nested_cpu_has_zero_length_injection(struct kvm_vcpu *vcpu)
1979 {
1980         return to_vmx(vcpu)->nested.msrs.misc_low & VMX_MISC_ZERO_LEN_INS;
1981 }
1982
1983 static inline bool nested_cpu_supports_monitor_trap_flag(struct kvm_vcpu *vcpu)
1984 {
1985         return to_vmx(vcpu)->nested.msrs.procbased_ctls_high &
1986                         CPU_BASED_MONITOR_TRAP_FLAG;
1987 }
1988
1989 static inline bool nested_cpu_has_vmx_shadow_vmcs(struct kvm_vcpu *vcpu)
1990 {
1991         return to_vmx(vcpu)->nested.msrs.secondary_ctls_high &
1992                 SECONDARY_EXEC_SHADOW_VMCS;
1993 }
1994
1995 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
1996 {
1997         return vmcs12->cpu_based_vm_exec_control & bit;
1998 }
1999
2000 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
2001 {
2002         return (vmcs12->cpu_based_vm_exec_control &
2003                         CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
2004                 (vmcs12->secondary_vm_exec_control & bit);
2005 }
2006
2007 static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
2008 {
2009         return vmcs12->pin_based_vm_exec_control &
2010                 PIN_BASED_VMX_PREEMPTION_TIMER;
2011 }
2012
2013 static inline bool nested_cpu_has_nmi_exiting(struct vmcs12 *vmcs12)
2014 {
2015         return vmcs12->pin_based_vm_exec_control & PIN_BASED_NMI_EXITING;
2016 }
2017
2018 static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12)
2019 {
2020         return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
2021 }
2022
2023 static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
2024 {
2025         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
2026 }
2027
2028 static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
2029 {
2030         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
2031 }
2032
2033 static inline bool nested_cpu_has_pml(struct vmcs12 *vmcs12)
2034 {
2035         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML);
2036 }
2037
2038 static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
2039 {
2040         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
2041 }
2042
2043 static inline bool nested_cpu_has_vpid(struct vmcs12 *vmcs12)
2044 {
2045         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VPID);
2046 }
2047
2048 static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
2049 {
2050         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
2051 }
2052
2053 static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
2054 {
2055         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2056 }
2057
2058 static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
2059 {
2060         return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
2061 }
2062
2063 static inline bool nested_cpu_has_vmfunc(struct vmcs12 *vmcs12)
2064 {
2065         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VMFUNC);
2066 }
2067
2068 static inline bool nested_cpu_has_eptp_switching(struct vmcs12 *vmcs12)
2069 {
2070         return nested_cpu_has_vmfunc(vmcs12) &&
2071                 (vmcs12->vm_function_control &
2072                  VMX_VMFUNC_EPTP_SWITCHING);
2073 }
2074
2075 static inline bool nested_cpu_has_shadow_vmcs(struct vmcs12 *vmcs12)
2076 {
2077         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_SHADOW_VMCS);
2078 }
2079
2080 static inline bool is_nmi(u32 intr_info)
2081 {
2082         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
2083                 == (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK);
2084 }
2085
2086 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
2087                               u32 exit_intr_info,
2088                               unsigned long exit_qualification);
2089
2090 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
2091 {
2092         int i;
2093
2094         for (i = 0; i < vmx->nmsrs; ++i)
2095                 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
2096                         return i;
2097         return -1;
2098 }
2099
2100 static inline void __invvpid(unsigned long ext, u16 vpid, gva_t gva)
2101 {
2102     struct {
2103         u64 vpid : 16;
2104         u64 rsvd : 48;
2105         u64 gva;
2106     } operand = { vpid, 0, gva };
2107     bool error;
2108
2109     asm volatile (__ex("invvpid %2, %1") CC_SET(na)
2110                   : CC_OUT(na) (error) : "r"(ext), "m"(operand));
2111     BUG_ON(error);
2112 }
2113
2114 static inline void __invept(unsigned long ext, u64 eptp, gpa_t gpa)
2115 {
2116         struct {
2117                 u64 eptp, gpa;
2118         } operand = {eptp, gpa};
2119         bool error;
2120
2121         asm volatile (__ex("invept %2, %1") CC_SET(na)
2122                       : CC_OUT(na) (error) : "r"(ext), "m"(operand));
2123         BUG_ON(error);
2124 }
2125
2126 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
2127 {
2128         int i;
2129
2130         i = __find_msr_index(vmx, msr);
2131         if (i >= 0)
2132                 return &vmx->guest_msrs[i];
2133         return NULL;
2134 }
2135
2136 static void vmcs_clear(struct vmcs *vmcs)
2137 {
2138         u64 phys_addr = __pa(vmcs);
2139         bool error;
2140
2141         asm volatile (__ex("vmclear %1") CC_SET(na)
2142                       : CC_OUT(na) (error) : "m"(phys_addr));
2143         if (unlikely(error))
2144                 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
2145                        vmcs, phys_addr);
2146 }
2147
2148 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
2149 {
2150         vmcs_clear(loaded_vmcs->vmcs);
2151         if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
2152                 vmcs_clear(loaded_vmcs->shadow_vmcs);
2153         loaded_vmcs->cpu = -1;
2154         loaded_vmcs->launched = 0;
2155 }
2156
2157 static void vmcs_load(struct vmcs *vmcs)
2158 {
2159         u64 phys_addr = __pa(vmcs);
2160         bool error;
2161
2162         if (static_branch_unlikely(&enable_evmcs))
2163                 return evmcs_load(phys_addr);
2164
2165         asm volatile (__ex("vmptrld %1") CC_SET(na)
2166                       : CC_OUT(na) (error) : "m"(phys_addr));
2167         if (unlikely(error))
2168                 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
2169                        vmcs, phys_addr);
2170 }
2171
2172 #ifdef CONFIG_KEXEC_CORE
2173 /*
2174  * This bitmap is used to indicate whether the vmclear
2175  * operation is enabled on all cpus. All disabled by
2176  * default.
2177  */
2178 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
2179
2180 static inline void crash_enable_local_vmclear(int cpu)
2181 {
2182         cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
2183 }
2184
2185 static inline void crash_disable_local_vmclear(int cpu)
2186 {
2187         cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
2188 }
2189
2190 static inline int crash_local_vmclear_enabled(int cpu)
2191 {
2192         return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
2193 }
2194
2195 static void crash_vmclear_local_loaded_vmcss(void)
2196 {
2197         int cpu = raw_smp_processor_id();
2198         struct loaded_vmcs *v;
2199
2200         if (!crash_local_vmclear_enabled(cpu))
2201                 return;
2202
2203         list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
2204                             loaded_vmcss_on_cpu_link)
2205                 vmcs_clear(v->vmcs);
2206 }
2207 #else
2208 static inline void crash_enable_local_vmclear(int cpu) { }
2209 static inline void crash_disable_local_vmclear(int cpu) { }
2210 #endif /* CONFIG_KEXEC_CORE */
2211
2212 static void __loaded_vmcs_clear(void *arg)
2213 {
2214         struct loaded_vmcs *loaded_vmcs = arg;
2215         int cpu = raw_smp_processor_id();
2216
2217         if (loaded_vmcs->cpu != cpu)
2218                 return; /* vcpu migration can race with cpu offline */
2219         if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
2220                 per_cpu(current_vmcs, cpu) = NULL;
2221         crash_disable_local_vmclear(cpu);
2222         list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
2223
2224         /*
2225          * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
2226          * is before setting loaded_vmcs->vcpu to -1 which is done in
2227          * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
2228          * then adds the vmcs into percpu list before it is deleted.
2229          */
2230         smp_wmb();
2231
2232         loaded_vmcs_init(loaded_vmcs);
2233         crash_enable_local_vmclear(cpu);
2234 }
2235
2236 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
2237 {
2238         int cpu = loaded_vmcs->cpu;
2239
2240         if (cpu != -1)
2241                 smp_call_function_single(cpu,
2242                          __loaded_vmcs_clear, loaded_vmcs, 1);
2243 }
2244
2245 static inline bool vpid_sync_vcpu_addr(int vpid, gva_t addr)
2246 {
2247         if (vpid == 0)
2248                 return true;
2249
2250         if (cpu_has_vmx_invvpid_individual_addr()) {
2251                 __invvpid(VMX_VPID_EXTENT_INDIVIDUAL_ADDR, vpid, addr);
2252                 return true;
2253         }
2254
2255         return false;
2256 }
2257
2258 static inline void vpid_sync_vcpu_single(int vpid)
2259 {
2260         if (vpid == 0)
2261                 return;
2262
2263         if (cpu_has_vmx_invvpid_single())
2264                 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vpid, 0);
2265 }
2266
2267 static inline void vpid_sync_vcpu_global(void)
2268 {
2269         if (cpu_has_vmx_invvpid_global())
2270                 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
2271 }
2272
2273 static inline void vpid_sync_context(int vpid)
2274 {
2275         if (cpu_has_vmx_invvpid_single())
2276                 vpid_sync_vcpu_single(vpid);
2277         else
2278                 vpid_sync_vcpu_global();
2279 }
2280
2281 static inline void ept_sync_global(void)
2282 {
2283         __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
2284 }
2285
2286 static inline void ept_sync_context(u64 eptp)
2287 {
2288         if (cpu_has_vmx_invept_context())
2289                 __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
2290         else
2291                 ept_sync_global();
2292 }
2293
2294 static __always_inline void vmcs_check16(unsigned long field)
2295 {
2296         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
2297                          "16-bit accessor invalid for 64-bit field");
2298         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2299                          "16-bit accessor invalid for 64-bit high field");
2300         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2301                          "16-bit accessor invalid for 32-bit high field");
2302         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2303                          "16-bit accessor invalid for natural width field");
2304 }
2305
2306 static __always_inline void vmcs_check32(unsigned long field)
2307 {
2308         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2309                          "32-bit accessor invalid for 16-bit field");
2310         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2311                          "32-bit accessor invalid for natural width field");
2312 }
2313
2314 static __always_inline void vmcs_check64(unsigned long field)
2315 {
2316         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2317                          "64-bit accessor invalid for 16-bit field");
2318         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2319                          "64-bit accessor invalid for 64-bit high field");
2320         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2321                          "64-bit accessor invalid for 32-bit field");
2322         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2323                          "64-bit accessor invalid for natural width field");
2324 }
2325
2326 static __always_inline void vmcs_checkl(unsigned long field)
2327 {
2328         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2329                          "Natural width accessor invalid for 16-bit field");
2330         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
2331                          "Natural width accessor invalid for 64-bit field");
2332         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2333                          "Natural width accessor invalid for 64-bit high field");
2334         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2335                          "Natural width accessor invalid for 32-bit field");
2336 }
2337
2338 static __always_inline unsigned long __vmcs_readl(unsigned long field)
2339 {
2340         unsigned long value;
2341
2342         asm volatile (__ex_clear("vmread %1, %0", "%k0")
2343                       : "=r"(value) : "r"(field));
2344         return value;
2345 }
2346
2347 static __always_inline u16 vmcs_read16(unsigned long field)
2348 {
2349         vmcs_check16(field);
2350         if (static_branch_unlikely(&enable_evmcs))
2351                 return evmcs_read16(field);
2352         return __vmcs_readl(field);
2353 }
2354
2355 static __always_inline u32 vmcs_read32(unsigned long field)
2356 {
2357         vmcs_check32(field);
2358         if (static_branch_unlikely(&enable_evmcs))
2359                 return evmcs_read32(field);
2360         return __vmcs_readl(field);
2361 }
2362
2363 static __always_inline u64 vmcs_read64(unsigned long field)
2364 {
2365         vmcs_check64(field);
2366         if (static_branch_unlikely(&enable_evmcs))
2367                 return evmcs_read64(field);
2368 #ifdef CONFIG_X86_64
2369         return __vmcs_readl(field);
2370 #else
2371         return __vmcs_readl(field) | ((u64)__vmcs_readl(field+1) << 32);
2372 #endif
2373 }
2374
2375 static __always_inline unsigned long vmcs_readl(unsigned long field)
2376 {
2377         vmcs_checkl(field);
2378         if (static_branch_unlikely(&enable_evmcs))
2379                 return evmcs_read64(field);
2380         return __vmcs_readl(field);
2381 }
2382
2383 static noinline void vmwrite_error(unsigned long field, unsigned long value)
2384 {
2385         printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
2386                field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
2387         dump_stack();
2388 }
2389
2390 static __always_inline void __vmcs_writel(unsigned long field, unsigned long value)
2391 {
2392         bool error;
2393
2394         asm volatile (__ex("vmwrite %2, %1") CC_SET(na)
2395                       : CC_OUT(na) (error) : "r"(field), "rm"(value));
2396         if (unlikely(error))
2397                 vmwrite_error(field, value);
2398 }
2399
2400 static __always_inline void vmcs_write16(unsigned long field, u16 value)
2401 {
2402         vmcs_check16(field);
2403         if (static_branch_unlikely(&enable_evmcs))
2404                 return evmcs_write16(field, value);
2405
2406         __vmcs_writel(field, value);
2407 }
2408
2409 static __always_inline void vmcs_write32(unsigned long field, u32 value)
2410 {
2411         vmcs_check32(field);
2412         if (static_branch_unlikely(&enable_evmcs))
2413                 return evmcs_write32(field, value);
2414
2415         __vmcs_writel(field, value);
2416 }
2417
2418 static __always_inline void vmcs_write64(unsigned long field, u64 value)
2419 {
2420         vmcs_check64(field);
2421         if (static_branch_unlikely(&enable_evmcs))
2422                 return evmcs_write64(field, value);
2423
2424         __vmcs_writel(field, value);
2425 #ifndef CONFIG_X86_64
2426         asm volatile ("");
2427         __vmcs_writel(field+1, value >> 32);
2428 #endif
2429 }
2430
2431 static __always_inline void vmcs_writel(unsigned long field, unsigned long value)
2432 {
2433         vmcs_checkl(field);
2434         if (static_branch_unlikely(&enable_evmcs))
2435                 return evmcs_write64(field, value);
2436
2437         __vmcs_writel(field, value);
2438 }
2439
2440 static __always_inline void vmcs_clear_bits(unsigned long field, u32 mask)
2441 {
2442         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
2443                          "vmcs_clear_bits does not support 64-bit fields");
2444         if (static_branch_unlikely(&enable_evmcs))
2445                 return evmcs_write32(field, evmcs_read32(field) & ~mask);
2446
2447         __vmcs_writel(field, __vmcs_readl(field) & ~mask);
2448 }
2449
2450 static __always_inline void vmcs_set_bits(unsigned long field, u32 mask)
2451 {
2452         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
2453                          "vmcs_set_bits does not support 64-bit fields");
2454         if (static_branch_unlikely(&enable_evmcs))
2455                 return evmcs_write32(field, evmcs_read32(field) | mask);
2456
2457         __vmcs_writel(field, __vmcs_readl(field) | mask);
2458 }
2459
2460 static inline void vm_entry_controls_reset_shadow(struct vcpu_vmx *vmx)
2461 {
2462         vmx->vm_entry_controls_shadow = vmcs_read32(VM_ENTRY_CONTROLS);
2463 }
2464
2465 static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
2466 {
2467         vmcs_write32(VM_ENTRY_CONTROLS, val);
2468         vmx->vm_entry_controls_shadow = val;
2469 }
2470
2471 static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
2472 {
2473         if (vmx->vm_entry_controls_shadow != val)
2474                 vm_entry_controls_init(vmx, val);
2475 }
2476
2477 static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
2478 {
2479         return vmx->vm_entry_controls_shadow;
2480 }
2481
2482
2483 static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
2484 {
2485         vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
2486 }
2487
2488 static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
2489 {
2490         vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
2491 }
2492
2493 static inline void vm_exit_controls_reset_shadow(struct vcpu_vmx *vmx)
2494 {
2495         vmx->vm_exit_controls_shadow = vmcs_read32(VM_EXIT_CONTROLS);
2496 }
2497
2498 static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
2499 {
2500         vmcs_write32(VM_EXIT_CONTROLS, val);
2501         vmx->vm_exit_controls_shadow = val;
2502 }
2503
2504 static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
2505 {
2506         if (vmx->vm_exit_controls_shadow != val)
2507                 vm_exit_controls_init(vmx, val);
2508 }
2509
2510 static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
2511 {
2512         return vmx->vm_exit_controls_shadow;
2513 }
2514
2515
2516 static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
2517 {
2518         vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
2519 }
2520
2521 static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
2522 {
2523         vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
2524 }
2525
2526 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
2527 {
2528         vmx->segment_cache.bitmask = 0;
2529 }
2530
2531 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
2532                                        unsigned field)
2533 {
2534         bool ret;
2535         u32 mask = 1 << (seg * SEG_FIELD_NR + field);
2536
2537         if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
2538                 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
2539                 vmx->segment_cache.bitmask = 0;
2540         }
2541         ret = vmx->segment_cache.bitmask & mask;
2542         vmx->segment_cache.bitmask |= mask;
2543         return ret;
2544 }
2545
2546 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
2547 {
2548         u16 *p = &vmx->segment_cache.seg[seg].selector;
2549
2550         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
2551                 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
2552         return *p;
2553 }
2554
2555 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
2556 {
2557         ulong *p = &vmx->segment_cache.seg[seg].base;
2558
2559         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
2560                 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
2561         return *p;
2562 }
2563
2564 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
2565 {
2566         u32 *p = &vmx->segment_cache.seg[seg].limit;
2567
2568         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
2569                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
2570         return *p;
2571 }
2572
2573 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
2574 {
2575         u32 *p = &vmx->segment_cache.seg[seg].ar;
2576
2577         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
2578                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
2579         return *p;
2580 }
2581
2582 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
2583 {
2584         u32 eb;
2585
2586         eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
2587              (1u << DB_VECTOR) | (1u << AC_VECTOR);
2588         /*
2589          * Guest access to VMware backdoor ports could legitimately
2590          * trigger #GP because of TSS I/O permission bitmap.
2591          * We intercept those #GP and allow access to them anyway
2592          * as VMware does.
2593          */
2594         if (enable_vmware_backdoor)
2595                 eb |= (1u << GP_VECTOR);
2596         if ((vcpu->guest_debug &
2597              (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
2598             (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
2599                 eb |= 1u << BP_VECTOR;
2600         if (to_vmx(vcpu)->rmode.vm86_active)
2601                 eb = ~0;
2602         if (enable_ept)
2603                 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
2604
2605         /* When we are running a nested L2 guest and L1 specified for it a
2606          * certain exception bitmap, we must trap the same exceptions and pass
2607          * them to L1. When running L2, we will only handle the exceptions
2608          * specified above if L1 did not want them.
2609          */
2610         if (is_guest_mode(vcpu))
2611                 eb |= get_vmcs12(vcpu)->exception_bitmap;
2612
2613         vmcs_write32(EXCEPTION_BITMAP, eb);
2614 }
2615
2616 /*
2617  * Check if MSR is intercepted for currently loaded MSR bitmap.
2618  */
2619 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
2620 {
2621         unsigned long *msr_bitmap;
2622         int f = sizeof(unsigned long);
2623
2624         if (!cpu_has_vmx_msr_bitmap())
2625                 return true;
2626
2627         msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
2628
2629         if (msr <= 0x1fff) {
2630                 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2631         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2632                 msr &= 0x1fff;
2633                 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2634         }
2635
2636         return true;
2637 }
2638
2639 /*
2640  * Check if MSR is intercepted for L01 MSR bitmap.
2641  */
2642 static bool msr_write_intercepted_l01(struct kvm_vcpu *vcpu, u32 msr)
2643 {
2644         unsigned long *msr_bitmap;
2645         int f = sizeof(unsigned long);
2646
2647         if (!cpu_has_vmx_msr_bitmap())
2648                 return true;
2649
2650         msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
2651
2652         if (msr <= 0x1fff) {
2653                 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2654         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2655                 msr &= 0x1fff;
2656                 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2657         }
2658
2659         return true;
2660 }
2661
2662 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2663                 unsigned long entry, unsigned long exit)
2664 {
2665         vm_entry_controls_clearbit(vmx, entry);
2666         vm_exit_controls_clearbit(vmx, exit);
2667 }
2668
2669 static int find_msr(struct vmx_msrs *m, unsigned int msr)
2670 {
2671         unsigned int i;
2672
2673         for (i = 0; i < m->nr; ++i) {
2674                 if (m->val[i].index == msr)
2675                         return i;
2676         }
2677         return -ENOENT;
2678 }
2679
2680 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
2681 {
2682         int i;
2683         struct msr_autoload *m = &vmx->msr_autoload;
2684
2685         switch (msr) {
2686         case MSR_EFER:
2687                 if (cpu_has_load_ia32_efer) {
2688                         clear_atomic_switch_msr_special(vmx,
2689                                         VM_ENTRY_LOAD_IA32_EFER,
2690                                         VM_EXIT_LOAD_IA32_EFER);
2691                         return;
2692                 }
2693                 break;
2694         case MSR_CORE_PERF_GLOBAL_CTRL:
2695                 if (cpu_has_load_perf_global_ctrl) {
2696                         clear_atomic_switch_msr_special(vmx,
2697                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2698                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
2699                         return;
2700                 }
2701                 break;
2702         }
2703         i = find_msr(&m->guest, msr);
2704         if (i < 0)
2705                 goto skip_guest;
2706         --m->guest.nr;
2707         m->guest.val[i] = m->guest.val[m->guest.nr];
2708         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2709
2710 skip_guest:
2711         i = find_msr(&m->host, msr);
2712         if (i < 0)
2713                 return;
2714
2715         --m->host.nr;
2716         m->host.val[i] = m->host.val[m->host.nr];
2717         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2718 }
2719
2720 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2721                 unsigned long entry, unsigned long exit,
2722                 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
2723                 u64 guest_val, u64 host_val)
2724 {
2725         vmcs_write64(guest_val_vmcs, guest_val);
2726         if (host_val_vmcs != HOST_IA32_EFER)
2727                 vmcs_write64(host_val_vmcs, host_val);
2728         vm_entry_controls_setbit(vmx, entry);
2729         vm_exit_controls_setbit(vmx, exit);
2730 }
2731
2732 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
2733                                   u64 guest_val, u64 host_val, bool entry_only)
2734 {
2735         int i, j = 0;
2736         struct msr_autoload *m = &vmx->msr_autoload;
2737
2738         switch (msr) {
2739         case MSR_EFER:
2740                 if (cpu_has_load_ia32_efer) {
2741                         add_atomic_switch_msr_special(vmx,
2742                                         VM_ENTRY_LOAD_IA32_EFER,
2743                                         VM_EXIT_LOAD_IA32_EFER,
2744                                         GUEST_IA32_EFER,
2745                                         HOST_IA32_EFER,
2746                                         guest_val, host_val);
2747                         return;
2748                 }
2749                 break;
2750         case MSR_CORE_PERF_GLOBAL_CTRL:
2751                 if (cpu_has_load_perf_global_ctrl) {
2752                         add_atomic_switch_msr_special(vmx,
2753                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2754                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
2755                                         GUEST_IA32_PERF_GLOBAL_CTRL,
2756                                         HOST_IA32_PERF_GLOBAL_CTRL,
2757                                         guest_val, host_val);
2758                         return;
2759                 }
2760                 break;
2761         case MSR_IA32_PEBS_ENABLE:
2762                 /* PEBS needs a quiescent period after being disabled (to write
2763                  * a record).  Disabling PEBS through VMX MSR swapping doesn't
2764                  * provide that period, so a CPU could write host's record into
2765                  * guest's memory.
2766                  */
2767                 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
2768         }
2769
2770         i = find_msr(&m->guest, msr);
2771         if (!entry_only)
2772                 j = find_msr(&m->host, msr);
2773
2774         if (i == NR_AUTOLOAD_MSRS || j == NR_AUTOLOAD_MSRS) {
2775                 printk_once(KERN_WARNING "Not enough msr switch entries. "
2776                                 "Can't add msr %x\n", msr);
2777                 return;
2778         }
2779         if (i < 0) {
2780                 i = m->guest.nr++;
2781                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2782         }
2783         m->guest.val[i].index = msr;
2784         m->guest.val[i].value = guest_val;
2785
2786         if (entry_only)
2787                 return;
2788
2789         if (j < 0) {
2790                 j = m->host.nr++;
2791                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2792         }
2793         m->host.val[j].index = msr;
2794         m->host.val[j].value = host_val;
2795 }
2796
2797 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
2798 {
2799         u64 guest_efer = vmx->vcpu.arch.efer;
2800         u64 ignore_bits = 0;
2801
2802         if (!enable_ept) {
2803                 /*
2804                  * NX is needed to handle CR0.WP=1, CR4.SMEP=1.  Testing
2805                  * host CPUID is more efficient than testing guest CPUID
2806                  * or CR4.  Host SMEP is anyway a requirement for guest SMEP.
2807                  */
2808                 if (boot_cpu_has(X86_FEATURE_SMEP))
2809                         guest_efer |= EFER_NX;
2810                 else if (!(guest_efer & EFER_NX))
2811                         ignore_bits |= EFER_NX;
2812         }
2813
2814         /*
2815          * LMA and LME handled by hardware; SCE meaningless outside long mode.
2816          */
2817         ignore_bits |= EFER_SCE;
2818 #ifdef CONFIG_X86_64
2819         ignore_bits |= EFER_LMA | EFER_LME;
2820         /* SCE is meaningful only in long mode on Intel */
2821         if (guest_efer & EFER_LMA)
2822                 ignore_bits &= ~(u64)EFER_SCE;
2823 #endif
2824
2825         /*
2826          * On EPT, we can't emulate NX, so we must switch EFER atomically.
2827          * On CPUs that support "load IA32_EFER", always switch EFER
2828          * atomically, since it's faster than switching it manually.
2829          */
2830         if (cpu_has_load_ia32_efer ||
2831             (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
2832                 if (!(guest_efer & EFER_LMA))
2833                         guest_efer &= ~EFER_LME;
2834                 if (guest_efer != host_efer)
2835                         add_atomic_switch_msr(vmx, MSR_EFER,
2836                                               guest_efer, host_efer, false);
2837                 else
2838                         clear_atomic_switch_msr(vmx, MSR_EFER);
2839                 return false;
2840         } else {
2841                 clear_atomic_switch_msr(vmx, MSR_EFER);
2842
2843                 guest_efer &= ~ignore_bits;
2844                 guest_efer |= host_efer & ignore_bits;
2845
2846                 vmx->guest_msrs[efer_offset].data = guest_efer;
2847                 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
2848
2849                 return true;
2850         }
2851 }
2852
2853 #ifdef CONFIG_X86_32
2854 /*
2855  * On 32-bit kernels, VM exits still load the FS and GS bases from the
2856  * VMCS rather than the segment table.  KVM uses this helper to figure
2857  * out the current bases to poke them into the VMCS before entry.
2858  */
2859 static unsigned long segment_base(u16 selector)
2860 {
2861         struct desc_struct *table;
2862         unsigned long v;
2863
2864         if (!(selector & ~SEGMENT_RPL_MASK))
2865                 return 0;
2866
2867         table = get_current_gdt_ro();
2868
2869         if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
2870                 u16 ldt_selector = kvm_read_ldt();
2871
2872                 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
2873                         return 0;
2874
2875                 table = (struct desc_struct *)segment_base(ldt_selector);
2876         }
2877         v = get_desc_base(&table[selector >> 3]);
2878         return v;
2879 }
2880 #endif
2881
2882 static void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
2883 {
2884         struct vcpu_vmx *vmx = to_vmx(vcpu);
2885         struct vmcs_host_state *host_state;
2886 #ifdef CONFIG_X86_64
2887         int cpu = raw_smp_processor_id();
2888 #endif
2889         unsigned long fs_base, gs_base;
2890         u16 fs_sel, gs_sel;
2891         int i;
2892
2893         vmx->req_immediate_exit = false;
2894
2895         if (vmx->loaded_cpu_state)
2896                 return;
2897
2898         vmx->loaded_cpu_state = vmx->loaded_vmcs;
2899         host_state = &vmx->loaded_cpu_state->host_state;
2900
2901         /*
2902          * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
2903          * allow segment selectors with cpl > 0 or ti == 1.
2904          */
2905         host_state->ldt_sel = kvm_read_ldt();
2906
2907 #ifdef CONFIG_X86_64
2908         savesegment(ds, host_state->ds_sel);
2909         savesegment(es, host_state->es_sel);
2910
2911         gs_base = cpu_kernelmode_gs_base(cpu);
2912         if (likely(is_64bit_mm(current->mm))) {
2913                 save_fsgs_for_kvm();
2914                 fs_sel = current->thread.fsindex;
2915                 gs_sel = current->thread.gsindex;
2916                 fs_base = current->thread.fsbase;
2917                 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
2918         } else {
2919                 savesegment(fs, fs_sel);
2920                 savesegment(gs, gs_sel);
2921                 fs_base = read_msr(MSR_FS_BASE);
2922                 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
2923         }
2924
2925         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2926 #else
2927         savesegment(fs, fs_sel);
2928         savesegment(gs, gs_sel);
2929         fs_base = segment_base(fs_sel);
2930         gs_base = segment_base(gs_sel);
2931 #endif
2932
2933         if (unlikely(fs_sel != host_state->fs_sel)) {
2934                 if (!(fs_sel & 7))
2935                         vmcs_write16(HOST_FS_SELECTOR, fs_sel);
2936                 else
2937                         vmcs_write16(HOST_FS_SELECTOR, 0);
2938                 host_state->fs_sel = fs_sel;
2939         }
2940         if (unlikely(gs_sel != host_state->gs_sel)) {
2941                 if (!(gs_sel & 7))
2942                         vmcs_write16(HOST_GS_SELECTOR, gs_sel);
2943                 else
2944                         vmcs_write16(HOST_GS_SELECTOR, 0);
2945                 host_state->gs_sel = gs_sel;
2946         }
2947         if (unlikely(fs_base != host_state->fs_base)) {
2948                 vmcs_writel(HOST_FS_BASE, fs_base);
2949                 host_state->fs_base = fs_base;
2950         }
2951         if (unlikely(gs_base != host_state->gs_base)) {
2952                 vmcs_writel(HOST_GS_BASE, gs_base);
2953                 host_state->gs_base = gs_base;
2954         }
2955
2956         for (i = 0; i < vmx->save_nmsrs; ++i)
2957                 kvm_set_shared_msr(vmx->guest_msrs[i].index,
2958                                    vmx->guest_msrs[i].data,
2959                                    vmx->guest_msrs[i].mask);
2960 }
2961
2962 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
2963 {
2964         struct vmcs_host_state *host_state;
2965
2966         if (!vmx->loaded_cpu_state)
2967                 return;
2968
2969         WARN_ON_ONCE(vmx->loaded_cpu_state != vmx->loaded_vmcs);
2970         host_state = &vmx->loaded_cpu_state->host_state;
2971
2972         ++vmx->vcpu.stat.host_state_reload;
2973         vmx->loaded_cpu_state = NULL;
2974
2975 #ifdef CONFIG_X86_64
2976         rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2977 #endif
2978         if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
2979                 kvm_load_ldt(host_state->ldt_sel);
2980 #ifdef CONFIG_X86_64
2981                 load_gs_index(host_state->gs_sel);
2982 #else
2983                 loadsegment(gs, host_state->gs_sel);
2984 #endif
2985         }
2986         if (host_state->fs_sel & 7)
2987                 loadsegment(fs, host_state->fs_sel);
2988 #ifdef CONFIG_X86_64
2989         if (unlikely(host_state->ds_sel | host_state->es_sel)) {
2990                 loadsegment(ds, host_state->ds_sel);
2991                 loadsegment(es, host_state->es_sel);
2992         }
2993 #endif
2994         invalidate_tss_limit();
2995 #ifdef CONFIG_X86_64
2996         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2997 #endif
2998         load_fixmap_gdt(raw_smp_processor_id());
2999 }
3000
3001 #ifdef CONFIG_X86_64
3002 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
3003 {
3004         preempt_disable();
3005         if (vmx->loaded_cpu_state)
3006                 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
3007         preempt_enable();
3008         return vmx->msr_guest_kernel_gs_base;
3009 }
3010
3011 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
3012 {
3013         preempt_disable();
3014         if (vmx->loaded_cpu_state)
3015                 wrmsrl(MSR_KERNEL_GS_BASE, data);
3016         preempt_enable();
3017         vmx->msr_guest_kernel_gs_base = data;
3018 }
3019 #endif
3020
3021 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
3022 {
3023         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
3024         struct pi_desc old, new;
3025         unsigned int dest;
3026
3027         /*
3028          * In case of hot-plug or hot-unplug, we may have to undo
3029          * vmx_vcpu_pi_put even if there is no assigned device.  And we
3030          * always keep PI.NDST up to date for simplicity: it makes the
3031          * code easier, and CPU migration is not a fast path.
3032          */
3033         if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
3034                 return;
3035
3036         /*
3037          * First handle the simple case where no cmpxchg is necessary; just
3038          * allow posting non-urgent interrupts.
3039          *
3040          * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
3041          * PI.NDST: pi_post_block will do it for us and the wakeup_handler
3042          * expects the VCPU to be on the blocked_vcpu_list that matches
3043          * PI.NDST.
3044          */
3045         if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR ||
3046             vcpu->cpu == cpu) {
3047                 pi_clear_sn(pi_desc);
3048                 return;
3049         }
3050
3051         /* The full case.  */
3052         do {
3053                 old.control = new.control = pi_desc->control;
3054
3055                 dest = cpu_physical_id(cpu);
3056
3057                 if (x2apic_enabled())
3058                         new.ndst = dest;
3059                 else
3060                         new.ndst = (dest << 8) & 0xFF00;
3061
3062                 new.sn = 0;
3063         } while (cmpxchg64(&pi_desc->control, old.control,
3064                            new.control) != old.control);
3065 }
3066
3067 static void decache_tsc_multiplier(struct vcpu_vmx *vmx)
3068 {
3069         vmx->current_tsc_ratio = vmx->vcpu.arch.tsc_scaling_ratio;
3070         vmcs_write64(TSC_MULTIPLIER, vmx->current_tsc_ratio);
3071 }
3072
3073 /*
3074  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
3075  * vcpu mutex is already taken.
3076  */
3077 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3078 {
3079         struct vcpu_vmx *vmx = to_vmx(vcpu);
3080         bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
3081
3082         if (!already_loaded) {
3083                 loaded_vmcs_clear(vmx->loaded_vmcs);
3084                 local_irq_disable();
3085                 crash_disable_local_vmclear(cpu);
3086
3087                 /*
3088                  * Read loaded_vmcs->cpu should be before fetching
3089                  * loaded_vmcs->loaded_vmcss_on_cpu_link.
3090                  * See the comments in __loaded_vmcs_clear().
3091                  */
3092                 smp_rmb();
3093
3094                 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
3095                          &per_cpu(loaded_vmcss_on_cpu, cpu));
3096                 crash_enable_local_vmclear(cpu);
3097                 local_irq_enable();
3098         }
3099
3100         if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
3101                 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
3102                 vmcs_load(vmx->loaded_vmcs->vmcs);
3103                 indirect_branch_prediction_barrier();
3104         }
3105
3106         if (!already_loaded) {
3107                 void *gdt = get_current_gdt_ro();
3108                 unsigned long sysenter_esp;
3109
3110                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3111
3112                 /*
3113                  * Linux uses per-cpu TSS and GDT, so set these when switching
3114                  * processors.  See 22.2.4.
3115                  */
3116                 vmcs_writel(HOST_TR_BASE,
3117                             (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
3118                 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt);   /* 22.2.4 */
3119
3120                 /*
3121                  * VM exits change the host TR limit to 0x67 after a VM
3122                  * exit.  This is okay, since 0x67 covers everything except
3123                  * the IO bitmap and have have code to handle the IO bitmap
3124                  * being lost after a VM exit.
3125                  */
3126                 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
3127
3128                 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
3129                 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
3130
3131                 vmx->loaded_vmcs->cpu = cpu;
3132         }
3133
3134         /* Setup TSC multiplier */
3135         if (kvm_has_tsc_control &&
3136             vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
3137                 decache_tsc_multiplier(vmx);
3138
3139         vmx_vcpu_pi_load(vcpu, cpu);
3140         vmx->host_pkru = read_pkru();
3141         vmx->host_debugctlmsr = get_debugctlmsr();
3142 }
3143
3144 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
3145 {
3146         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
3147
3148         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
3149                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
3150                 !kvm_vcpu_apicv_active(vcpu))
3151                 return;
3152
3153         /* Set SN when the vCPU is preempted */
3154         if (vcpu->preempted)
3155                 pi_set_sn(pi_desc);
3156 }
3157
3158 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
3159 {
3160         vmx_vcpu_pi_put(vcpu);
3161
3162         vmx_prepare_switch_to_host(to_vmx(vcpu));
3163 }
3164
3165 static bool emulation_required(struct kvm_vcpu *vcpu)
3166 {
3167         return emulate_invalid_guest_state && !guest_state_valid(vcpu);
3168 }
3169
3170 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
3171
3172 /*
3173  * Return the cr0 value that a nested guest would read. This is a combination
3174  * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
3175  * its hypervisor (cr0_read_shadow).
3176  */
3177 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
3178 {
3179         return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
3180                 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
3181 }
3182 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
3183 {
3184         return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
3185                 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
3186 }
3187
3188 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
3189 {
3190         unsigned long rflags, save_rflags;
3191
3192         if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
3193                 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
3194                 rflags = vmcs_readl(GUEST_RFLAGS);
3195                 if (to_vmx(vcpu)->rmode.vm86_active) {
3196                         rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
3197                         save_rflags = to_vmx(vcpu)->rmode.save_rflags;
3198                         rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
3199                 }
3200                 to_vmx(vcpu)->rflags = rflags;
3201         }
3202         return to_vmx(vcpu)->rflags;
3203 }
3204
3205 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
3206 {
3207         unsigned long old_rflags = vmx_get_rflags(vcpu);
3208
3209         __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
3210         to_vmx(vcpu)->rflags = rflags;
3211         if (to_vmx(vcpu)->rmode.vm86_active) {
3212                 to_vmx(vcpu)->rmode.save_rflags = rflags;
3213                 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
3214         }
3215         vmcs_writel(GUEST_RFLAGS, rflags);
3216
3217         if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
3218                 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
3219 }
3220
3221 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
3222 {
3223         u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
3224         int ret = 0;
3225
3226         if (interruptibility & GUEST_INTR_STATE_STI)
3227                 ret |= KVM_X86_SHADOW_INT_STI;
3228         if (interruptibility & GUEST_INTR_STATE_MOV_SS)
3229                 ret |= KVM_X86_SHADOW_INT_MOV_SS;
3230
3231         return ret;
3232 }
3233
3234 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
3235 {
3236         u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
3237         u32 interruptibility = interruptibility_old;
3238
3239         interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
3240
3241         if (mask & KVM_X86_SHADOW_INT_MOV_SS)
3242                 interruptibility |= GUEST_INTR_STATE_MOV_SS;
3243         else if (mask & KVM_X86_SHADOW_INT_STI)
3244                 interruptibility |= GUEST_INTR_STATE_STI;
3245
3246         if ((interruptibility != interruptibility_old))
3247                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
3248 }
3249
3250 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
3251 {
3252         unsigned long rip;
3253
3254         rip = kvm_rip_read(vcpu);
3255         rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
3256         kvm_rip_write(vcpu, rip);
3257
3258         /* skipping an emulated instruction also counts */
3259         vmx_set_interrupt_shadow(vcpu, 0);
3260 }
3261
3262 static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
3263                                                unsigned long exit_qual)
3264 {
3265         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3266         unsigned int nr = vcpu->arch.exception.nr;
3267         u32 intr_info = nr | INTR_INFO_VALID_MASK;
3268
3269         if (vcpu->arch.exception.has_error_code) {
3270                 vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code;
3271                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
3272         }
3273
3274         if (kvm_exception_is_soft(nr))
3275                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
3276         else
3277                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
3278
3279         if (!(vmcs12->idt_vectoring_info_field & VECTORING_INFO_VALID_MASK) &&
3280             vmx_get_nmi_mask(vcpu))
3281                 intr_info |= INTR_INFO_UNBLOCK_NMI;
3282
3283         nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI, intr_info, exit_qual);
3284 }
3285
3286 /*
3287  * KVM wants to inject page-faults which it got to the guest. This function
3288  * checks whether in a nested guest, we need to inject them to L1 or L2.
3289  */
3290 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned long *exit_qual)
3291 {
3292         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3293         unsigned int nr = vcpu->arch.exception.nr;
3294
3295         if (nr == PF_VECTOR) {
3296                 if (vcpu->arch.exception.nested_apf) {
3297                         *exit_qual = vcpu->arch.apf.nested_apf_token;
3298                         return 1;
3299                 }
3300                 /*
3301                  * FIXME: we must not write CR2 when L1 intercepts an L2 #PF exception.
3302                  * The fix is to add the ancillary datum (CR2 or DR6) to structs
3303                  * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6
3304                  * can be written only when inject_pending_event runs.  This should be
3305                  * conditional on a new capability---if the capability is disabled,
3306                  * kvm_multiple_exception would write the ancillary information to
3307                  * CR2 or DR6, for backwards ABI-compatibility.
3308                  */
3309                 if (nested_vmx_is_page_fault_vmexit(vmcs12,
3310                                                     vcpu->arch.exception.error_code)) {
3311                         *exit_qual = vcpu->arch.cr2;
3312                         return 1;
3313                 }
3314         } else {
3315                 if (vmcs12->exception_bitmap & (1u << nr)) {
3316                         if (nr == DB_VECTOR) {
3317                                 *exit_qual = vcpu->arch.dr6;
3318                                 *exit_qual &= ~(DR6_FIXED_1 | DR6_BT);
3319                                 *exit_qual ^= DR6_RTM;
3320                         } else {
3321                                 *exit_qual = 0;
3322                         }
3323                         return 1;
3324                 }
3325         }
3326
3327         return 0;
3328 }
3329
3330 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
3331 {
3332         /*
3333          * Ensure that we clear the HLT state in the VMCS.  We don't need to
3334          * explicitly skip the instruction because if the HLT state is set,
3335          * then the instruction is already executing and RIP has already been
3336          * advanced.
3337          */
3338         if (kvm_hlt_in_guest(vcpu->kvm) &&
3339                         vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
3340                 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
3341 }
3342
3343 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
3344 {
3345         struct vcpu_vmx *vmx = to_vmx(vcpu);
3346         unsigned nr = vcpu->arch.exception.nr;
3347         bool has_error_code = vcpu->arch.exception.has_error_code;
3348         u32 error_code = vcpu->arch.exception.error_code;
3349         u32 intr_info = nr | INTR_INFO_VALID_MASK;
3350
3351         if (has_error_code) {
3352                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
3353                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
3354         }
3355
3356         if (vmx->rmode.vm86_active) {
3357                 int inc_eip = 0;
3358                 if (kvm_exception_is_soft(nr))
3359                         inc_eip = vcpu->arch.event_exit_inst_len;
3360                 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
3361                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3362                 return;
3363         }
3364
3365         WARN_ON_ONCE(vmx->emulation_required);
3366
3367         if (kvm_exception_is_soft(nr)) {
3368                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
3369                              vmx->vcpu.arch.event_exit_inst_len);
3370                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
3371         } else
3372                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
3373
3374         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
3375
3376         vmx_clear_hlt(vcpu);
3377 }
3378
3379 static bool vmx_rdtscp_supported(void)
3380 {
3381         return cpu_has_vmx_rdtscp();
3382 }
3383
3384 static bool vmx_invpcid_supported(void)
3385 {
3386         return cpu_has_vmx_invpcid();
3387 }
3388
3389 /*
3390  * Swap MSR entry in host/guest MSR entry array.
3391  */
3392 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
3393 {
3394         struct shared_msr_entry tmp;
3395
3396         tmp = vmx->guest_msrs[to];
3397         vmx->guest_msrs[to] = vmx->guest_msrs[from];
3398         vmx->guest_msrs[from] = tmp;
3399 }
3400
3401 /*
3402  * Set up the vmcs to automatically save and restore system
3403  * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
3404  * mode, as fiddling with msrs is very expensive.
3405  */
3406 static void setup_msrs(struct vcpu_vmx *vmx)
3407 {
3408         int save_nmsrs, index;
3409
3410         save_nmsrs = 0;
3411 #ifdef CONFIG_X86_64
3412         if (is_long_mode(&vmx->vcpu)) {
3413                 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
3414                 if (index >= 0)
3415                         move_msr_up(vmx, index, save_nmsrs++);
3416                 index = __find_msr_index(vmx, MSR_LSTAR);
3417                 if (index >= 0)
3418                         move_msr_up(vmx, index, save_nmsrs++);
3419                 index = __find_msr_index(vmx, MSR_CSTAR);
3420                 if (index >= 0)
3421                         move_msr_up(vmx, index, save_nmsrs++);
3422                 index = __find_msr_index(vmx, MSR_TSC_AUX);
3423                 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
3424                         move_msr_up(vmx, index, save_nmsrs++);
3425                 /*
3426                  * MSR_STAR is only needed on long mode guests, and only
3427                  * if efer.sce is enabled.
3428                  */
3429                 index = __find_msr_index(vmx, MSR_STAR);
3430                 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
3431                         move_msr_up(vmx, index, save_nmsrs++);
3432         }
3433 #endif
3434         index = __find_msr_index(vmx, MSR_EFER);
3435         if (index >= 0 && update_transition_efer(vmx, index))
3436                 move_msr_up(vmx, index, save_nmsrs++);
3437
3438         vmx->save_nmsrs = save_nmsrs;
3439
3440         if (cpu_has_vmx_msr_bitmap())
3441                 vmx_update_msr_bitmap(&vmx->vcpu);
3442 }
3443
3444 static u64 vmx_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
3445 {
3446         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3447
3448         if (is_guest_mode(vcpu) &&
3449             (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
3450                 return vcpu->arch.tsc_offset - vmcs12->tsc_offset;
3451
3452         return vcpu->arch.tsc_offset;
3453 }
3454
3455 /*
3456  * writes 'offset' into guest's timestamp counter offset register
3457  */
3458 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
3459 {
3460         if (is_guest_mode(vcpu)) {
3461                 /*
3462                  * We're here if L1 chose not to trap WRMSR to TSC. According
3463                  * to the spec, this should set L1's TSC; The offset that L1
3464                  * set for L2 remains unchanged, and still needs to be added
3465                  * to the newly set TSC to get L2's TSC.
3466                  */
3467                 struct vmcs12 *vmcs12;
3468                 /* recalculate vmcs02.TSC_OFFSET: */
3469                 vmcs12 = get_vmcs12(vcpu);
3470                 vmcs_write64(TSC_OFFSET, offset +
3471                         (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
3472                          vmcs12->tsc_offset : 0));
3473         } else {
3474                 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
3475                                            vmcs_read64(TSC_OFFSET), offset);
3476                 vmcs_write64(TSC_OFFSET, offset);
3477         }
3478 }
3479
3480 /*
3481  * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
3482  * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
3483  * all guests if the "nested" module option is off, and can also be disabled
3484  * for a single guest by disabling its VMX cpuid bit.
3485  */
3486 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
3487 {
3488         return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
3489 }
3490
3491 /*
3492  * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
3493  * returned for the various VMX controls MSRs when nested VMX is enabled.
3494  * The same values should also be used to verify that vmcs12 control fields are
3495  * valid during nested entry from L1 to L2.
3496  * Each of these control msrs has a low and high 32-bit half: A low bit is on
3497  * if the corresponding bit in the (32-bit) control field *must* be on, and a
3498  * bit in the high half is on if the corresponding bit in the control field
3499  * may be on. See also vmx_control_verify().
3500  */
3501 static void nested_vmx_setup_ctls_msrs(struct nested_vmx_msrs *msrs, bool apicv)
3502 {
3503         if (!nested) {
3504                 memset(msrs, 0, sizeof(*msrs));
3505                 return;
3506         }
3507
3508         /*
3509          * Note that as a general rule, the high half of the MSRs (bits in
3510          * the control fields which may be 1) should be initialized by the
3511          * intersection of the underlying hardware's MSR (i.e., features which
3512          * can be supported) and the list of features we want to expose -
3513          * because they are known to be properly supported in our code.
3514          * Also, usually, the low half of the MSRs (bits which must be 1) can
3515          * be set to 0, meaning that L1 may turn off any of these bits. The
3516          * reason is that if one of these bits is necessary, it will appear
3517          * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
3518          * fields of vmcs01 and vmcs02, will turn these bits off - and
3519          * nested_vmx_exit_reflected() will not pass related exits to L1.
3520          * These rules have exceptions below.
3521          */
3522
3523         /* pin-based controls */
3524         rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
3525                 msrs->pinbased_ctls_low,
3526                 msrs->pinbased_ctls_high);
3527         msrs->pinbased_ctls_low |=
3528                 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3529         msrs->pinbased_ctls_high &=
3530                 PIN_BASED_EXT_INTR_MASK |
3531                 PIN_BASED_NMI_EXITING |
3532                 PIN_BASED_VIRTUAL_NMIS |
3533                 (apicv ? PIN_BASED_POSTED_INTR : 0);
3534         msrs->pinbased_ctls_high |=
3535                 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
3536                 PIN_BASED_VMX_PREEMPTION_TIMER;
3537
3538         /* exit controls */
3539         rdmsr(MSR_IA32_VMX_EXIT_CTLS,
3540                 msrs->exit_ctls_low,
3541                 msrs->exit_ctls_high);
3542         msrs->exit_ctls_low =
3543                 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
3544
3545         msrs->exit_ctls_high &=
3546 #ifdef CONFIG_X86_64
3547                 VM_EXIT_HOST_ADDR_SPACE_SIZE |
3548 #endif
3549                 VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
3550         msrs->exit_ctls_high |=
3551                 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
3552                 VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
3553                 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
3554
3555         /* We support free control of debug control saving. */
3556         msrs->exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
3557
3558         /* entry controls */
3559         rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
3560                 msrs->entry_ctls_low,
3561                 msrs->entry_ctls_high);
3562         msrs->entry_ctls_low =
3563                 VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
3564         msrs->entry_ctls_high &=
3565 #ifdef CONFIG_X86_64
3566                 VM_ENTRY_IA32E_MODE |
3567 #endif
3568                 VM_ENTRY_LOAD_IA32_PAT;
3569         msrs->entry_ctls_high |=
3570                 (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
3571
3572         /* We support free control of debug control loading. */
3573         msrs->entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
3574
3575         /* cpu-based controls */
3576         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
3577                 msrs->procbased_ctls_low,
3578                 msrs->procbased_ctls_high);
3579         msrs->procbased_ctls_low =
3580                 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3581         msrs->procbased_ctls_high &=
3582                 CPU_BASED_VIRTUAL_INTR_PENDING |
3583                 CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
3584                 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
3585                 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
3586                 CPU_BASED_CR3_STORE_EXITING |
3587 #ifdef CONFIG_X86_64
3588                 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
3589 #endif
3590                 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
3591                 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
3592                 CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
3593                 CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
3594                 CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
3595         /*
3596          * We can allow some features even when not supported by the
3597          * hardware. For example, L1 can specify an MSR bitmap - and we
3598          * can use it to avoid exits to L1 - even when L0 runs L2
3599          * without MSR bitmaps.
3600          */
3601         msrs->procbased_ctls_high |=
3602                 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
3603                 CPU_BASED_USE_MSR_BITMAPS;
3604
3605         /* We support free control of CR3 access interception. */
3606         msrs->procbased_ctls_low &=
3607                 ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
3608
3609         /*
3610          * secondary cpu-based controls.  Do not include those that
3611          * depend on CPUID bits, they are added later by vmx_cpuid_update.
3612          */
3613         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
3614                 msrs->secondary_ctls_low,
3615                 msrs->secondary_ctls_high);
3616         msrs->secondary_ctls_low = 0;
3617         msrs->secondary_ctls_high &=
3618                 SECONDARY_EXEC_DESC |
3619                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3620                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3621                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
3622                 SECONDARY_EXEC_WBINVD_EXITING;
3623
3624         /*
3625          * We can emulate "VMCS shadowing," even if the hardware
3626          * doesn't support it.
3627          */
3628         msrs->secondary_ctls_high |=
3629                 SECONDARY_EXEC_SHADOW_VMCS;
3630
3631         if (enable_ept) {
3632                 /* nested EPT: emulate EPT also to L1 */
3633                 msrs->secondary_ctls_high |=
3634                         SECONDARY_EXEC_ENABLE_EPT;
3635                 msrs->ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
3636                          VMX_EPTP_WB_BIT | VMX_EPT_INVEPT_BIT;
3637                 if (cpu_has_vmx_ept_execute_only())
3638                         msrs->ept_caps |=
3639                                 VMX_EPT_EXECUTE_ONLY_BIT;
3640                 msrs->ept_caps &= vmx_capability.ept;
3641                 msrs->ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
3642                         VMX_EPT_EXTENT_CONTEXT_BIT | VMX_EPT_2MB_PAGE_BIT |
3643                         VMX_EPT_1GB_PAGE_BIT;
3644                 if (enable_ept_ad_bits) {
3645                         msrs->secondary_ctls_high |=
3646                                 SECONDARY_EXEC_ENABLE_PML;
3647                         msrs->ept_caps |= VMX_EPT_AD_BIT;
3648                 }
3649         }
3650
3651         if (cpu_has_vmx_vmfunc()) {
3652                 msrs->secondary_ctls_high |=
3653                         SECONDARY_EXEC_ENABLE_VMFUNC;
3654                 /*
3655                  * Advertise EPTP switching unconditionally
3656                  * since we emulate it
3657                  */
3658                 if (enable_ept)
3659                         msrs->vmfunc_controls =
3660                                 VMX_VMFUNC_EPTP_SWITCHING;
3661         }
3662
3663         /*
3664          * Old versions of KVM use the single-context version without
3665          * checking for support, so declare that it is supported even
3666          * though it is treated as global context.  The alternative is
3667          * not failing the single-context invvpid, and it is worse.
3668          */
3669         if (enable_vpid) {
3670                 msrs->secondary_ctls_high |=
3671                         SECONDARY_EXEC_ENABLE_VPID;
3672                 msrs->vpid_caps = VMX_VPID_INVVPID_BIT |
3673                         VMX_VPID_EXTENT_SUPPORTED_MASK;
3674         }
3675
3676         if (enable_unrestricted_guest)
3677                 msrs->secondary_ctls_high |=
3678                         SECONDARY_EXEC_UNRESTRICTED_GUEST;
3679
3680         if (flexpriority_enabled)
3681                 msrs->secondary_ctls_high |=
3682                         SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
3683
3684         /* miscellaneous data */
3685         rdmsr(MSR_IA32_VMX_MISC,
3686                 msrs->misc_low,
3687                 msrs->misc_high);
3688         msrs->misc_low &= VMX_MISC_SAVE_EFER_LMA;
3689         msrs->misc_low |=
3690                 MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS |
3691                 VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
3692                 VMX_MISC_ACTIVITY_HLT;
3693         msrs->misc_high = 0;
3694
3695         /*
3696          * This MSR reports some information about VMX support. We
3697          * should return information about the VMX we emulate for the
3698          * guest, and the VMCS structure we give it - not about the
3699          * VMX support of the underlying hardware.
3700          */
3701         msrs->basic =
3702                 VMCS12_REVISION |
3703                 VMX_BASIC_TRUE_CTLS |
3704                 ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
3705                 (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
3706
3707         if (cpu_has_vmx_basic_inout())
3708                 msrs->basic |= VMX_BASIC_INOUT;
3709
3710         /*
3711          * These MSRs specify bits which the guest must keep fixed on
3712          * while L1 is in VMXON mode (in L1's root mode, or running an L2).
3713          * We picked the standard core2 setting.
3714          */
3715 #define VMXON_CR0_ALWAYSON     (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
3716 #define VMXON_CR4_ALWAYSON     X86_CR4_VMXE
3717         msrs->cr0_fixed0 = VMXON_CR0_ALWAYSON;
3718         msrs->cr4_fixed0 = VMXON_CR4_ALWAYSON;
3719
3720         /* These MSRs specify bits which the guest must keep fixed off. */
3721         rdmsrl(MSR_IA32_VMX_CR0_FIXED1, msrs->cr0_fixed1);
3722         rdmsrl(MSR_IA32_VMX_CR4_FIXED1, msrs->cr4_fixed1);
3723
3724         /* highest index: VMX_PREEMPTION_TIMER_VALUE */
3725         msrs->vmcs_enum = VMCS12_MAX_FIELD_INDEX << 1;
3726 }
3727
3728 /*
3729  * if fixed0[i] == 1: val[i] must be 1
3730  * if fixed1[i] == 0: val[i] must be 0
3731  */
3732 static inline bool fixed_bits_valid(u64 val, u64 fixed0, u64 fixed1)
3733 {
3734         return ((val & fixed1) | fixed0) == val;
3735 }
3736
3737 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
3738 {
3739         return fixed_bits_valid(control, low, high);
3740 }
3741
3742 static inline u64 vmx_control_msr(u32 low, u32 high)
3743 {
3744         return low | ((u64)high << 32);
3745 }
3746
3747 static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
3748 {
3749         superset &= mask;
3750         subset &= mask;
3751
3752         return (superset | subset) == superset;
3753 }
3754
3755 static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
3756 {
3757         const u64 feature_and_reserved =
3758                 /* feature (except bit 48; see below) */
3759                 BIT_ULL(49) | BIT_ULL(54) | BIT_ULL(55) |
3760                 /* reserved */
3761                 BIT_ULL(31) | GENMASK_ULL(47, 45) | GENMASK_ULL(63, 56);
3762         u64 vmx_basic = vmx->nested.msrs.basic;
3763
3764         if (!is_bitwise_subset(vmx_basic, data, feature_and_reserved))
3765                 return -EINVAL;
3766
3767         /*
3768          * KVM does not emulate a version of VMX that constrains physical
3769          * addresses of VMX structures (e.g. VMCS) to 32-bits.
3770          */
3771         if (data & BIT_ULL(48))
3772                 return -EINVAL;
3773
3774         if (vmx_basic_vmcs_revision_id(vmx_basic) !=
3775             vmx_basic_vmcs_revision_id(data))
3776                 return -EINVAL;
3777
3778         if (vmx_basic_vmcs_size(vmx_basic) > vmx_basic_vmcs_size(data))
3779                 return -EINVAL;
3780
3781         vmx->nested.msrs.basic = data;
3782         return 0;
3783 }
3784
3785 static int
3786 vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3787 {
3788         u64 supported;
3789         u32 *lowp, *highp;
3790
3791         switch (msr_index) {
3792         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3793                 lowp = &vmx->nested.msrs.pinbased_ctls_low;
3794                 highp = &vmx->nested.msrs.pinbased_ctls_high;
3795                 break;
3796         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3797                 lowp = &vmx->nested.msrs.procbased_ctls_low;
3798                 highp = &vmx->nested.msrs.procbased_ctls_high;
3799                 break;
3800         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3801                 lowp = &vmx->nested.msrs.exit_ctls_low;
3802                 highp = &vmx->nested.msrs.exit_ctls_high;
3803                 break;
3804         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3805                 lowp = &vmx->nested.msrs.entry_ctls_low;
3806                 highp = &vmx->nested.msrs.entry_ctls_high;
3807                 break;
3808         case MSR_IA32_VMX_PROCBASED_CTLS2:
3809                 lowp = &vmx->nested.msrs.secondary_ctls_low;
3810                 highp = &vmx->nested.msrs.secondary_ctls_high;
3811                 break;
3812         default:
3813                 BUG();
3814         }
3815
3816         supported = vmx_control_msr(*lowp, *highp);
3817
3818         /* Check must-be-1 bits are still 1. */
3819         if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0)))
3820                 return -EINVAL;
3821
3822         /* Check must-be-0 bits are still 0. */
3823         if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32)))
3824                 return -EINVAL;
3825
3826         *lowp = data;
3827         *highp = data >> 32;
3828         return 0;
3829 }
3830
3831 static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
3832 {
3833         const u64 feature_and_reserved_bits =
3834                 /* feature */
3835                 BIT_ULL(5) | GENMASK_ULL(8, 6) | BIT_ULL(14) | BIT_ULL(15) |
3836                 BIT_ULL(28) | BIT_ULL(29) | BIT_ULL(30) |
3837                 /* reserved */
3838                 GENMASK_ULL(13, 9) | BIT_ULL(31);
3839         u64 vmx_misc;
3840
3841         vmx_misc = vmx_control_msr(vmx->nested.msrs.misc_low,
3842                                    vmx->nested.msrs.misc_high);
3843
3844         if (!is_bitwise_subset(vmx_misc, data, feature_and_reserved_bits))
3845                 return -EINVAL;
3846
3847         if ((vmx->nested.msrs.pinbased_ctls_high &
3848              PIN_BASED_VMX_PREEMPTION_TIMER) &&
3849             vmx_misc_preemption_timer_rate(data) !=
3850             vmx_misc_preemption_timer_rate(vmx_misc))
3851                 return -EINVAL;
3852
3853         if (vmx_misc_cr3_count(data) > vmx_misc_cr3_count(vmx_misc))
3854                 return -EINVAL;
3855
3856         if (vmx_misc_max_msr(data) > vmx_misc_max_msr(vmx_misc))
3857                 return -EINVAL;
3858
3859         if (vmx_misc_mseg_revid(data) != vmx_misc_mseg_revid(vmx_misc))
3860                 return -EINVAL;
3861
3862         vmx->nested.msrs.misc_low = data;
3863         vmx->nested.msrs.misc_high = data >> 32;
3864
3865         /*
3866          * If L1 has read-only VM-exit information fields, use the
3867          * less permissive vmx_vmwrite_bitmap to specify write
3868          * permissions for the shadow VMCS.
3869          */
3870         if (enable_shadow_vmcs && !nested_cpu_has_vmwrite_any_field(&vmx->vcpu))
3871                 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
3872
3873         return 0;
3874 }
3875
3876 static int vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx *vmx, u64 data)
3877 {
3878         u64 vmx_ept_vpid_cap;
3879
3880         vmx_ept_vpid_cap = vmx_control_msr(vmx->nested.msrs.ept_caps,
3881                                            vmx->nested.msrs.vpid_caps);
3882
3883         /* Every bit is either reserved or a feature bit. */
3884         if (!is_bitwise_subset(vmx_ept_vpid_cap, data, -1ULL))
3885                 return -EINVAL;
3886
3887         vmx->nested.msrs.ept_caps = data;
3888         vmx->nested.msrs.vpid_caps = data >> 32;
3889         return 0;
3890 }
3891
3892 static int vmx_restore_fixed0_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3893 {
3894         u64 *msr;
3895
3896         switch (msr_index) {
3897         case MSR_IA32_VMX_CR0_FIXED0:
3898                 msr = &vmx->nested.msrs.cr0_fixed0;
3899                 break;
3900         case MSR_IA32_VMX_CR4_FIXED0:
3901                 msr = &vmx->nested.msrs.cr4_fixed0;
3902                 break;
3903         default:
3904                 BUG();
3905         }
3906
3907         /*
3908          * 1 bits (which indicates bits which "must-be-1" during VMX operation)
3909          * must be 1 in the restored value.
3910          */
3911         if (!is_bitwise_subset(data, *msr, -1ULL))
3912                 return -EINVAL;
3913
3914         *msr = data;
3915         return 0;
3916 }
3917
3918 /*
3919  * Called when userspace is restoring VMX MSRs.
3920  *
3921  * Returns 0 on success, non-0 otherwise.
3922  */
3923 static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
3924 {
3925         struct vcpu_vmx *vmx = to_vmx(vcpu);
3926
3927         /*
3928          * Don't allow changes to the VMX capability MSRs while the vCPU
3929          * is in VMX operation.
3930          */
3931         if (vmx->nested.vmxon)
3932                 return -EBUSY;
3933
3934         switch (msr_index) {
3935         case MSR_IA32_VMX_BASIC:
3936                 return vmx_restore_vmx_basic(vmx, data);
3937         case MSR_IA32_VMX_PINBASED_CTLS:
3938         case MSR_IA32_VMX_PROCBASED_CTLS:
3939         case MSR_IA32_VMX_EXIT_CTLS:
3940         case MSR_IA32_VMX_ENTRY_CTLS:
3941                 /*
3942                  * The "non-true" VMX capability MSRs are generated from the
3943                  * "true" MSRs, so we do not support restoring them directly.
3944                  *
3945                  * If userspace wants to emulate VMX_BASIC[55]=0, userspace
3946                  * should restore the "true" MSRs with the must-be-1 bits
3947                  * set according to the SDM Vol 3. A.2 "RESERVED CONTROLS AND
3948                  * DEFAULT SETTINGS".
3949                  */
3950                 return -EINVAL;
3951         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3952         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3953         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3954         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3955         case MSR_IA32_VMX_PROCBASED_CTLS2:
3956                 return vmx_restore_control_msr(vmx, msr_index, data);
3957         case MSR_IA32_VMX_MISC:
3958                 return vmx_restore_vmx_misc(vmx, data);
3959         case MSR_IA32_VMX_CR0_FIXED0:
3960         case MSR_IA32_VMX_CR4_FIXED0:
3961                 return vmx_restore_fixed0_msr(vmx, msr_index, data);
3962         case MSR_IA32_VMX_CR0_FIXED1:
3963         case MSR_IA32_VMX_CR4_FIXED1:
3964                 /*
3965                  * These MSRs are generated based on the vCPU's CPUID, so we
3966                  * do not support restoring them directly.
3967                  */
3968                 return -EINVAL;
3969         case MSR_IA32_VMX_EPT_VPID_CAP:
3970                 return vmx_restore_vmx_ept_vpid_cap(vmx, data);
3971         case MSR_IA32_VMX_VMCS_ENUM:
3972                 vmx->nested.msrs.vmcs_enum = data;
3973                 return 0;
3974         default:
3975                 /*
3976                  * The rest of the VMX capability MSRs do not support restore.
3977                  */
3978                 return -EINVAL;
3979         }
3980 }
3981
3982 /* Returns 0 on success, non-0 otherwise. */
3983 static int vmx_get_vmx_msr(struct nested_vmx_msrs *msrs, u32 msr_index, u64 *pdata)
3984 {
3985         switch (msr_index) {
3986         case MSR_IA32_VMX_BASIC:
3987                 *pdata = msrs->basic;
3988                 break;
3989         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3990         case MSR_IA32_VMX_PINBASED_CTLS:
3991                 *pdata = vmx_control_msr(
3992                         msrs->pinbased_ctls_low,
3993                         msrs->pinbased_ctls_high);
3994                 if (msr_index == MSR_IA32_VMX_PINBASED_CTLS)
3995                         *pdata |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3996                 break;
3997         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3998         case MSR_IA32_VMX_PROCBASED_CTLS:
3999                 *pdata = vmx_control_msr(
4000                         msrs->procbased_ctls_low,
4001                         msrs->procbased_ctls_high);
4002                 if (msr_index == MSR_IA32_VMX_PROCBASED_CTLS)
4003                         *pdata |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
4004                 break;
4005         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
4006         case MSR_IA32_VMX_EXIT_CTLS:
4007                 *pdata = vmx_control_msr(
4008                         msrs->exit_ctls_low,
4009                         msrs->exit_ctls_high);
4010                 if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
4011                         *pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
4012                 break;
4013         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
4014         case MSR_IA32_VMX_ENTRY_CTLS:
4015                 *pdata = vmx_control_msr(
4016                         msrs->entry_ctls_low,
4017                         msrs->entry_ctls_high);
4018                 if (msr_index == MSR_IA32_VMX_ENTRY_CTLS)
4019                         *pdata |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
4020                 break;
4021         case MSR_IA32_VMX_MISC:
4022                 *pdata = vmx_control_msr(
4023                         msrs->misc_low,
4024                         msrs->misc_high);
4025                 break;
4026         case MSR_IA32_VMX_CR0_FIXED0:
4027                 *pdata = msrs->cr0_fixed0;
4028                 break;
4029         case MSR_IA32_VMX_CR0_FIXED1:
4030                 *pdata = msrs->cr0_fixed1;
4031                 break;
4032         case MSR_IA32_VMX_CR4_FIXED0:
4033                 *pdata = msrs->cr4_fixed0;
4034                 break;
4035         case MSR_IA32_VMX_CR4_FIXED1:
4036                 *pdata = msrs->cr4_fixed1;
4037                 break;
4038         case MSR_IA32_VMX_VMCS_ENUM:
4039                 *pdata = msrs->vmcs_enum;
4040                 break;
4041         case MSR_IA32_VMX_PROCBASED_CTLS2:
4042                 *pdata = vmx_control_msr(
4043                         msrs->secondary_ctls_low,
4044                         msrs->secondary_ctls_high);
4045                 break;
4046         case MSR_IA32_VMX_EPT_VPID_CAP:
4047                 *pdata = msrs->ept_caps |
4048                         ((u64)msrs->vpid_caps << 32);
4049                 break;
4050         case MSR_IA32_VMX_VMFUNC:
4051                 *pdata = msrs->vmfunc_controls;
4052                 break;
4053         default:
4054                 return 1;
4055         }
4056
4057         return 0;
4058 }
4059
4060 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
4061                                                  uint64_t val)
4062 {
4063         uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
4064
4065         return !(val & ~valid_bits);
4066 }
4067
4068 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
4069 {
4070         switch (msr->index) {
4071         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4072                 if (!nested)
4073                         return 1;
4074                 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
4075         default:
4076                 return 1;
4077         }
4078
4079         return 0;
4080 }
4081
4082 /*
4083  * Reads an msr value (of 'msr_index') into 'pdata'.
4084  * Returns 0 on success, non-0 otherwise.
4085  * Assumes vcpu_load() was already called.
4086  */
4087 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4088 {
4089         struct vcpu_vmx *vmx = to_vmx(vcpu);
4090         struct shared_msr_entry *msr;
4091
4092         switch (msr_info->index) {
4093 #ifdef CONFIG_X86_64
4094         case MSR_FS_BASE:
4095                 msr_info->data = vmcs_readl(GUEST_FS_BASE);
4096                 break;
4097         case MSR_GS_BASE:
4098                 msr_info->data = vmcs_readl(GUEST_GS_BASE);
4099                 break;
4100         case MSR_KERNEL_GS_BASE:
4101                 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
4102                 break;
4103 #endif
4104         case MSR_EFER:
4105                 return kvm_get_msr_common(vcpu, msr_info);
4106         case MSR_IA32_SPEC_CTRL:
4107                 if (!msr_info->host_initiated &&
4108                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
4109                         return 1;
4110
4111                 msr_info->data = to_vmx(vcpu)->spec_ctrl;
4112                 break;
4113         case MSR_IA32_ARCH_CAPABILITIES:
4114                 if (!msr_info->host_initiated &&
4115                     !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
4116                         return 1;
4117                 msr_info->data = to_vmx(vcpu)->arch_capabilities;
4118                 break;
4119         case MSR_IA32_SYSENTER_CS:
4120                 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
4121                 break;
4122         case MSR_IA32_SYSENTER_EIP:
4123                 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
4124                 break;
4125         case MSR_IA32_SYSENTER_ESP:
4126                 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
4127                 break;
4128         case MSR_IA32_BNDCFGS:
4129                 if (!kvm_mpx_supported() ||
4130                     (!msr_info->host_initiated &&
4131                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
4132                         return 1;
4133                 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
4134                 break;
4135         case MSR_IA32_MCG_EXT_CTL:
4136                 if (!msr_info->host_initiated &&
4137                     !(vmx->msr_ia32_feature_control &
4138                       FEATURE_CONTROL_LMCE))
4139                         return 1;
4140                 msr_info->data = vcpu->arch.mcg_ext_ctl;
4141                 break;
4142         case MSR_IA32_FEATURE_CONTROL:
4143                 msr_info->data = vmx->msr_ia32_feature_control;
4144                 break;
4145         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4146                 if (!nested_vmx_allowed(vcpu))
4147                         return 1;
4148                 return vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
4149                                        &msr_info->data);
4150         case MSR_IA32_XSS:
4151                 if (!vmx_xsaves_supported())
4152                         return 1;
4153                 msr_info->data = vcpu->arch.ia32_xss;
4154                 break;
4155         case MSR_TSC_AUX:
4156                 if (!msr_info->host_initiated &&
4157                     !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
4158                         return 1;
4159                 /* Otherwise falls through */
4160         default:
4161                 msr = find_msr_entry(vmx, msr_info->index);
4162                 if (msr) {
4163                         msr_info->data = msr->data;
4164                         break;
4165                 }
4166                 return kvm_get_msr_common(vcpu, msr_info);
4167         }
4168
4169         return 0;
4170 }
4171
4172 static void vmx_leave_nested(struct kvm_vcpu *vcpu);
4173
4174 /*
4175  * Writes msr value into into the appropriate "register".
4176  * Returns 0 on success, non-0 otherwise.
4177  * Assumes vcpu_load() was already called.
4178  */
4179 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4180 {
4181         struct vcpu_vmx *vmx = to_vmx(vcpu);
4182         struct shared_msr_entry *msr;
4183         int ret = 0;
4184         u32 msr_index = msr_info->index;
4185         u64 data = msr_info->data;
4186
4187         switch (msr_index) {
4188         case MSR_EFER:
4189                 ret = kvm_set_msr_common(vcpu, msr_info);
4190                 break;
4191 #ifdef CONFIG_X86_64
4192         case MSR_FS_BASE:
4193                 vmx_segment_cache_clear(vmx);
4194                 vmcs_writel(GUEST_FS_BASE, data);
4195                 break;
4196         case MSR_GS_BASE:
4197                 vmx_segment_cache_clear(vmx);
4198                 vmcs_writel(GUEST_GS_BASE, data);
4199                 break;
4200         case MSR_KERNEL_GS_BASE:
4201                 vmx_write_guest_kernel_gs_base(vmx, data);
4202                 break;
4203 #endif
4204         case MSR_IA32_SYSENTER_CS:
4205                 vmcs_write32(GUEST_SYSENTER_CS, data);
4206                 break;
4207         case MSR_IA32_SYSENTER_EIP:
4208                 vmcs_writel(GUEST_SYSENTER_EIP, data);
4209                 break;
4210         case MSR_IA32_SYSENTER_ESP:
4211                 vmcs_writel(GUEST_SYSENTER_ESP, data);
4212                 break;
4213         case MSR_IA32_BNDCFGS:
4214                 if (!kvm_mpx_supported() ||
4215                     (!msr_info->host_initiated &&
4216                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
4217                         return 1;
4218                 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
4219                     (data & MSR_IA32_BNDCFGS_RSVD))
4220                         return 1;
4221                 vmcs_write64(GUEST_BNDCFGS, data);
4222                 break;
4223         case MSR_IA32_SPEC_CTRL:
4224                 if (!msr_info->host_initiated &&
4225                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
4226                         return 1;
4227
4228                 /* The STIBP bit doesn't fault even if it's not advertised */
4229                 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
4230                         return 1;
4231
4232                 vmx->spec_ctrl = data;
4233
4234                 if (!data)
4235                         break;
4236
4237                 /*
4238                  * For non-nested:
4239                  * When it's written (to non-zero) for the first time, pass
4240                  * it through.
4241                  *
4242                  * For nested:
4243                  * The handling of the MSR bitmap for L2 guests is done in
4244                  * nested_vmx_merge_msr_bitmap. We should not touch the
4245                  * vmcs02.msr_bitmap here since it gets completely overwritten
4246                  * in the merging. We update the vmcs01 here for L1 as well
4247                  * since it will end up touching the MSR anyway now.
4248                  */
4249                 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
4250                                               MSR_IA32_SPEC_CTRL,
4251                                               MSR_TYPE_RW);
4252                 break;
4253         case MSR_IA32_PRED_CMD:
4254                 if (!msr_info->host_initiated &&
4255                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
4256                         return 1;
4257
4258                 if (data & ~PRED_CMD_IBPB)
4259                         return 1;
4260
4261                 if (!data)
4262                         break;
4263
4264                 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
4265
4266                 /*
4267                  * For non-nested:
4268                  * When it's written (to non-zero) for the first time, pass
4269                  * it through.
4270                  *
4271                  * For nested:
4272                  * The handling of the MSR bitmap for L2 guests is done in
4273                  * nested_vmx_merge_msr_bitmap. We should not touch the
4274                  * vmcs02.msr_bitmap here since it gets completely overwritten
4275                  * in the merging.
4276                  */
4277                 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
4278                                               MSR_TYPE_W);
4279                 break;
4280         case MSR_IA32_ARCH_CAPABILITIES:
4281                 if (!msr_info->host_initiated)
4282                         return 1;
4283                 vmx->arch_capabilities = data;
4284                 break;
4285         case MSR_IA32_CR_PAT:
4286                 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
4287                         if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
4288                                 return 1;
4289                         vmcs_write64(GUEST_IA32_PAT, data);
4290                         vcpu->arch.pat = data;
4291                         break;
4292                 }
4293                 ret = kvm_set_msr_common(vcpu, msr_info);
4294                 break;
4295         case MSR_IA32_TSC_ADJUST:
4296                 ret = kvm_set_msr_common(vcpu, msr_info);
4297                 break;
4298         case MSR_IA32_MCG_EXT_CTL:
4299                 if ((!msr_info->host_initiated &&
4300                      !(to_vmx(vcpu)->msr_ia32_feature_control &
4301                        FEATURE_CONTROL_LMCE)) ||
4302                     (data & ~MCG_EXT_CTL_LMCE_EN))
4303                         return 1;
4304                 vcpu->arch.mcg_ext_ctl = data;
4305                 break;
4306         case MSR_IA32_FEATURE_CONTROL:
4307                 if (!vmx_feature_control_msr_valid(vcpu, data) ||
4308                     (to_vmx(vcpu)->msr_ia32_feature_control &
4309                      FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
4310                         return 1;
4311                 vmx->msr_ia32_feature_control = data;
4312                 if (msr_info->host_initiated && data == 0)
4313                         vmx_leave_nested(vcpu);
4314                 break;
4315         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4316                 if (!msr_info->host_initiated)
4317                         return 1; /* they are read-only */
4318                 if (!nested_vmx_allowed(vcpu))
4319                         return 1;
4320                 return vmx_set_vmx_msr(vcpu, msr_index, data);
4321         case MSR_IA32_XSS:
4322                 if (!vmx_xsaves_supported())
4323                         return 1;
4324                 /*
4325                  * The only supported bit as of Skylake is bit 8, but
4326                  * it is not supported on KVM.
4327                  */
4328                 if (data != 0)
4329                         return 1;
4330                 vcpu->arch.ia32_xss = data;
4331                 if (vcpu->arch.ia32_xss != host_xss)
4332                         add_atomic_switch_msr(vmx, MSR_IA32_XSS,
4333                                 vcpu->arch.ia32_xss, host_xss, false);
4334                 else
4335                         clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
4336                 break;
4337         case MSR_TSC_AUX:
4338                 if (!msr_info->host_initiated &&
4339                     !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
4340                         return 1;
4341                 /* Check reserved bit, higher 32 bits should be zero */
4342                 if ((data >> 32) != 0)
4343                         return 1;
4344                 /* Otherwise falls through */
4345         default:
4346                 msr = find_msr_entry(vmx, msr_index);
4347                 if (msr) {
4348                         u64 old_msr_data = msr->data;
4349                         msr->data = data;
4350                         if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
4351                                 preempt_disable();
4352                                 ret = kvm_set_shared_msr(msr->index, msr->data,
4353                                                          msr->mask);
4354                                 preempt_enable();
4355                                 if (ret)
4356                                         msr->data = old_msr_data;
4357                         }
4358                         break;
4359                 }
4360                 ret = kvm_set_msr_common(vcpu, msr_info);
4361         }
4362
4363         return ret;
4364 }
4365
4366 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
4367 {
4368         __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
4369         switch (reg) {
4370         case VCPU_REGS_RSP:
4371                 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
4372                 break;
4373         case VCPU_REGS_RIP:
4374                 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
4375                 break;
4376         case VCPU_EXREG_PDPTR:
4377                 if (enable_ept)
4378                         ept_save_pdptrs(vcpu);
4379                 break;
4380         default:
4381                 break;
4382         }
4383 }
4384
4385 static __init int cpu_has_kvm_support(void)
4386 {
4387         return cpu_has_vmx();
4388 }
4389
4390 static __init int vmx_disabled_by_bios(void)
4391 {
4392         u64 msr;
4393
4394         rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
4395         if (msr & FEATURE_CONTROL_LOCKED) {
4396                 /* launched w/ TXT and VMX disabled */
4397                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
4398                         && tboot_enabled())
4399                         return 1;
4400                 /* launched w/o TXT and VMX only enabled w/ TXT */
4401                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
4402                         && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
4403                         && !tboot_enabled()) {
4404                         printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
4405                                 "activate TXT before enabling KVM\n");
4406                         return 1;
4407                 }
4408                 /* launched w/o TXT and VMX disabled */
4409                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
4410                         && !tboot_enabled())
4411                         return 1;
4412         }
4413
4414         return 0;
4415 }
4416
4417 static void kvm_cpu_vmxon(u64 addr)
4418 {
4419         cr4_set_bits(X86_CR4_VMXE);
4420         intel_pt_handle_vmx(1);
4421
4422         asm volatile ("vmxon %0" : : "m"(addr));
4423 }
4424
4425 static int hardware_enable(void)
4426 {
4427         int cpu = raw_smp_processor_id();
4428         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
4429         u64 old, test_bits;
4430
4431         if (cr4_read_shadow() & X86_CR4_VMXE)
4432                 return -EBUSY;
4433
4434         /*
4435          * This can happen if we hot-added a CPU but failed to allocate
4436          * VP assist page for it.
4437          */
4438         if (static_branch_unlikely(&enable_evmcs) &&
4439             !hv_get_vp_assist_page(cpu))
4440                 return -EFAULT;
4441
4442         INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
4443         INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
4444         spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
4445
4446         /*
4447          * Now we can enable the vmclear operation in kdump
4448          * since the loaded_vmcss_on_cpu list on this cpu
4449          * has been initialized.
4450          *
4451          * Though the cpu is not in VMX operation now, there
4452          * is no problem to enable the vmclear operation
4453          * for the loaded_vmcss_on_cpu list is empty!
4454          */
4455         crash_enable_local_vmclear(cpu);
4456
4457         rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
4458
4459         test_bits = FEATURE_CONTROL_LOCKED;
4460         test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
4461         if (tboot_enabled())
4462                 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
4463
4464         if ((old & test_bits) != test_bits) {
4465                 /* enable and lock */
4466                 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
4467         }
4468         kvm_cpu_vmxon(phys_addr);
4469         if (enable_ept)
4470                 ept_sync_global();
4471
4472         return 0;
4473 }
4474
4475 static void vmclear_local_loaded_vmcss(void)
4476 {
4477         int cpu = raw_smp_processor_id();
4478         struct loaded_vmcs *v, *n;
4479
4480         list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
4481                                  loaded_vmcss_on_cpu_link)
4482                 __loaded_vmcs_clear(v);
4483 }
4484
4485
4486 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
4487  * tricks.
4488  */
4489 static void kvm_cpu_vmxoff(void)
4490 {
4491         asm volatile (__ex("vmxoff"));
4492
4493         intel_pt_handle_vmx(0);
4494         cr4_clear_bits(X86_CR4_VMXE);
4495 }
4496
4497 static void hardware_disable(void)
4498 {
4499         vmclear_local_loaded_vmcss();
4500         kvm_cpu_vmxoff();
4501 }
4502
4503 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
4504                                       u32 msr, u32 *result)
4505 {
4506         u32 vmx_msr_low, vmx_msr_high;
4507         u32 ctl = ctl_min | ctl_opt;
4508
4509         rdmsr(msr, vmx_msr_low, vmx_msr_high);
4510
4511         ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
4512         ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
4513
4514         /* Ensure minimum (required) set of control bits are supported. */
4515         if (ctl_min & ~ctl)
4516                 return -EIO;
4517
4518         *result = ctl;
4519         return 0;
4520 }
4521
4522 static __init bool allow_1_setting(u32 msr, u32 ctl)
4523 {
4524         u32 vmx_msr_low, vmx_msr_high;
4525
4526         rdmsr(msr, vmx_msr_low, vmx_msr_high);
4527         return vmx_msr_high & ctl;
4528 }
4529
4530 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
4531 {
4532         u32 vmx_msr_low, vmx_msr_high;
4533         u32 min, opt, min2, opt2;
4534         u32 _pin_based_exec_control = 0;
4535         u32 _cpu_based_exec_control = 0;
4536         u32 _cpu_based_2nd_exec_control = 0;
4537         u32 _vmexit_control = 0;
4538         u32 _vmentry_control = 0;
4539
4540         memset(vmcs_conf, 0, sizeof(*vmcs_conf));
4541         min = CPU_BASED_HLT_EXITING |
4542 #ifdef CONFIG_X86_64
4543               CPU_BASED_CR8_LOAD_EXITING |
4544               CPU_BASED_CR8_STORE_EXITING |
4545 #endif
4546               CPU_BASED_CR3_LOAD_EXITING |
4547               CPU_BASED_CR3_STORE_EXITING |
4548               CPU_BASED_UNCOND_IO_EXITING |
4549               CPU_BASED_MOV_DR_EXITING |
4550               CPU_BASED_USE_TSC_OFFSETING |
4551               CPU_BASED_MWAIT_EXITING |
4552               CPU_BASED_MONITOR_EXITING |
4553               CPU_BASED_INVLPG_EXITING |
4554               CPU_BASED_RDPMC_EXITING;
4555
4556         opt = CPU_BASED_TPR_SHADOW |
4557               CPU_BASED_USE_MSR_BITMAPS |
4558               CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
4559         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
4560                                 &_cpu_based_exec_control) < 0)
4561                 return -EIO;
4562 #ifdef CONFIG_X86_64
4563         if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
4564                 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
4565                                            ~CPU_BASED_CR8_STORE_EXITING;
4566 #endif
4567         if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
4568                 min2 = 0;
4569                 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
4570                         SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
4571                         SECONDARY_EXEC_WBINVD_EXITING |
4572                         SECONDARY_EXEC_ENABLE_VPID |
4573                         SECONDARY_EXEC_ENABLE_EPT |
4574                         SECONDARY_EXEC_UNRESTRICTED_GUEST |
4575                         SECONDARY_EXEC_PAUSE_LOOP_EXITING |
4576                         SECONDARY_EXEC_DESC |
4577                         SECONDARY_EXEC_RDTSCP |
4578                         SECONDARY_EXEC_ENABLE_INVPCID |
4579                         SECONDARY_EXEC_APIC_REGISTER_VIRT |
4580                         SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
4581                         SECONDARY_EXEC_SHADOW_VMCS |
4582                         SECONDARY_EXEC_XSAVES |
4583                         SECONDARY_EXEC_RDSEED_EXITING |
4584                         SECONDARY_EXEC_RDRAND_EXITING |
4585                         SECONDARY_EXEC_ENABLE_PML |
4586                         SECONDARY_EXEC_TSC_SCALING |
4587                         SECONDARY_EXEC_ENABLE_VMFUNC |
4588                         SECONDARY_EXEC_ENCLS_EXITING;
4589                 if (adjust_vmx_controls(min2, opt2,
4590                                         MSR_IA32_VMX_PROCBASED_CTLS2,
4591                                         &_cpu_based_2nd_exec_control) < 0)
4592                         return -EIO;
4593         }
4594 #ifndef CONFIG_X86_64
4595         if (!(_cpu_based_2nd_exec_control &
4596                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
4597                 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
4598 #endif
4599
4600         if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
4601                 _cpu_based_2nd_exec_control &= ~(
4602                                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4603                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
4604                                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4605
4606         rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
4607                 &vmx_capability.ept, &vmx_capability.vpid);
4608
4609         if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
4610                 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
4611                    enabled */
4612                 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
4613                                              CPU_BASED_CR3_STORE_EXITING |
4614                                              CPU_BASED_INVLPG_EXITING);
4615         } else if (vmx_capability.ept) {
4616                 vmx_capability.ept = 0;
4617                 pr_warn_once("EPT CAP should not exist if not support "
4618                                 "1-setting enable EPT VM-execution control\n");
4619         }
4620         if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
4621                 vmx_capability.vpid) {
4622                 vmx_capability.vpid = 0;
4623                 pr_warn_once("VPID CAP should not exist if not support "
4624                                 "1-setting enable VPID VM-execution control\n");
4625         }
4626
4627         min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
4628 #ifdef CONFIG_X86_64
4629         min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
4630 #endif
4631         opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
4632                 VM_EXIT_CLEAR_BNDCFGS;
4633         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
4634                                 &_vmexit_control) < 0)
4635                 return -EIO;
4636
4637         min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
4638         opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
4639                  PIN_BASED_VMX_PREEMPTION_TIMER;
4640         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
4641                                 &_pin_based_exec_control) < 0)
4642                 return -EIO;
4643
4644         if (cpu_has_broken_vmx_preemption_timer())
4645                 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4646         if (!(_cpu_based_2nd_exec_control &
4647                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
4648                 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
4649
4650         min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
4651         opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
4652         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
4653                                 &_vmentry_control) < 0)
4654                 return -EIO;
4655
4656         rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
4657
4658         /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
4659         if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
4660                 return -EIO;
4661
4662 #ifdef CONFIG_X86_64
4663         /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
4664         if (vmx_msr_high & (1u<<16))
4665                 return -EIO;
4666 #endif
4667
4668         /* Require Write-Back (WB) memory type for VMCS accesses. */
4669         if (((vmx_msr_high >> 18) & 15) != 6)
4670                 return -EIO;
4671
4672         vmcs_conf->size = vmx_msr_high & 0x1fff;
4673         vmcs_conf->order = get_order(vmcs_conf->size);
4674         vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
4675
4676         vmcs_conf->revision_id = vmx_msr_low;
4677
4678         vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
4679         vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
4680         vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
4681         vmcs_conf->vmexit_ctrl         = _vmexit_control;
4682         vmcs_conf->vmentry_ctrl        = _vmentry_control;
4683
4684         if (static_branch_unlikely(&enable_evmcs))
4685                 evmcs_sanitize_exec_ctrls(vmcs_conf);
4686
4687         cpu_has_load_ia32_efer =
4688                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
4689                                 VM_ENTRY_LOAD_IA32_EFER)
4690                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
4691                                    VM_EXIT_LOAD_IA32_EFER);
4692
4693         cpu_has_load_perf_global_ctrl =
4694                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
4695                                 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
4696                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
4697                                    VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
4698
4699         /*
4700          * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
4701          * but due to errata below it can't be used. Workaround is to use
4702          * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
4703          *
4704          * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
4705          *
4706          * AAK155             (model 26)
4707          * AAP115             (model 30)
4708          * AAT100             (model 37)
4709          * BC86,AAY89,BD102   (model 44)
4710          * BA97               (model 46)
4711          *
4712          */
4713         if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
4714                 switch (boot_cpu_data.x86_model) {
4715                 case 26:
4716                 case 30:
4717                 case 37:
4718                 case 44:
4719                 case 46:
4720                         cpu_has_load_perf_global_ctrl = false;
4721                         printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
4722                                         "does not work properly. Using workaround\n");
4723                         break;
4724                 default:
4725                         break;
4726                 }
4727         }
4728
4729         if (boot_cpu_has(X86_FEATURE_XSAVES))
4730                 rdmsrl(MSR_IA32_XSS, host_xss);
4731
4732         return 0;
4733 }
4734
4735 static struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu)
4736 {
4737         int node = cpu_to_node(cpu);
4738         struct page *pages;
4739         struct vmcs *vmcs;
4740
4741         pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
4742         if (!pages)
4743                 return NULL;
4744         vmcs = page_address(pages);
4745         memset(vmcs, 0, vmcs_config.size);
4746
4747         /* KVM supports Enlightened VMCS v1 only */
4748         if (static_branch_unlikely(&enable_evmcs))
4749                 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
4750         else
4751                 vmcs->hdr.revision_id = vmcs_config.revision_id;
4752
4753         if (shadow)
4754                 vmcs->hdr.shadow_vmcs = 1;
4755         return vmcs;
4756 }
4757
4758 static void free_vmcs(struct vmcs *vmcs)
4759 {
4760         free_pages((unsigned long)vmcs, vmcs_config.order);
4761 }
4762
4763 /*
4764  * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
4765  */
4766 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
4767 {
4768         if (!loaded_vmcs->vmcs)
4769                 return;
4770         loaded_vmcs_clear(loaded_vmcs);
4771         free_vmcs(loaded_vmcs->vmcs);
4772         loaded_vmcs->vmcs = NULL;
4773         if (loaded_vmcs->msr_bitmap)
4774                 free_page((unsigned long)loaded_vmcs->msr_bitmap);
4775         WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
4776 }
4777
4778 static struct vmcs *alloc_vmcs(bool shadow)
4779 {
4780         return alloc_vmcs_cpu(shadow, raw_smp_processor_id());
4781 }
4782
4783 static int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
4784 {
4785         loaded_vmcs->vmcs = alloc_vmcs(false);
4786         if (!loaded_vmcs->vmcs)
4787                 return -ENOMEM;
4788
4789         loaded_vmcs->shadow_vmcs = NULL;
4790         loaded_vmcs_init(loaded_vmcs);
4791
4792         if (cpu_has_vmx_msr_bitmap()) {
4793                 loaded_vmcs->msr_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
4794                 if (!loaded_vmcs->msr_bitmap)
4795                         goto out_vmcs;
4796                 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
4797
4798                 if (IS_ENABLED(CONFIG_HYPERV) &&
4799                     static_branch_unlikely(&enable_evmcs) &&
4800                     (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
4801                         struct hv_enlightened_vmcs *evmcs =
4802                                 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
4803
4804                         evmcs->hv_enlightenments_control.msr_bitmap = 1;
4805                 }
4806         }
4807
4808         memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
4809
4810         return 0;
4811
4812 out_vmcs:
4813         free_loaded_vmcs(loaded_vmcs);
4814         return -ENOMEM;
4815 }
4816
4817 static void free_kvm_area(void)
4818 {
4819         int cpu;
4820
4821         for_each_possible_cpu(cpu) {
4822                 free_vmcs(per_cpu(vmxarea, cpu));
4823                 per_cpu(vmxarea, cpu) = NULL;
4824         }
4825 }
4826
4827 enum vmcs_field_width {
4828         VMCS_FIELD_WIDTH_U16 = 0,
4829         VMCS_FIELD_WIDTH_U64 = 1,
4830         VMCS_FIELD_WIDTH_U32 = 2,
4831         VMCS_FIELD_WIDTH_NATURAL_WIDTH = 3
4832 };
4833
4834 static inline int vmcs_field_width(unsigned long field)
4835 {
4836         if (0x1 & field)        /* the *_HIGH fields are all 32 bit */
4837                 return VMCS_FIELD_WIDTH_U32;
4838         return (field >> 13) & 0x3 ;
4839 }
4840
4841 static inline int vmcs_field_readonly(unsigned long field)
4842 {
4843         return (((field >> 10) & 0x3) == 1);
4844 }
4845
4846 static void init_vmcs_shadow_fields(void)
4847 {
4848         int i, j;
4849
4850         for (i = j = 0; i < max_shadow_read_only_fields; i++) {
4851                 u16 field = shadow_read_only_fields[i];
4852                 if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
4853                     (i + 1 == max_shadow_read_only_fields ||
4854                      shadow_read_only_fields[i + 1] != field + 1))
4855                         pr_err("Missing field from shadow_read_only_field %x\n",
4856                                field + 1);
4857
4858                 clear_bit(field, vmx_vmread_bitmap);
4859 #ifdef CONFIG_X86_64
4860                 if (field & 1)
4861                         continue;
4862 #endif
4863                 if (j < i)
4864                         shadow_read_only_fields[j] = field;
4865                 j++;
4866         }
4867         max_shadow_read_only_fields = j;
4868
4869         for (i = j = 0; i < max_shadow_read_write_fields; i++) {
4870                 u16 field = shadow_read_write_fields[i];
4871                 if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
4872                     (i + 1 == max_shadow_read_write_fields ||
4873                      shadow_read_write_fields[i + 1] != field + 1))
4874                         pr_err("Missing field from shadow_read_write_field %x\n",
4875                                field + 1);
4876
4877                 /*
4878                  * PML and the preemption timer can be emulated, but the
4879                  * processor cannot vmwrite to fields that don't exist
4880                  * on bare metal.
4881                  */
4882                 switch (field) {
4883                 case GUEST_PML_INDEX:
4884                         if (!cpu_has_vmx_pml())
4885                                 continue;
4886                         break;
4887                 case VMX_PREEMPTION_TIMER_VALUE:
4888                         if (!cpu_has_vmx_preemption_timer())
4889                                 continue;
4890                         break;
4891                 case GUEST_INTR_STATUS:
4892                         if (!cpu_has_vmx_apicv())
4893                                 continue;
4894                         break;
4895                 default:
4896                         break;
4897                 }
4898
4899                 clear_bit(field, vmx_vmwrite_bitmap);
4900                 clear_bit(field, vmx_vmread_bitmap);
4901 #ifdef CONFIG_X86_64
4902                 if (field & 1)
4903                         continue;
4904 #endif
4905                 if (j < i)
4906                         shadow_read_write_fields[j] = field;
4907                 j++;
4908         }
4909         max_shadow_read_write_fields = j;
4910 }
4911
4912 static __init int alloc_kvm_area(void)
4913 {
4914         int cpu;
4915
4916         for_each_possible_cpu(cpu) {
4917                 struct vmcs *vmcs;
4918
4919                 vmcs = alloc_vmcs_cpu(false, cpu);
4920                 if (!vmcs) {
4921                         free_kvm_area();
4922                         return -ENOMEM;
4923                 }
4924
4925                 /*
4926                  * When eVMCS is enabled, alloc_vmcs_cpu() sets
4927                  * vmcs->revision_id to KVM_EVMCS_VERSION instead of
4928                  * revision_id reported by MSR_IA32_VMX_BASIC.
4929                  *
4930                  * However, even though not explictly documented by
4931                  * TLFS, VMXArea passed as VMXON argument should
4932                  * still be marked with revision_id reported by
4933                  * physical CPU.
4934                  */
4935                 if (static_branch_unlikely(&enable_evmcs))
4936                         vmcs->hdr.revision_id = vmcs_config.revision_id;
4937
4938                 per_cpu(vmxarea, cpu) = vmcs;
4939         }
4940         return 0;
4941 }
4942
4943 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
4944                 struct kvm_segment *save)
4945 {
4946         if (!emulate_invalid_guest_state) {
4947                 /*
4948                  * CS and SS RPL should be equal during guest entry according
4949                  * to VMX spec, but in reality it is not always so. Since vcpu
4950                  * is in the middle of the transition from real mode to
4951                  * protected mode it is safe to assume that RPL 0 is a good
4952                  * default value.
4953                  */
4954                 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
4955                         save->selector &= ~SEGMENT_RPL_MASK;
4956                 save->dpl = save->selector & SEGMENT_RPL_MASK;
4957                 save->s = 1;
4958         }
4959         vmx_set_segment(vcpu, save, seg);
4960 }
4961
4962 static void enter_pmode(struct kvm_vcpu *vcpu)
4963 {
4964         unsigned long flags;
4965         struct vcpu_vmx *vmx = to_vmx(vcpu);
4966
4967         /*
4968          * Update real mode segment cache. It may be not up-to-date if sement
4969          * register was written while vcpu was in a guest mode.
4970          */
4971         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4972         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4973         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4974         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4975         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4976         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4977
4978         vmx->rmode.vm86_active = 0;
4979
4980         vmx_segment_cache_clear(vmx);
4981
4982         vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4983
4984         flags = vmcs_readl(GUEST_RFLAGS);
4985         flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
4986         flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
4987         vmcs_writel(GUEST_RFLAGS, flags);
4988
4989         vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
4990                         (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
4991
4992         update_exception_bitmap(vcpu);
4993
4994         fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4995         fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4996         fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4997         fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4998         fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4999         fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
5000 }
5001
5002 static void fix_rmode_seg(int seg, struct kvm_segment *save)
5003 {
5004         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
5005         struct kvm_segment var = *save;
5006
5007         var.dpl = 0x3;
5008         if (seg == VCPU_SREG_CS)
5009                 var.type = 0x3;
5010
5011         if (!emulate_invalid_guest_state) {
5012                 var.selector = var.base >> 4;
5013                 var.base = var.base & 0xffff0;
5014                 var.limit = 0xffff;
5015                 var.g = 0;
5016                 var.db = 0;
5017                 var.present = 1;
5018                 var.s = 1;
5019                 var.l = 0;
5020                 var.unusable = 0;
5021                 var.type = 0x3;
5022                 var.avl = 0;
5023                 if (save->base & 0xf)
5024                         printk_once(KERN_WARNING "kvm: segment base is not "
5025                                         "paragraph aligned when entering "
5026                                         "protected mode (seg=%d)", seg);
5027         }
5028
5029         vmcs_write16(sf->selector, var.selector);
5030         vmcs_writel(sf->base, var.base);
5031         vmcs_write32(sf->limit, var.limit);
5032         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
5033 }
5034
5035 static void enter_rmode(struct kvm_vcpu *vcpu)
5036 {
5037         unsigned long flags;
5038         struct vcpu_vmx *vmx = to_vmx(vcpu);
5039         struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
5040
5041         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
5042         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
5043         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
5044         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
5045         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
5046         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
5047         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
5048
5049         vmx->rmode.vm86_active = 1;
5050
5051         /*
5052          * Very old userspace does not call KVM_SET_TSS_ADDR before entering
5053          * vcpu. Warn the user that an update is overdue.
5054          */
5055         if (!kvm_vmx->tss_addr)
5056                 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
5057                              "called before entering vcpu\n");
5058
5059         vmx_segment_cache_clear(vmx);
5060
5061         vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
5062         vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
5063         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
5064
5065         flags = vmcs_readl(GUEST_RFLAGS);
5066         vmx->rmode.save_rflags = flags;
5067
5068         flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
5069
5070         vmcs_writel(GUEST_RFLAGS, flags);
5071         vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
5072         update_exception_bitmap(vcpu);
5073
5074         fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
5075         fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
5076         fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
5077         fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
5078         fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
5079         fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
5080
5081         kvm_mmu_reset_context(vcpu);
5082 }
5083
5084 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
5085 {
5086         struct vcpu_vmx *vmx = to_vmx(vcpu);
5087         struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
5088
5089         if (!msr)
5090                 return;
5091
5092         vcpu->arch.efer = efer;
5093         if (efer & EFER_LMA) {
5094                 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
5095                 msr->data = efer;
5096         } else {
5097                 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
5098
5099                 msr->data = efer & ~EFER_LME;
5100         }
5101         setup_msrs(vmx);
5102 }
5103
5104 #ifdef CONFIG_X86_64
5105
5106 static void enter_lmode(struct kvm_vcpu *vcpu)
5107 {
5108         u32 guest_tr_ar;
5109
5110         vmx_segment_cache_clear(to_vmx(vcpu));
5111
5112         guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
5113         if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
5114                 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
5115                                      __func__);
5116                 vmcs_write32(GUEST_TR_AR_BYTES,
5117                              (guest_tr_ar & ~VMX_AR_TYPE_MASK)
5118                              | VMX_AR_TYPE_BUSY_64_TSS);
5119         }
5120         vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
5121 }
5122
5123 static void exit_lmode(struct kvm_vcpu *vcpu)
5124 {
5125         vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
5126         vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
5127 }
5128
5129 #endif
5130
5131 static inline void __vmx_flush_tlb(struct kvm_vcpu *vcpu, int vpid,
5132                                 bool invalidate_gpa)
5133 {
5134         if (enable_ept && (invalidate_gpa || !enable_vpid)) {
5135                 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
5136                         return;
5137                 ept_sync_context(construct_eptp(vcpu,
5138                                                 vcpu->arch.mmu->root_hpa));
5139         } else {
5140                 vpid_sync_context(vpid);
5141         }
5142 }
5143
5144 static void vmx_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
5145 {
5146         __vmx_flush_tlb(vcpu, to_vmx(vcpu)->vpid, invalidate_gpa);
5147 }
5148
5149 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
5150 {
5151         int vpid = to_vmx(vcpu)->vpid;
5152
5153         if (!vpid_sync_vcpu_addr(vpid, addr))
5154                 vpid_sync_context(vpid);
5155
5156         /*
5157          * If VPIDs are not supported or enabled, then the above is a no-op.
5158          * But we don't really need a TLB flush in that case anyway, because
5159          * each VM entry/exit includes an implicit flush when VPID is 0.
5160          */
5161 }
5162
5163 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
5164 {
5165         ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
5166
5167         vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
5168         vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
5169 }
5170
5171 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
5172 {
5173         if (enable_unrestricted_guest || (enable_ept && is_paging(vcpu)))
5174                 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
5175         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
5176 }
5177
5178 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
5179 {
5180         ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
5181
5182         vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
5183         vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
5184 }
5185
5186 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
5187 {
5188         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
5189
5190         if (!test_bit(VCPU_EXREG_PDPTR,
5191                       (unsigned long *)&vcpu->arch.regs_dirty))
5192                 return;
5193
5194         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
5195                 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
5196                 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
5197                 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
5198                 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
5199         }
5200 }
5201
5202 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
5203 {
5204         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
5205
5206         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
5207                 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
5208                 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
5209                 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
5210                 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
5211         }
5212
5213         __set_bit(VCPU_EXREG_PDPTR,
5214                   (unsigned long *)&vcpu->arch.regs_avail);
5215         __set_bit(VCPU_EXREG_PDPTR,
5216                   (unsigned long *)&vcpu->arch.regs_dirty);
5217 }
5218
5219 static bool nested_guest_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
5220 {
5221         u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr0_fixed0;
5222         u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr0_fixed1;
5223         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5224
5225         if (to_vmx(vcpu)->nested.msrs.secondary_ctls_high &
5226                 SECONDARY_EXEC_UNRESTRICTED_GUEST &&
5227             nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
5228                 fixed0 &= ~(X86_CR0_PE | X86_CR0_PG);
5229
5230         return fixed_bits_valid(val, fixed0, fixed1);
5231 }
5232
5233 static bool nested_host_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
5234 {
5235         u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr0_fixed0;
5236         u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr0_fixed1;
5237
5238         return fixed_bits_valid(val, fixed0, fixed1);
5239 }
5240
5241 static bool nested_cr4_valid(struct kvm_vcpu *vcpu, unsigned long val)
5242 {
5243         u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr4_fixed0;
5244         u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr4_fixed1;
5245
5246         return fixed_bits_valid(val, fixed0, fixed1);
5247 }
5248
5249 /* No difference in the restrictions on guest and host CR4 in VMX operation. */
5250 #define nested_guest_cr4_valid  nested_cr4_valid
5251 #define nested_host_cr4_valid   nested_cr4_valid
5252
5253 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
5254
5255 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
5256                                         unsigned long cr0,
5257                                         struct kvm_vcpu *vcpu)
5258 {
5259         if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
5260                 vmx_decache_cr3(vcpu);
5261         if (!(cr0 & X86_CR0_PG)) {
5262                 /* From paging/starting to nonpaging */
5263                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
5264                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
5265                              (CPU_BASED_CR3_LOAD_EXITING |
5266                               CPU_BASED_CR3_STORE_EXITING));
5267                 vcpu->arch.cr0 = cr0;
5268                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
5269         } else if (!is_paging(vcpu)) {
5270                 /* From nonpaging to paging */
5271                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
5272                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
5273                              ~(CPU_BASED_CR3_LOAD_EXITING |
5274                                CPU_BASED_CR3_STORE_EXITING));
5275                 vcpu->arch.cr0 = cr0;
5276                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
5277         }
5278
5279         if (!(cr0 & X86_CR0_WP))
5280                 *hw_cr0 &= ~X86_CR0_WP;
5281 }
5282
5283 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
5284 {
5285         struct vcpu_vmx *vmx = to_vmx(vcpu);
5286         unsigned long hw_cr0;
5287
5288         hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
5289         if (enable_unrestricted_guest)
5290                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
5291         else {
5292                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
5293
5294                 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
5295                         enter_pmode(vcpu);
5296
5297                 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
5298                         enter_rmode(vcpu);
5299         }
5300
5301 #ifdef CONFIG_X86_64
5302         if (vcpu->arch.efer & EFER_LME) {
5303                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
5304                         enter_lmode(vcpu);
5305                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
5306                         exit_lmode(vcpu);
5307         }
5308 #endif
5309
5310         if (enable_ept && !enable_unrestricted_guest)
5311                 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
5312
5313         vmcs_writel(CR0_READ_SHADOW, cr0);
5314         vmcs_writel(GUEST_CR0, hw_cr0);
5315         vcpu->arch.cr0 = cr0;
5316
5317         /* depends on vcpu->arch.cr0 to be set to a new value */
5318         vmx->emulation_required = emulation_required(vcpu);
5319 }
5320
5321 static int get_ept_level(struct kvm_vcpu *vcpu)
5322 {
5323         if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
5324                 return 5;
5325         return 4;
5326 }
5327
5328 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
5329 {
5330         u64 eptp = VMX_EPTP_MT_WB;
5331
5332         eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
5333
5334         if (enable_ept_ad_bits &&
5335             (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
5336                 eptp |= VMX_EPTP_AD_ENABLE_BIT;
5337         eptp |= (root_hpa & PAGE_MASK);
5338
5339         return eptp;
5340 }
5341
5342 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
5343 {
5344         struct kvm *kvm = vcpu->kvm;
5345         unsigned long guest_cr3;
5346         u64 eptp;
5347
5348         guest_cr3 = cr3;
5349         if (enable_ept) {
5350                 eptp = construct_eptp(vcpu, cr3);
5351                 vmcs_write64(EPT_POINTER, eptp);
5352
5353                 if (kvm_x86_ops->tlb_remote_flush) {
5354                         spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
5355                         to_vmx(vcpu)->ept_pointer = eptp;
5356                         to_kvm_vmx(kvm)->ept_pointers_match
5357                                 = EPT_POINTERS_CHECK;
5358                         spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
5359                 }
5360
5361                 if (enable_unrestricted_guest || is_paging(vcpu) ||
5362                     is_guest_mode(vcpu))
5363                         guest_cr3 = kvm_read_cr3(vcpu);
5364                 else
5365                         guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
5366                 ept_load_pdptrs(vcpu);
5367         }
5368
5369         vmcs_writel(GUEST_CR3, guest_cr3);
5370 }
5371
5372 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
5373 {
5374         /*
5375          * Pass through host's Machine Check Enable value to hw_cr4, which
5376          * is in force while we are in guest mode.  Do not let guests control
5377          * this bit, even if host CR4.MCE == 0.
5378          */
5379         unsigned long hw_cr4;
5380
5381         hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
5382         if (enable_unrestricted_guest)
5383                 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
5384         else if (to_vmx(vcpu)->rmode.vm86_active)
5385                 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
5386         else
5387                 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
5388
5389         if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
5390                 if (cr4 & X86_CR4_UMIP) {
5391                         vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
5392                                 SECONDARY_EXEC_DESC);
5393                         hw_cr4 &= ~X86_CR4_UMIP;
5394                 } else if (!is_guest_mode(vcpu) ||
5395                         !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC))
5396                         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
5397                                         SECONDARY_EXEC_DESC);
5398         }
5399
5400         if (cr4 & X86_CR4_VMXE) {
5401                 /*
5402                  * To use VMXON (and later other VMX instructions), a guest
5403                  * must first be able to turn on cr4.VMXE (see handle_vmon()).
5404                  * So basically the check on whether to allow nested VMX
5405                  * is here.  We operate under the default treatment of SMM,
5406                  * so VMX cannot be enabled under SMM.
5407                  */
5408                 if (!nested_vmx_allowed(vcpu) || is_smm(vcpu))
5409                         return 1;
5410         }
5411
5412         if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
5413                 return 1;
5414
5415         vcpu->arch.cr4 = cr4;
5416
5417         if (!enable_unrestricted_guest) {
5418                 if (enable_ept) {
5419                         if (!is_paging(vcpu)) {
5420                                 hw_cr4 &= ~X86_CR4_PAE;
5421                                 hw_cr4 |= X86_CR4_PSE;
5422                         } else if (!(cr4 & X86_CR4_PAE)) {
5423                                 hw_cr4 &= ~X86_CR4_PAE;
5424                         }
5425                 }
5426
5427                 /*
5428                  * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
5429                  * hardware.  To emulate this behavior, SMEP/SMAP/PKU needs
5430                  * to be manually disabled when guest switches to non-paging
5431                  * mode.
5432                  *
5433                  * If !enable_unrestricted_guest, the CPU is always running
5434                  * with CR0.PG=1 and CR4 needs to be modified.
5435                  * If enable_unrestricted_guest, the CPU automatically
5436                  * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
5437                  */
5438                 if (!is_paging(vcpu))
5439                         hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
5440         }
5441
5442         vmcs_writel(CR4_READ_SHADOW, cr4);
5443         vmcs_writel(GUEST_CR4, hw_cr4);
5444         return 0;
5445 }
5446
5447 static void vmx_get_segment(struct kvm_vcpu *vcpu,
5448                             struct kvm_segment *var, int seg)
5449 {
5450         struct vcpu_vmx *vmx = to_vmx(vcpu);
5451         u32 ar;
5452
5453         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
5454                 *var = vmx->rmode.segs[seg];
5455                 if (seg == VCPU_SREG_TR
5456                     || var->selector == vmx_read_guest_seg_selector(vmx, seg))
5457                         return;
5458                 var->base = vmx_read_guest_seg_base(vmx, seg);
5459                 var->selector = vmx_read_guest_seg_selector(vmx, seg);
5460                 return;
5461         }
5462         var->base = vmx_read_guest_seg_base(vmx, seg);
5463         var->limit = vmx_read_guest_seg_limit(vmx, seg);
5464         var->selector = vmx_read_guest_seg_selector(vmx, seg);
5465         ar = vmx_read_guest_seg_ar(vmx, seg);
5466         var->unusable = (ar >> 16) & 1;
5467         var->type = ar & 15;
5468         var->s = (ar >> 4) & 1;
5469         var->dpl = (ar >> 5) & 3;
5470         /*
5471          * Some userspaces do not preserve unusable property. Since usable
5472          * segment has to be present according to VMX spec we can use present
5473          * property to amend userspace bug by making unusable segment always
5474          * nonpresent. vmx_segment_access_rights() already marks nonpresent
5475          * segment as unusable.
5476          */
5477         var->present = !var->unusable;
5478         var->avl = (ar >> 12) & 1;
5479         var->l = (ar >> 13) & 1;
5480         var->db = (ar >> 14) & 1;
5481         var->g = (ar >> 15) & 1;
5482 }
5483
5484 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
5485 {
5486         struct kvm_segment s;
5487
5488         if (to_vmx(vcpu)->rmode.vm86_active) {
5489                 vmx_get_segment(vcpu, &s, seg);
5490                 return s.base;
5491         }
5492         return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
5493 }
5494
5495 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
5496 {
5497         struct vcpu_vmx *vmx = to_vmx(vcpu);
5498
5499         if (unlikely(vmx->rmode.vm86_active))
5500                 return 0;
5501         else {
5502                 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
5503                 return VMX_AR_DPL(ar);
5504         }
5505 }
5506
5507 static u32 vmx_segment_access_rights(struct kvm_segment *var)
5508 {
5509         u32 ar;
5510
5511         if (var->unusable || !var->present)
5512                 ar = 1 << 16;
5513         else {
5514                 ar = var->type & 15;
5515                 ar |= (var->s & 1) << 4;
5516                 ar |= (var->dpl & 3) << 5;
5517                 ar |= (var->present & 1) << 7;
5518                 ar |= (var->avl & 1) << 12;
5519                 ar |= (var->l & 1) << 13;
5520                 ar |= (var->db & 1) << 14;
5521                 ar |= (var->g & 1) << 15;
5522         }
5523
5524         return ar;
5525 }
5526
5527 static void vmx_set_segment(struct kvm_vcpu *vcpu,
5528                             struct kvm_segment *var, int seg)
5529 {
5530         struct vcpu_vmx *vmx = to_vmx(vcpu);
5531         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
5532
5533         vmx_segment_cache_clear(vmx);
5534
5535         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
5536                 vmx->rmode.segs[seg] = *var;
5537                 if (seg == VCPU_SREG_TR)
5538                         vmcs_write16(sf->selector, var->selector);
5539                 else if (var->s)
5540                         fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
5541                 goto out;
5542         }
5543
5544         vmcs_writel(sf->base, var->base);
5545         vmcs_write32(sf->limit, var->limit);
5546         vmcs_write16(sf->selector, var->selector);
5547
5548         /*
5549          *   Fix the "Accessed" bit in AR field of segment registers for older
5550          * qemu binaries.
5551          *   IA32 arch specifies that at the time of processor reset the
5552          * "Accessed" bit in the AR field of segment registers is 1. And qemu
5553          * is setting it to 0 in the userland code. This causes invalid guest
5554          * state vmexit when "unrestricted guest" mode is turned on.
5555          *    Fix for this setup issue in cpu_reset is being pushed in the qemu
5556          * tree. Newer qemu binaries with that qemu fix would not need this
5557          * kvm hack.
5558          */
5559         if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
5560                 var->type |= 0x1; /* Accessed */
5561
5562         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
5563
5564 out:
5565         vmx->emulation_required = emulation_required(vcpu);
5566 }
5567
5568 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
5569 {
5570         u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
5571
5572         *db = (ar >> 14) & 1;
5573         *l = (ar >> 13) & 1;
5574 }
5575
5576 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5577 {
5578         dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
5579         dt->address = vmcs_readl(GUEST_IDTR_BASE);
5580 }
5581
5582 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5583 {
5584         vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
5585         vmcs_writel(GUEST_IDTR_BASE, dt->address);
5586 }
5587
5588 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5589 {
5590         dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
5591         dt->address = vmcs_readl(GUEST_GDTR_BASE);
5592 }
5593
5594 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5595 {
5596         vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
5597         vmcs_writel(GUEST_GDTR_BASE, dt->address);
5598 }
5599
5600 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
5601 {
5602         struct kvm_segment var;
5603         u32 ar;
5604
5605         vmx_get_segment(vcpu, &var, seg);
5606         var.dpl = 0x3;
5607         if (seg == VCPU_SREG_CS)
5608                 var.type = 0x3;
5609         ar = vmx_segment_access_rights(&var);
5610
5611         if (var.base != (var.selector << 4))
5612                 return false;
5613         if (var.limit != 0xffff)
5614                 return false;
5615         if (ar != 0xf3)
5616                 return false;
5617
5618         return true;
5619 }
5620
5621 static bool code_segment_valid(struct kvm_vcpu *vcpu)
5622 {
5623         struct kvm_segment cs;
5624         unsigned int cs_rpl;
5625
5626         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5627         cs_rpl = cs.selector & SEGMENT_RPL_MASK;
5628
5629         if (cs.unusable)
5630                 return false;
5631         if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
5632                 return false;
5633         if (!cs.s)
5634                 return false;
5635         if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
5636                 if (cs.dpl > cs_rpl)
5637                         return false;
5638         } else {
5639                 if (cs.dpl != cs_rpl)
5640                         return false;
5641         }
5642         if (!cs.present)
5643                 return false;
5644
5645         /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
5646         return true;
5647 }
5648
5649 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
5650 {
5651         struct kvm_segment ss;
5652         unsigned int ss_rpl;
5653
5654         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
5655         ss_rpl = ss.selector & SEGMENT_RPL_MASK;
5656
5657         if (ss.unusable)
5658                 return true;
5659         if (ss.type != 3 && ss.type != 7)
5660                 return false;
5661         if (!ss.s)
5662                 return false;
5663         if (ss.dpl != ss_rpl) /* DPL != RPL */
5664                 return false;
5665         if (!ss.present)
5666                 return false;
5667
5668         return true;
5669 }
5670
5671 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
5672 {
5673         struct kvm_segment var;
5674         unsigned int rpl;
5675
5676         vmx_get_segment(vcpu, &var, seg);
5677         rpl = var.selector & SEGMENT_RPL_MASK;
5678
5679         if (var.unusable)
5680                 return true;
5681         if (!var.s)
5682                 return false;
5683         if (!var.present)
5684                 return false;
5685         if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
5686                 if (var.dpl < rpl) /* DPL < RPL */
5687                         return false;
5688         }
5689
5690         /* TODO: Add other members to kvm_segment_field to allow checking for other access
5691          * rights flags
5692          */
5693         return true;
5694 }
5695
5696 static bool tr_valid(struct kvm_vcpu *vcpu)
5697 {
5698         struct kvm_segment tr;
5699
5700         vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
5701
5702         if (tr.unusable)
5703                 return false;
5704         if (tr.selector & SEGMENT_TI_MASK)      /* TI = 1 */
5705                 return false;
5706         if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
5707                 return false;
5708         if (!tr.present)
5709                 return false;
5710
5711         return true;
5712 }
5713
5714 static bool ldtr_valid(struct kvm_vcpu *vcpu)
5715 {
5716         struct kvm_segment ldtr;
5717
5718         vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
5719
5720         if (ldtr.unusable)
5721                 return true;
5722         if (ldtr.selector & SEGMENT_TI_MASK)    /* TI = 1 */
5723                 return false;
5724         if (ldtr.type != 2)
5725                 return false;
5726         if (!ldtr.present)
5727                 return false;
5728
5729         return true;
5730 }
5731
5732 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
5733 {
5734         struct kvm_segment cs, ss;
5735
5736         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5737         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
5738
5739         return ((cs.selector & SEGMENT_RPL_MASK) ==
5740                  (ss.selector & SEGMENT_RPL_MASK));
5741 }
5742
5743 /*
5744  * Check if guest state is valid. Returns true if valid, false if
5745  * not.
5746  * We assume that registers are always usable
5747  */
5748 static bool guest_state_valid(struct kvm_vcpu *vcpu)
5749 {
5750         if (enable_unrestricted_guest)
5751                 return true;
5752
5753         /* real mode guest state checks */
5754         if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
5755                 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
5756                         return false;
5757                 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
5758                         return false;
5759                 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
5760                         return false;
5761                 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
5762                         return false;
5763                 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
5764                         return false;
5765                 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
5766                         return false;
5767         } else {
5768         /* protected mode guest state checks */
5769                 if (!cs_ss_rpl_check(vcpu))
5770                         return false;
5771                 if (!code_segment_valid(vcpu))
5772                         return false;
5773                 if (!stack_segment_valid(vcpu))
5774                         return false;
5775                 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
5776                         return false;
5777                 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
5778                         return false;
5779                 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
5780                         return false;
5781                 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
5782                         return false;
5783                 if (!tr_valid(vcpu))
5784                         return false;
5785                 if (!ldtr_valid(vcpu))
5786                         return false;
5787         }
5788         /* TODO:
5789          * - Add checks on RIP
5790          * - Add checks on RFLAGS
5791          */
5792
5793         return true;
5794 }
5795
5796 static bool page_address_valid(struct kvm_vcpu *vcpu, gpa_t gpa)
5797 {
5798         return PAGE_ALIGNED(gpa) && !(gpa >> cpuid_maxphyaddr(vcpu));
5799 }
5800
5801 static int init_rmode_tss(struct kvm *kvm)
5802 {
5803         gfn_t fn;
5804         u16 data = 0;
5805         int idx, r;
5806
5807         idx = srcu_read_lock(&kvm->srcu);
5808         fn = to_kvm_vmx(kvm)->tss_addr >> PAGE_SHIFT;
5809         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
5810         if (r < 0)
5811                 goto out;
5812         data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
5813         r = kvm_write_guest_page(kvm, fn++, &data,
5814                         TSS_IOPB_BASE_OFFSET, sizeof(u16));
5815         if (r < 0)
5816                 goto out;
5817         r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
5818         if (r < 0)
5819                 goto out;
5820         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
5821         if (r < 0)
5822                 goto out;
5823         data = ~0;
5824         r = kvm_write_guest_page(kvm, fn, &data,
5825                                  RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
5826                                  sizeof(u8));
5827 out:
5828         srcu_read_unlock(&kvm->srcu, idx);
5829         return r;
5830 }
5831
5832 static int init_rmode_identity_map(struct kvm *kvm)
5833 {
5834         struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
5835         int i, idx, r = 0;
5836         kvm_pfn_t identity_map_pfn;
5837         u32 tmp;
5838
5839         /* Protect kvm_vmx->ept_identity_pagetable_done. */
5840         mutex_lock(&kvm->slots_lock);
5841
5842         if (likely(kvm_vmx->ept_identity_pagetable_done))
5843                 goto out2;
5844
5845         if (!kvm_vmx->ept_identity_map_addr)
5846                 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
5847         identity_map_pfn = kvm_vmx->ept_identity_map_addr >> PAGE_SHIFT;
5848
5849         r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
5850                                     kvm_vmx->ept_identity_map_addr, PAGE_SIZE);
5851         if (r < 0)
5852                 goto out2;
5853
5854         idx = srcu_read_lock(&kvm->srcu);
5855         r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
5856         if (r < 0)
5857                 goto out;
5858         /* Set up identity-mapping pagetable for EPT in real mode */
5859         for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
5860                 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
5861                         _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
5862                 r = kvm_write_guest_page(kvm, identity_map_pfn,
5863                                 &tmp, i * sizeof(tmp), sizeof(tmp));
5864                 if (r < 0)
5865                         goto out;
5866         }
5867         kvm_vmx->ept_identity_pagetable_done = true;
5868
5869 out:
5870         srcu_read_unlock(&kvm->srcu, idx);
5871
5872 out2:
5873         mutex_unlock(&kvm->slots_lock);
5874         return r;
5875 }
5876
5877 static void seg_setup(int seg)
5878 {
5879         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
5880         unsigned int ar;
5881
5882         vmcs_write16(sf->selector, 0);
5883         vmcs_writel(sf->base, 0);
5884         vmcs_write32(sf->limit, 0xffff);
5885         ar = 0x93;
5886         if (seg == VCPU_SREG_CS)
5887                 ar |= 0x08; /* code segment */
5888
5889         vmcs_write32(sf->ar_bytes, ar);
5890 }
5891
5892 static int alloc_apic_access_page(struct kvm *kvm)
5893 {
5894         struct page *page;
5895         int r = 0;
5896
5897         mutex_lock(&kvm->slots_lock);
5898         if (kvm->arch.apic_access_page_done)
5899                 goto out;
5900         r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
5901                                     APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
5902         if (r)
5903                 goto out;
5904
5905         page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
5906         if (is_error_page(page)) {
5907                 r = -EFAULT;
5908                 goto out;
5909         }
5910
5911         /*
5912          * Do not pin the page in memory, so that memory hot-unplug
5913          * is able to migrate it.
5914          */
5915         put_page(page);
5916         kvm->arch.apic_access_page_done = true;
5917 out:
5918         mutex_unlock(&kvm->slots_lock);
5919         return r;
5920 }
5921
5922 static int allocate_vpid(void)
5923 {
5924         int vpid;
5925
5926         if (!enable_vpid)
5927                 return 0;
5928         spin_lock(&vmx_vpid_lock);
5929         vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
5930         if (vpid < VMX_NR_VPIDS)
5931                 __set_bit(vpid, vmx_vpid_bitmap);
5932         else
5933                 vpid = 0;
5934         spin_unlock(&vmx_vpid_lock);
5935         return vpid;
5936 }
5937
5938 static void free_vpid(int vpid)
5939 {
5940         if (!enable_vpid || vpid == 0)
5941                 return;
5942         spin_lock(&vmx_vpid_lock);
5943         __clear_bit(vpid, vmx_vpid_bitmap);
5944         spin_unlock(&vmx_vpid_lock);
5945 }
5946
5947 static void __always_inline vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
5948                                                           u32 msr, int type)
5949 {
5950         int f = sizeof(unsigned long);
5951
5952         if (!cpu_has_vmx_msr_bitmap())
5953                 return;
5954
5955         if (static_branch_unlikely(&enable_evmcs))
5956                 evmcs_touch_msr_bitmap();
5957
5958         /*
5959          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5960          * have the write-low and read-high bitmap offsets the wrong way round.
5961          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5962          */
5963         if (msr <= 0x1fff) {
5964                 if (type & MSR_TYPE_R)
5965                         /* read-low */
5966                         __clear_bit(msr, msr_bitmap + 0x000 / f);
5967
5968                 if (type & MSR_TYPE_W)
5969                         /* write-low */
5970                         __clear_bit(msr, msr_bitmap + 0x800 / f);
5971
5972         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5973                 msr &= 0x1fff;
5974                 if (type & MSR_TYPE_R)
5975                         /* read-high */
5976                         __clear_bit(msr, msr_bitmap + 0x400 / f);
5977
5978                 if (type & MSR_TYPE_W)
5979                         /* write-high */
5980                         __clear_bit(msr, msr_bitmap + 0xc00 / f);
5981
5982         }
5983 }
5984
5985 static void __always_inline vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
5986                                                          u32 msr, int type)
5987 {
5988         int f = sizeof(unsigned long);
5989
5990         if (!cpu_has_vmx_msr_bitmap())
5991                 return;
5992
5993         if (static_branch_unlikely(&enable_evmcs))
5994                 evmcs_touch_msr_bitmap();
5995
5996         /*
5997          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5998          * have the write-low and read-high bitmap offsets the wrong way round.
5999          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
6000          */
6001         if (msr <= 0x1fff) {
6002                 if (type & MSR_TYPE_R)
6003                         /* read-low */
6004                         __set_bit(msr, msr_bitmap + 0x000 / f);
6005
6006                 if (type & MSR_TYPE_W)
6007                         /* write-low */
6008                         __set_bit(msr, msr_bitmap + 0x800 / f);
6009
6010         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
6011                 msr &= 0x1fff;
6012                 if (type & MSR_TYPE_R)
6013                         /* read-high */
6014                         __set_bit(msr, msr_bitmap + 0x400 / f);
6015
6016                 if (type & MSR_TYPE_W)
6017                         /* write-high */
6018                         __set_bit(msr, msr_bitmap + 0xc00 / f);
6019
6020         }
6021 }
6022
6023 static void __always_inline vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
6024                                                       u32 msr, int type, bool value)
6025 {
6026         if (value)
6027                 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
6028         else
6029                 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
6030 }
6031
6032 /*
6033  * If a msr is allowed by L0, we should check whether it is allowed by L1.
6034  * The corresponding bit will be cleared unless both of L0 and L1 allow it.
6035  */
6036 static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
6037                                                unsigned long *msr_bitmap_nested,
6038                                                u32 msr, int type)
6039 {
6040         int f = sizeof(unsigned long);
6041
6042         /*
6043          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
6044          * have the write-low and read-high bitmap offsets the wrong way round.
6045          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
6046          */
6047         if (msr <= 0x1fff) {
6048                 if (type & MSR_TYPE_R &&
6049                    !test_bit(msr, msr_bitmap_l1 + 0x000 / f))
6050                         /* read-low */
6051                         __clear_bit(msr, msr_bitmap_nested + 0x000 / f);
6052
6053                 if (type & MSR_TYPE_W &&
6054                    !test_bit(msr, msr_bitmap_l1 + 0x800 / f))
6055                         /* write-low */
6056                         __clear_bit(msr, msr_bitmap_nested + 0x800 / f);
6057
6058         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
6059                 msr &= 0x1fff;
6060                 if (type & MSR_TYPE_R &&
6061                    !test_bit(msr, msr_bitmap_l1 + 0x400 / f))
6062                         /* read-high */
6063                         __clear_bit(msr, msr_bitmap_nested + 0x400 / f);
6064
6065                 if (type & MSR_TYPE_W &&
6066                    !test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
6067                         /* write-high */
6068                         __clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
6069
6070         }
6071 }
6072
6073 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
6074 {
6075         u8 mode = 0;
6076
6077         if (cpu_has_secondary_exec_ctrls() &&
6078             (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
6079              SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
6080                 mode |= MSR_BITMAP_MODE_X2APIC;
6081                 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
6082                         mode |= MSR_BITMAP_MODE_X2APIC_APICV;
6083         }
6084
6085         return mode;
6086 }
6087
6088 #define X2APIC_MSR(r) (APIC_BASE_MSR + ((r) >> 4))
6089
6090 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
6091                                          u8 mode)
6092 {
6093         int msr;
6094
6095         for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
6096                 unsigned word = msr / BITS_PER_LONG;
6097                 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
6098                 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
6099         }
6100
6101         if (mode & MSR_BITMAP_MODE_X2APIC) {
6102                 /*
6103                  * TPR reads and writes can be virtualized even if virtual interrupt
6104                  * delivery is not in use.
6105                  */
6106                 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
6107                 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
6108                         vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
6109                         vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
6110                         vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
6111                 }
6112         }
6113 }
6114
6115 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
6116 {
6117         struct vcpu_vmx *vmx = to_vmx(vcpu);
6118         unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
6119         u8 mode = vmx_msr_bitmap_mode(vcpu);
6120         u8 changed = mode ^ vmx->msr_bitmap_mode;
6121
6122         if (!changed)
6123                 return;
6124
6125         if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
6126                 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
6127
6128         vmx->msr_bitmap_mode = mode;
6129 }
6130
6131 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
6132 {
6133         return enable_apicv;
6134 }
6135
6136 static void nested_mark_vmcs12_pages_dirty(struct kvm_vcpu *vcpu)
6137 {
6138         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6139         gfn_t gfn;
6140
6141         /*
6142          * Don't need to mark the APIC access page dirty; it is never
6143          * written to by the CPU during APIC virtualization.
6144          */
6145
6146         if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
6147                 gfn = vmcs12->virtual_apic_page_addr >> PAGE_SHIFT;
6148                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
6149         }
6150
6151         if (nested_cpu_has_posted_intr(vmcs12)) {
6152                 gfn = vmcs12->posted_intr_desc_addr >> PAGE_SHIFT;
6153                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
6154         }
6155 }
6156
6157
6158 static void vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
6159 {
6160         struct vcpu_vmx *vmx = to_vmx(vcpu);
6161         int max_irr;
6162         void *vapic_page;
6163         u16 status;
6164
6165         if (!vmx->nested.pi_desc || !vmx->nested.pi_pending)
6166                 return;
6167
6168         vmx->nested.pi_pending = false;
6169         if (!pi_test_and_clear_on(vmx->nested.pi_desc))
6170                 return;
6171
6172         max_irr = find_last_bit((unsigned long *)vmx->nested.pi_desc->pir, 256);
6173         if (max_irr != 256) {
6174                 vapic_page = kmap(vmx->nested.virtual_apic_page);
6175                 __kvm_apic_update_irr(vmx->nested.pi_desc->pir,
6176                         vapic_page, &max_irr);
6177                 kunmap(vmx->nested.virtual_apic_page);
6178
6179                 status = vmcs_read16(GUEST_INTR_STATUS);
6180                 if ((u8)max_irr > ((u8)status & 0xff)) {
6181                         status &= ~0xff;
6182                         status |= (u8)max_irr;
6183                         vmcs_write16(GUEST_INTR_STATUS, status);
6184                 }
6185         }
6186
6187         nested_mark_vmcs12_pages_dirty(vcpu);
6188 }
6189
6190 static u8 vmx_get_rvi(void)
6191 {
6192         return vmcs_read16(GUEST_INTR_STATUS) & 0xff;
6193 }
6194
6195 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
6196 {
6197         struct vcpu_vmx *vmx = to_vmx(vcpu);
6198         void *vapic_page;
6199         u32 vppr;
6200         int rvi;
6201
6202         if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
6203                 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
6204                 WARN_ON_ONCE(!vmx->nested.virtual_apic_page))
6205                 return false;
6206
6207         rvi = vmx_get_rvi();
6208
6209         vapic_page = kmap(vmx->nested.virtual_apic_page);
6210         vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
6211         kunmap(vmx->nested.virtual_apic_page);
6212
6213         return ((rvi & 0xf0) > (vppr & 0xf0));
6214 }
6215
6216 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
6217                                                      bool nested)
6218 {
6219 #ifdef CONFIG_SMP
6220         int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
6221
6222         if (vcpu->mode == IN_GUEST_MODE) {
6223                 /*
6224                  * The vector of interrupt to be delivered to vcpu had
6225                  * been set in PIR before this function.
6226                  *
6227                  * Following cases will be reached in this block, and
6228                  * we always send a notification event in all cases as
6229                  * explained below.
6230                  *
6231                  * Case 1: vcpu keeps in non-root mode. Sending a
6232                  * notification event posts the interrupt to vcpu.
6233                  *
6234                  * Case 2: vcpu exits to root mode and is still
6235                  * runnable. PIR will be synced to vIRR before the
6236                  * next vcpu entry. Sending a notification event in
6237                  * this case has no effect, as vcpu is not in root
6238                  * mode.
6239                  *
6240                  * Case 3: vcpu exits to root mode and is blocked.
6241                  * vcpu_block() has already synced PIR to vIRR and
6242                  * never blocks vcpu if vIRR is not cleared. Therefore,
6243                  * a blocked vcpu here does not wait for any requested
6244                  * interrupts in PIR, and sending a notification event
6245                  * which has no effect is safe here.
6246                  */
6247
6248                 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
6249                 return true;
6250         }
6251 #endif
6252         return false;
6253 }
6254
6255 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
6256                                                 int vector)
6257 {
6258         struct vcpu_vmx *vmx = to_vmx(vcpu);
6259
6260         if (is_guest_mode(vcpu) &&
6261             vector == vmx->nested.posted_intr_nv) {
6262                 /*
6263                  * If a posted intr is not recognized by hardware,
6264                  * we will accomplish it in the next vmentry.
6265                  */
6266                 vmx->nested.pi_pending = true;
6267                 kvm_make_request(KVM_REQ_EVENT, vcpu);
6268                 /* the PIR and ON have been set by L1. */
6269                 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
6270                         kvm_vcpu_kick(vcpu);
6271                 return 0;
6272         }
6273         return -1;
6274 }
6275 /*
6276  * Send interrupt to vcpu via posted interrupt way.
6277  * 1. If target vcpu is running(non-root mode), send posted interrupt
6278  * notification to vcpu and hardware will sync PIR to vIRR atomically.
6279  * 2. If target vcpu isn't running(root mode), kick it to pick up the
6280  * interrupt from PIR in next vmentry.
6281  */
6282 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
6283 {
6284         struct vcpu_vmx *vmx = to_vmx(vcpu);
6285         int r;
6286
6287         r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
6288         if (!r)
6289                 return;
6290
6291         if (pi_test_and_set_pir(vector, &vmx->pi_desc))
6292                 return;
6293
6294         /* If a previous notification has sent the IPI, nothing to do.  */
6295         if (pi_test_and_set_on(&vmx->pi_desc))
6296                 return;
6297
6298         if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
6299                 kvm_vcpu_kick(vcpu);
6300 }
6301
6302 /*
6303  * Set up the vmcs's constant host-state fields, i.e., host-state fields that
6304  * will not change in the lifetime of the guest.
6305  * Note that host-state that does change is set elsewhere. E.g., host-state
6306  * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
6307  */
6308 static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
6309 {
6310         u32 low32, high32;
6311         unsigned long tmpl;
6312         struct desc_ptr dt;
6313         unsigned long cr0, cr3, cr4;
6314
6315         cr0 = read_cr0();
6316         WARN_ON(cr0 & X86_CR0_TS);
6317         vmcs_writel(HOST_CR0, cr0);  /* 22.2.3 */
6318
6319         /*
6320          * Save the most likely value for this task's CR3 in the VMCS.
6321          * We can't use __get_current_cr3_fast() because we're not atomic.
6322          */
6323         cr3 = __read_cr3();
6324         vmcs_writel(HOST_CR3, cr3);             /* 22.2.3  FIXME: shadow tables */
6325         vmx->loaded_vmcs->host_state.cr3 = cr3;
6326
6327         /* Save the most likely value for this task's CR4 in the VMCS. */
6328         cr4 = cr4_read_shadow();
6329         vmcs_writel(HOST_CR4, cr4);                     /* 22.2.3, 22.2.5 */
6330         vmx->loaded_vmcs->host_state.cr4 = cr4;
6331
6332         vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
6333 #ifdef CONFIG_X86_64
6334         /*
6335          * Load null selectors, so we can avoid reloading them in
6336          * vmx_prepare_switch_to_host(), in case userspace uses
6337          * the null selectors too (the expected case).
6338          */
6339         vmcs_write16(HOST_DS_SELECTOR, 0);
6340         vmcs_write16(HOST_ES_SELECTOR, 0);
6341 #else
6342         vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
6343         vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
6344 #endif
6345         vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
6346         vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
6347
6348         store_idt(&dt);
6349         vmcs_writel(HOST_IDTR_BASE, dt.address);   /* 22.2.4 */
6350         vmx->host_idt_base = dt.address;
6351
6352         vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
6353
6354         rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
6355         vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
6356         rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
6357         vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl);   /* 22.2.3 */
6358
6359         if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
6360                 rdmsr(MSR_IA32_CR_PAT, low32, high32);
6361                 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
6362         }
6363
6364         if (cpu_has_load_ia32_efer)
6365                 vmcs_write64(HOST_IA32_EFER, host_efer);
6366 }
6367
6368 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
6369 {
6370         vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
6371         if (enable_ept)
6372                 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
6373         if (is_guest_mode(&vmx->vcpu))
6374                 vmx->vcpu.arch.cr4_guest_owned_bits &=
6375                         ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
6376         vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
6377 }
6378
6379 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
6380 {
6381         u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
6382
6383         if (!kvm_vcpu_apicv_active(&vmx->vcpu))
6384                 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
6385
6386         if (!enable_vnmi)
6387                 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
6388
6389         /* Enable the preemption timer dynamically */
6390         pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
6391         return pin_based_exec_ctrl;
6392 }
6393
6394 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
6395 {
6396         struct vcpu_vmx *vmx = to_vmx(vcpu);
6397
6398         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
6399         if (cpu_has_secondary_exec_ctrls()) {
6400                 if (kvm_vcpu_apicv_active(vcpu))
6401                         vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
6402                                       SECONDARY_EXEC_APIC_REGISTER_VIRT |
6403                                       SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6404                 else
6405                         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
6406                                         SECONDARY_EXEC_APIC_REGISTER_VIRT |
6407                                         SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6408         }
6409
6410         if (cpu_has_vmx_msr_bitmap())
6411                 vmx_update_msr_bitmap(vcpu);
6412 }
6413
6414 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
6415 {
6416         u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
6417
6418         if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
6419                 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
6420
6421         if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
6422                 exec_control &= ~CPU_BASED_TPR_SHADOW;
6423 #ifdef CONFIG_X86_64
6424                 exec_control |= CPU_BASED_CR8_STORE_EXITING |
6425                                 CPU_BASED_CR8_LOAD_EXITING;
6426 #endif
6427         }
6428         if (!enable_ept)
6429                 exec_control |= CPU_BASED_CR3_STORE_EXITING |
6430                                 CPU_BASED_CR3_LOAD_EXITING  |
6431                                 CPU_BASED_INVLPG_EXITING;
6432         if (kvm_mwait_in_guest(vmx->vcpu.kvm))
6433                 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
6434                                 CPU_BASED_MONITOR_EXITING);
6435         if (kvm_hlt_in_guest(vmx->vcpu.kvm))
6436                 exec_control &= ~CPU_BASED_HLT_EXITING;
6437         return exec_control;
6438 }
6439
6440 static bool vmx_rdrand_supported(void)
6441 {
6442         return vmcs_config.cpu_based_2nd_exec_ctrl &
6443                 SECONDARY_EXEC_RDRAND_EXITING;
6444 }
6445
6446 static bool vmx_rdseed_supported(void)
6447 {
6448         return vmcs_config.cpu_based_2nd_exec_ctrl &
6449                 SECONDARY_EXEC_RDSEED_EXITING;
6450 }
6451
6452 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
6453 {
6454         struct kvm_vcpu *vcpu = &vmx->vcpu;
6455
6456         u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
6457
6458         if (!cpu_need_virtualize_apic_accesses(vcpu))
6459                 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6460         if (vmx->vpid == 0)
6461                 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
6462         if (!enable_ept) {
6463                 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
6464                 enable_unrestricted_guest = 0;
6465         }
6466         if (!enable_unrestricted_guest)
6467                 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
6468         if (kvm_pause_in_guest(vmx->vcpu.kvm))
6469                 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
6470         if (!kvm_vcpu_apicv_active(vcpu))
6471                 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
6472                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6473         exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6474
6475         /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
6476          * in vmx_set_cr4.  */
6477         exec_control &= ~SECONDARY_EXEC_DESC;
6478
6479         /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
6480            (handle_vmptrld).
6481            We can NOT enable shadow_vmcs here because we don't have yet
6482            a current VMCS12
6483         */
6484         exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
6485
6486         if (!enable_pml)
6487                 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
6488
6489         if (vmx_xsaves_supported()) {
6490                 /* Exposing XSAVES only when XSAVE is exposed */
6491                 bool xsaves_enabled =
6492                         guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
6493                         guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
6494
6495                 if (!xsaves_enabled)
6496                         exec_control &= ~SECONDARY_EXEC_XSAVES;
6497
6498                 if (nested) {
6499                         if (xsaves_enabled)
6500                                 vmx->nested.msrs.secondary_ctls_high |=
6501                                         SECONDARY_EXEC_XSAVES;
6502                         else
6503                                 vmx->nested.msrs.secondary_ctls_high &=
6504                                         ~SECONDARY_EXEC_XSAVES;
6505                 }
6506         }
6507
6508         if (vmx_rdtscp_supported()) {
6509                 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
6510                 if (!rdtscp_enabled)
6511                         exec_control &= ~SECONDARY_EXEC_RDTSCP;
6512
6513                 if (nested) {
6514                         if (rdtscp_enabled)
6515                                 vmx->nested.msrs.secondary_ctls_high |=
6516                                         SECONDARY_EXEC_RDTSCP;
6517                         else
6518                                 vmx->nested.msrs.secondary_ctls_high &=
6519                                         ~SECONDARY_EXEC_RDTSCP;
6520                 }
6521         }
6522
6523         if (vmx_invpcid_supported()) {
6524                 /* Exposing INVPCID only when PCID is exposed */
6525                 bool invpcid_enabled =
6526                         guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
6527                         guest_cpuid_has(vcpu, X86_FEATURE_PCID);
6528
6529                 if (!invpcid_enabled) {
6530                         exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
6531                         guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
6532                 }
6533
6534                 if (nested) {
6535                         if (invpcid_enabled)
6536                                 vmx->nested.msrs.secondary_ctls_high |=
6537                                         SECONDARY_EXEC_ENABLE_INVPCID;
6538                         else
6539                                 vmx->nested.msrs.secondary_ctls_high &=
6540                                         ~SECONDARY_EXEC_ENABLE_INVPCID;
6541                 }
6542         }
6543
6544         if (vmx_rdrand_supported()) {
6545                 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
6546                 if (rdrand_enabled)
6547                         exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
6548
6549                 if (nested) {
6550                         if (rdrand_enabled)
6551                                 vmx->nested.msrs.secondary_ctls_high |=
6552                                         SECONDARY_EXEC_RDRAND_EXITING;
6553                         else
6554                                 vmx->nested.msrs.secondary_ctls_high &=
6555                                         ~SECONDARY_EXEC_RDRAND_EXITING;
6556                 }
6557         }
6558
6559         if (vmx_rdseed_supported()) {
6560                 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
6561                 if (rdseed_enabled)
6562                         exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
6563
6564                 if (nested) {
6565                         if (rdseed_enabled)
6566                                 vmx->nested.msrs.secondary_ctls_high |=
6567                                         SECONDARY_EXEC_RDSEED_EXITING;
6568                         else
6569                                 vmx->nested.msrs.secondary_ctls_high &=
6570                                         ~SECONDARY_EXEC_RDSEED_EXITING;
6571                 }
6572         }
6573
6574         vmx->secondary_exec_control = exec_control;
6575 }
6576
6577 static void ept_set_mmio_spte_mask(void)
6578 {
6579         /*
6580          * EPT Misconfigurations can be generated if the value of bits 2:0
6581          * of an EPT paging-structure entry is 110b (write/execute).
6582          */
6583         kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
6584                                    VMX_EPT_MISCONFIG_WX_VALUE);
6585 }
6586
6587 #define VMX_XSS_EXIT_BITMAP 0
6588 /*
6589  * Sets up the vmcs for emulated real mode.
6590  */
6591 static void vmx_vcpu_setup(struct vcpu_vmx *vmx)
6592 {
6593         int i;
6594
6595         if (enable_shadow_vmcs) {
6596                 /*
6597                  * At vCPU creation, "VMWRITE to any supported field
6598                  * in the VMCS" is supported, so use the more
6599                  * permissive vmx_vmread_bitmap to specify both read
6600                  * and write permissions for the shadow VMCS.
6601                  */
6602                 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
6603                 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmread_bitmap));
6604         }
6605         if (cpu_has_vmx_msr_bitmap())
6606                 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
6607
6608         vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
6609
6610         /* Control */
6611         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
6612         vmx->hv_deadline_tsc = -1;
6613
6614         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
6615
6616         if (cpu_has_secondary_exec_ctrls()) {
6617                 vmx_compute_secondary_exec_control(vmx);
6618                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
6619                              vmx->secondary_exec_control);
6620         }
6621
6622         if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
6623                 vmcs_write64(EOI_EXIT_BITMAP0, 0);
6624                 vmcs_write64(EOI_EXIT_BITMAP1, 0);
6625                 vmcs_write64(EOI_EXIT_BITMAP2, 0);
6626                 vmcs_write64(EOI_EXIT_BITMAP3, 0);
6627
6628                 vmcs_write16(GUEST_INTR_STATUS, 0);
6629
6630                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
6631                 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
6632         }
6633
6634         if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
6635                 vmcs_write32(PLE_GAP, ple_gap);
6636                 vmx->ple_window = ple_window;
6637                 vmx->ple_window_dirty = true;
6638         }
6639
6640         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
6641         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
6642         vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
6643
6644         vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
6645         vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
6646         vmx_set_constant_host_state(vmx);
6647         vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
6648         vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
6649
6650         if (cpu_has_vmx_vmfunc())
6651                 vmcs_write64(VM_FUNCTION_CONTROL, 0);
6652
6653         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
6654         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
6655         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
6656         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
6657         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
6658
6659         if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
6660                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
6661
6662         for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
6663                 u32 index = vmx_msr_index[i];
6664                 u32 data_low, data_high;
6665                 int j = vmx->nmsrs;
6666
6667                 if (rdmsr_safe(index, &data_low, &data_high) < 0)
6668                         continue;
6669                 if (wrmsr_safe(index, data_low, data_high) < 0)
6670                         continue;
6671                 vmx->guest_msrs[j].index = i;
6672                 vmx->guest_msrs[j].data = 0;
6673                 vmx->guest_msrs[j].mask = -1ull;
6674                 ++vmx->nmsrs;
6675         }
6676
6677         vmx->arch_capabilities = kvm_get_arch_capabilities();
6678
6679         vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
6680
6681         /* 22.2.1, 20.8.1 */
6682         vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
6683
6684         vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
6685         vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
6686
6687         set_cr4_guest_host_mask(vmx);
6688
6689         if (vmx_xsaves_supported())
6690                 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
6691
6692         if (enable_pml) {
6693                 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
6694                 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
6695         }
6696
6697         if (cpu_has_vmx_encls_vmexit())
6698                 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
6699 }
6700
6701 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
6702 {
6703         struct vcpu_vmx *vmx = to_vmx(vcpu);
6704         struct msr_data apic_base_msr;
6705         u64 cr0;
6706
6707         vmx->rmode.vm86_active = 0;
6708         vmx->spec_ctrl = 0;
6709
6710         vcpu->arch.microcode_version = 0x100000000ULL;
6711         vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
6712         kvm_set_cr8(vcpu, 0);
6713
6714         if (!init_event) {
6715                 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
6716                                      MSR_IA32_APICBASE_ENABLE;
6717                 if (kvm_vcpu_is_reset_bsp(vcpu))
6718                         apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
6719                 apic_base_msr.host_initiated = true;
6720                 kvm_set_apic_base(vcpu, &apic_base_msr);
6721         }
6722
6723         vmx_segment_cache_clear(vmx);
6724
6725         seg_setup(VCPU_SREG_CS);
6726         vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
6727         vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
6728
6729         seg_setup(VCPU_SREG_DS);
6730         seg_setup(VCPU_SREG_ES);
6731         seg_setup(VCPU_SREG_FS);
6732         seg_setup(VCPU_SREG_GS);
6733         seg_setup(VCPU_SREG_SS);
6734
6735         vmcs_write16(GUEST_TR_SELECTOR, 0);
6736         vmcs_writel(GUEST_TR_BASE, 0);
6737         vmcs_write32(GUEST_TR_LIMIT, 0xffff);
6738         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
6739
6740         vmcs_write16(GUEST_LDTR_SELECTOR, 0);
6741         vmcs_writel(GUEST_LDTR_BASE, 0);
6742         vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
6743         vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
6744
6745         if (!init_event) {
6746                 vmcs_write32(GUEST_SYSENTER_CS, 0);
6747                 vmcs_writel(GUEST_SYSENTER_ESP, 0);
6748                 vmcs_writel(GUEST_SYSENTER_EIP, 0);
6749                 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
6750         }
6751
6752         kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
6753         kvm_rip_write(vcpu, 0xfff0);
6754
6755         vmcs_writel(GUEST_GDTR_BASE, 0);
6756         vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
6757
6758         vmcs_writel(GUEST_IDTR_BASE, 0);
6759         vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
6760
6761         vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
6762         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
6763         vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
6764         if (kvm_mpx_supported())
6765                 vmcs_write64(GUEST_BNDCFGS, 0);
6766
6767         setup_msrs(vmx);
6768
6769         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
6770
6771         if (cpu_has_vmx_tpr_shadow() && !init_event) {
6772                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
6773                 if (cpu_need_tpr_shadow(vcpu))
6774                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
6775                                      __pa(vcpu->arch.apic->regs));
6776                 vmcs_write32(TPR_THRESHOLD, 0);
6777         }
6778
6779         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6780
6781         if (vmx->vpid != 0)
6782                 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
6783
6784         cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
6785         vmx->vcpu.arch.cr0 = cr0;
6786         vmx_set_cr0(vcpu, cr0); /* enter rmode */
6787         vmx_set_cr4(vcpu, 0);
6788         vmx_set_efer(vcpu, 0);
6789
6790         update_exception_bitmap(vcpu);
6791
6792         vpid_sync_context(vmx->vpid);
6793         if (init_event)
6794                 vmx_clear_hlt(vcpu);
6795 }
6796
6797 /*
6798  * In nested virtualization, check if L1 asked to exit on external interrupts.
6799  * For most existing hypervisors, this will always return true.
6800  */
6801 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
6802 {
6803         return get_vmcs12(vcpu)->pin_based_vm_exec_control &
6804                 PIN_BASED_EXT_INTR_MASK;
6805 }
6806
6807 /*
6808  * In nested virtualization, check if L1 has set
6809  * VM_EXIT_ACK_INTR_ON_EXIT
6810  */
6811 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
6812 {
6813         return get_vmcs12(vcpu)->vm_exit_controls &
6814                 VM_EXIT_ACK_INTR_ON_EXIT;
6815 }
6816
6817 static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
6818 {
6819         return nested_cpu_has_nmi_exiting(get_vmcs12(vcpu));
6820 }
6821
6822 static void enable_irq_window(struct kvm_vcpu *vcpu)
6823 {
6824         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
6825                       CPU_BASED_VIRTUAL_INTR_PENDING);
6826 }
6827
6828 static void enable_nmi_window(struct kvm_vcpu *vcpu)
6829 {
6830         if (!enable_vnmi ||
6831             vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
6832                 enable_irq_window(vcpu);
6833                 return;
6834         }
6835
6836         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
6837                       CPU_BASED_VIRTUAL_NMI_PENDING);
6838 }
6839
6840 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
6841 {
6842         struct vcpu_vmx *vmx = to_vmx(vcpu);
6843         uint32_t intr;
6844         int irq = vcpu->arch.interrupt.nr;
6845
6846         trace_kvm_inj_virq(irq);
6847
6848         ++vcpu->stat.irq_injections;
6849         if (vmx->rmode.vm86_active) {
6850                 int inc_eip = 0;
6851                 if (vcpu->arch.interrupt.soft)
6852                         inc_eip = vcpu->arch.event_exit_inst_len;
6853                 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
6854                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6855                 return;
6856         }
6857         intr = irq | INTR_INFO_VALID_MASK;
6858         if (vcpu->arch.interrupt.soft) {
6859                 intr |= INTR_TYPE_SOFT_INTR;
6860                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
6861                              vmx->vcpu.arch.event_exit_inst_len);
6862         } else
6863                 intr |= INTR_TYPE_EXT_INTR;
6864         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
6865
6866         vmx_clear_hlt(vcpu);
6867 }
6868
6869 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
6870 {
6871         struct vcpu_vmx *vmx = to_vmx(vcpu);
6872
6873         if (!enable_vnmi) {
6874                 /*
6875                  * Tracking the NMI-blocked state in software is built upon
6876                  * finding the next open IRQ window. This, in turn, depends on
6877                  * well-behaving guests: They have to keep IRQs disabled at
6878                  * least as long as the NMI handler runs. Otherwise we may
6879                  * cause NMI nesting, maybe breaking the guest. But as this is
6880                  * highly unlikely, we can live with the residual risk.
6881                  */
6882                 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
6883                 vmx->loaded_vmcs->vnmi_blocked_time = 0;
6884         }
6885
6886         ++vcpu->stat.nmi_injections;
6887         vmx->loaded_vmcs->nmi_known_unmasked = false;
6888
6889         if (vmx->rmode.vm86_active) {
6890                 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
6891                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6892                 return;
6893         }
6894
6895         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
6896                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
6897
6898         vmx_clear_hlt(vcpu);
6899 }
6900
6901 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
6902 {
6903         struct vcpu_vmx *vmx = to_vmx(vcpu);
6904         bool masked;
6905
6906         if (!enable_vnmi)
6907                 return vmx->loaded_vmcs->soft_vnmi_blocked;
6908         if (vmx->loaded_vmcs->nmi_known_unmasked)
6909                 return false;
6910         masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
6911         vmx->loaded_vmcs->nmi_known_unmasked = !masked;
6912         return masked;
6913 }
6914
6915 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
6916 {
6917         struct vcpu_vmx *vmx = to_vmx(vcpu);
6918
6919         if (!enable_vnmi) {
6920                 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
6921                         vmx->loaded_vmcs->soft_vnmi_blocked = masked;
6922                         vmx->loaded_vmcs->vnmi_blocked_time = 0;
6923                 }
6924         } else {
6925                 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
6926                 if (masked)
6927                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6928                                       GUEST_INTR_STATE_NMI);
6929                 else
6930                         vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
6931                                         GUEST_INTR_STATE_NMI);
6932         }
6933 }
6934
6935 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
6936 {
6937         if (to_vmx(vcpu)->nested.nested_run_pending)
6938                 return 0;
6939
6940         if (!enable_vnmi &&
6941             to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
6942                 return 0;
6943
6944         return  !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6945                   (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
6946                    | GUEST_INTR_STATE_NMI));
6947 }
6948
6949 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
6950 {
6951         return (!to_vmx(vcpu)->nested.nested_run_pending &&
6952                 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
6953                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6954                         (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
6955 }
6956
6957 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
6958 {
6959         int ret;
6960
6961         if (enable_unrestricted_guest)
6962                 return 0;
6963
6964         ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
6965                                     PAGE_SIZE * 3);
6966         if (ret)
6967                 return ret;
6968         to_kvm_vmx(kvm)->tss_addr = addr;
6969         return init_rmode_tss(kvm);
6970 }
6971
6972 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
6973 {
6974         to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
6975         return 0;
6976 }
6977
6978 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
6979 {
6980         switch (vec) {
6981         case BP_VECTOR:
6982                 /*
6983                  * Update instruction length as we may reinject the exception
6984                  * from user space while in guest debugging mode.
6985                  */
6986                 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
6987                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6988                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
6989                         return false;
6990                 /* fall through */
6991         case DB_VECTOR:
6992                 if (vcpu->guest_debug &
6993                         (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
6994                         return false;
6995                 /* fall through */
6996         case DE_VECTOR:
6997         case OF_VECTOR:
6998         case BR_VECTOR:
6999         case UD_VECTOR:
7000         case DF_VECTOR:
7001         case SS_VECTOR:
7002         case GP_VECTOR:
7003         case MF_VECTOR:
7004                 return true;
7005         break;
7006         }
7007         return false;
7008 }
7009
7010 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
7011                                   int vec, u32 err_code)
7012 {
7013         /*
7014          * Instruction with address size override prefix opcode 0x67
7015          * Cause the #SS fault with 0 error code in VM86 mode.
7016          */
7017         if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
7018                 if (kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE) {
7019                         if (vcpu->arch.halt_request) {
7020                                 vcpu->arch.halt_request = 0;
7021                                 return kvm_vcpu_halt(vcpu);
7022                         }
7023                         return 1;
7024                 }
7025                 return 0;
7026         }
7027
7028         /*
7029          * Forward all other exceptions that are valid in real mode.
7030          * FIXME: Breaks guest debugging in real mode, needs to be fixed with
7031          *        the required debugging infrastructure rework.
7032          */
7033         kvm_queue_exception(vcpu, vec);
7034         return 1;
7035 }
7036
7037 /*
7038  * Trigger machine check on the host. We assume all the MSRs are already set up
7039  * by the CPU and that we still run on the same CPU as the MCE occurred on.
7040  * We pass a fake environment to the machine check handler because we want
7041  * the guest to be always treated like user space, no matter what context
7042  * it used internally.
7043  */
7044 static void kvm_machine_check(void)
7045 {
7046 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
7047         struct pt_regs regs = {
7048                 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
7049                 .flags = X86_EFLAGS_IF,
7050         };
7051
7052         do_machine_check(&regs, 0);
7053 #endif
7054 }
7055
7056 static int handle_machine_check(struct kvm_vcpu *vcpu)
7057 {
7058         /* already handled by vcpu_run */
7059         return 1;
7060 }
7061
7062 static int handle_exception(struct kvm_vcpu *vcpu)
7063 {
7064         struct vcpu_vmx *vmx = to_vmx(vcpu);
7065         struct kvm_run *kvm_run = vcpu->run;
7066         u32 intr_info, ex_no, error_code;
7067         unsigned long cr2, rip, dr6;
7068         u32 vect_info;
7069         enum emulation_result er;
7070
7071         vect_info = vmx->idt_vectoring_info;
7072         intr_info = vmx->exit_intr_info;
7073
7074         if (is_machine_check(intr_info))
7075                 return handle_machine_check(vcpu);
7076
7077         if (is_nmi(intr_info))
7078                 return 1;  /* already handled by vmx_vcpu_run() */
7079
7080         if (is_invalid_opcode(intr_info))
7081                 return handle_ud(vcpu);
7082
7083         error_code = 0;
7084         if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
7085                 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
7086
7087         if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
7088                 WARN_ON_ONCE(!enable_vmware_backdoor);
7089                 er = kvm_emulate_instruction(vcpu,
7090                         EMULTYPE_VMWARE | EMULTYPE_NO_UD_ON_FAIL);
7091                 if (er == EMULATE_USER_EXIT)
7092                         return 0;
7093                 else if (er != EMULATE_DONE)
7094                         kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
7095                 return 1;
7096         }
7097
7098         /*
7099          * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
7100          * MMIO, it is better to report an internal error.
7101          * See the comments in vmx_handle_exit.
7102          */
7103         if ((vect_info & VECTORING_INFO_VALID_MASK) &&
7104             !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
7105                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7106                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
7107                 vcpu->run->internal.ndata = 3;
7108                 vcpu->run->internal.data[0] = vect_info;
7109                 vcpu->run->internal.data[1] = intr_info;
7110                 vcpu->run->internal.data[2] = error_code;
7111                 return 0;
7112         }
7113
7114         if (is_page_fault(intr_info)) {
7115                 cr2 = vmcs_readl(EXIT_QUALIFICATION);
7116                 /* EPT won't cause page fault directly */
7117                 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
7118                 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
7119         }
7120
7121         ex_no = intr_info & INTR_INFO_VECTOR_MASK;
7122
7123         if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
7124                 return handle_rmode_exception(vcpu, ex_no, error_code);
7125
7126         switch (ex_no) {
7127         case AC_VECTOR:
7128                 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
7129                 return 1;
7130         case DB_VECTOR:
7131                 dr6 = vmcs_readl(EXIT_QUALIFICATION);
7132                 if (!(vcpu->guest_debug &
7133                       (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
7134                         vcpu->arch.dr6 &= ~15;
7135                         vcpu->arch.dr6 |= dr6 | DR6_RTM;
7136                         if (is_icebp(intr_info))
7137                                 skip_emulated_instruction(vcpu);
7138
7139                         kvm_queue_exception(vcpu, DB_VECTOR);
7140                         return 1;
7141                 }
7142                 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
7143                 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
7144                 /* fall through */
7145         case BP_VECTOR:
7146                 /*
7147                  * Update instruction length as we may reinject #BP from
7148                  * user space while in guest debugging mode. Reading it for
7149                  * #DB as well causes no harm, it is not used in that case.
7150                  */
7151                 vmx->vcpu.arch.event_exit_inst_len =
7152                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
7153                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
7154                 rip = kvm_rip_read(vcpu);
7155                 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
7156                 kvm_run->debug.arch.exception = ex_no;
7157                 break;
7158         default:
7159                 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
7160                 kvm_run->ex.exception = ex_no;
7161                 kvm_run->ex.error_code = error_code;
7162                 break;
7163         }
7164         return 0;
7165 }
7166
7167 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
7168 {
7169         ++vcpu->stat.irq_exits;
7170         return 1;
7171 }
7172
7173 static int handle_triple_fault(struct kvm_vcpu *vcpu)
7174 {
7175         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
7176         vcpu->mmio_needed = 0;
7177         return 0;
7178 }
7179
7180 static int handle_io(struct kvm_vcpu *vcpu)
7181 {
7182         unsigned long exit_qualification;
7183         int size, in, string;
7184         unsigned port;
7185
7186         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7187         string = (exit_qualification & 16) != 0;
7188
7189         ++vcpu->stat.io_exits;
7190
7191         if (string)
7192                 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7193
7194         port = exit_qualification >> 16;
7195         size = (exit_qualification & 7) + 1;
7196         in = (exit_qualification & 8) != 0;
7197
7198         return kvm_fast_pio(vcpu, size, port, in);
7199 }
7200
7201 static void
7202 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
7203 {
7204         /*
7205          * Patch in the VMCALL instruction:
7206          */
7207         hypercall[0] = 0x0f;
7208         hypercall[1] = 0x01;
7209         hypercall[2] = 0xc1;
7210 }
7211
7212 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
7213 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
7214 {
7215         if (is_guest_mode(vcpu)) {
7216                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7217                 unsigned long orig_val = val;
7218
7219                 /*
7220                  * We get here when L2 changed cr0 in a way that did not change
7221                  * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
7222                  * but did change L0 shadowed bits. So we first calculate the
7223                  * effective cr0 value that L1 would like to write into the
7224                  * hardware. It consists of the L2-owned bits from the new
7225                  * value combined with the L1-owned bits from L1's guest_cr0.
7226                  */
7227                 val = (val & ~vmcs12->cr0_guest_host_mask) |
7228                         (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
7229
7230                 if (!nested_guest_cr0_valid(vcpu, val))
7231                         return 1;
7232
7233                 if (kvm_set_cr0(vcpu, val))
7234                         return 1;
7235                 vmcs_writel(CR0_READ_SHADOW, orig_val);
7236                 return 0;
7237         } else {
7238                 if (to_vmx(vcpu)->nested.vmxon &&
7239                     !nested_host_cr0_valid(vcpu, val))
7240                         return 1;
7241
7242                 return kvm_set_cr0(vcpu, val);
7243         }
7244 }
7245
7246 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
7247 {
7248         if (is_guest_mode(vcpu)) {
7249                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7250                 unsigned long orig_val = val;
7251
7252                 /* analogously to handle_set_cr0 */
7253                 val = (val & ~vmcs12->cr4_guest_host_mask) |
7254                         (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
7255                 if (kvm_set_cr4(vcpu, val))
7256                         return 1;
7257                 vmcs_writel(CR4_READ_SHADOW, orig_val);
7258                 return 0;
7259         } else
7260                 return kvm_set_cr4(vcpu, val);
7261 }
7262
7263 static int handle_desc(struct kvm_vcpu *vcpu)
7264 {
7265         WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
7266         return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7267 }
7268
7269 static int handle_cr(struct kvm_vcpu *vcpu)
7270 {
7271         unsigned long exit_qualification, val;
7272         int cr;
7273         int reg;
7274         int err;
7275         int ret;
7276
7277         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7278         cr = exit_qualification & 15;
7279         reg = (exit_qualification >> 8) & 15;
7280         switch ((exit_qualification >> 4) & 3) {
7281         case 0: /* mov to cr */
7282                 val = kvm_register_readl(vcpu, reg);
7283                 trace_kvm_cr_write(cr, val);
7284                 switch (cr) {
7285                 case 0:
7286                         err = handle_set_cr0(vcpu, val);
7287                         return kvm_complete_insn_gp(vcpu, err);
7288                 case 3:
7289                         WARN_ON_ONCE(enable_unrestricted_guest);
7290                         err = kvm_set_cr3(vcpu, val);
7291                         return kvm_complete_insn_gp(vcpu, err);
7292                 case 4:
7293                         err = handle_set_cr4(vcpu, val);
7294                         return kvm_complete_insn_gp(vcpu, err);
7295                 case 8: {
7296                                 u8 cr8_prev = kvm_get_cr8(vcpu);
7297                                 u8 cr8 = (u8)val;
7298                                 err = kvm_set_cr8(vcpu, cr8);
7299                                 ret = kvm_complete_insn_gp(vcpu, err);
7300                                 if (lapic_in_kernel(vcpu))
7301                                         return ret;
7302                                 if (cr8_prev <= cr8)
7303                                         return ret;
7304                                 /*
7305                                  * TODO: we might be squashing a
7306                                  * KVM_GUESTDBG_SINGLESTEP-triggered
7307                                  * KVM_EXIT_DEBUG here.
7308                                  */
7309                                 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
7310                                 return 0;
7311                         }
7312                 }
7313                 break;
7314         case 2: /* clts */
7315                 WARN_ONCE(1, "Guest should always own CR0.TS");
7316                 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
7317                 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
7318                 return kvm_skip_emulated_instruction(vcpu);
7319         case 1: /*mov from cr*/
7320                 switch (cr) {
7321                 case 3:
7322                         WARN_ON_ONCE(enable_unrestricted_guest);
7323                         val = kvm_read_cr3(vcpu);
7324                         kvm_register_write(vcpu, reg, val);
7325                         trace_kvm_cr_read(cr, val);
7326                         return kvm_skip_emulated_instruction(vcpu);
7327                 case 8:
7328                         val = kvm_get_cr8(vcpu);
7329                         kvm_register_write(vcpu, reg, val);
7330                         trace_kvm_cr_read(cr, val);
7331                         return kvm_skip_emulated_instruction(vcpu);
7332                 }
7333                 break;
7334         case 3: /* lmsw */
7335                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
7336                 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
7337                 kvm_lmsw(vcpu, val);
7338
7339                 return kvm_skip_emulated_instruction(vcpu);
7340         default:
7341                 break;
7342         }
7343         vcpu->run->exit_reason = 0;
7344         vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
7345                (int)(exit_qualification >> 4) & 3, cr);
7346         return 0;
7347 }
7348
7349 static int handle_dr(struct kvm_vcpu *vcpu)
7350 {
7351         unsigned long exit_qualification;
7352         int dr, dr7, reg;
7353
7354         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7355         dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
7356
7357         /* First, if DR does not exist, trigger UD */
7358         if (!kvm_require_dr(vcpu, dr))
7359                 return 1;
7360
7361         /* Do not handle if the CPL > 0, will trigger GP on re-entry */
7362         if (!kvm_require_cpl(vcpu, 0))
7363                 return 1;
7364         dr7 = vmcs_readl(GUEST_DR7);
7365         if (dr7 & DR7_GD) {
7366                 /*
7367                  * As the vm-exit takes precedence over the debug trap, we
7368                  * need to emulate the latter, either for the host or the
7369                  * guest debugging itself.
7370                  */
7371                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
7372                         vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
7373                         vcpu->run->debug.arch.dr7 = dr7;
7374                         vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
7375                         vcpu->run->debug.arch.exception = DB_VECTOR;
7376                         vcpu->run->exit_reason = KVM_EXIT_DEBUG;
7377                         return 0;
7378                 } else {
7379                         vcpu->arch.dr6 &= ~15;
7380                         vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
7381                         kvm_queue_exception(vcpu, DB_VECTOR);
7382                         return 1;
7383                 }
7384         }
7385
7386         if (vcpu->guest_debug == 0) {
7387                 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7388                                 CPU_BASED_MOV_DR_EXITING);
7389
7390                 /*
7391                  * No more DR vmexits; force a reload of the debug registers
7392                  * and reenter on this instruction.  The next vmexit will
7393                  * retrieve the full state of the debug registers.
7394                  */
7395                 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
7396                 return 1;
7397         }
7398
7399         reg = DEBUG_REG_ACCESS_REG(exit_qualification);
7400         if (exit_qualification & TYPE_MOV_FROM_DR) {
7401                 unsigned long val;
7402
7403                 if (kvm_get_dr(vcpu, dr, &val))
7404                         return 1;
7405                 kvm_register_write(vcpu, reg, val);
7406         } else
7407                 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
7408                         return 1;
7409
7410         return kvm_skip_emulated_instruction(vcpu);
7411 }
7412
7413 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
7414 {
7415         return vcpu->arch.dr6;
7416 }
7417
7418 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
7419 {
7420 }
7421
7422 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
7423 {
7424         get_debugreg(vcpu->arch.db[0], 0);
7425         get_debugreg(vcpu->arch.db[1], 1);
7426         get_debugreg(vcpu->arch.db[2], 2);
7427         get_debugreg(vcpu->arch.db[3], 3);
7428         get_debugreg(vcpu->arch.dr6, 6);
7429         vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
7430
7431         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
7432         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
7433 }
7434
7435 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
7436 {
7437         vmcs_writel(GUEST_DR7, val);
7438 }
7439
7440 static int handle_cpuid(struct kvm_vcpu *vcpu)
7441 {
7442         return kvm_emulate_cpuid(vcpu);
7443 }
7444
7445 static int handle_rdmsr(struct kvm_vcpu *vcpu)
7446 {
7447         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
7448         struct msr_data msr_info;
7449
7450         msr_info.index = ecx;
7451         msr_info.host_initiated = false;
7452         if (vmx_get_msr(vcpu, &msr_info)) {
7453                 trace_kvm_msr_read_ex(ecx);
7454                 kvm_inject_gp(vcpu, 0);
7455                 return 1;
7456         }
7457
7458         trace_kvm_msr_read(ecx, msr_info.data);
7459
7460         /* FIXME: handling of bits 32:63 of rax, rdx */
7461         vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
7462         vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
7463         return kvm_skip_emulated_instruction(vcpu);
7464 }
7465
7466 static int handle_wrmsr(struct kvm_vcpu *vcpu)
7467 {
7468         struct msr_data msr;
7469         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
7470         u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
7471                 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
7472
7473         msr.data = data;
7474         msr.index = ecx;
7475         msr.host_initiated = false;
7476         if (kvm_set_msr(vcpu, &msr) != 0) {
7477                 trace_kvm_msr_write_ex(ecx, data);
7478                 kvm_inject_gp(vcpu, 0);
7479                 return 1;
7480         }
7481
7482         trace_kvm_msr_write(ecx, data);
7483         return kvm_skip_emulated_instruction(vcpu);
7484 }
7485
7486 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
7487 {
7488         kvm_apic_update_ppr(vcpu);
7489         return 1;
7490 }
7491
7492 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
7493 {
7494         vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7495                         CPU_BASED_VIRTUAL_INTR_PENDING);
7496
7497         kvm_make_request(KVM_REQ_EVENT, vcpu);
7498
7499         ++vcpu->stat.irq_window_exits;
7500         return 1;
7501 }
7502
7503 static int handle_halt(struct kvm_vcpu *vcpu)
7504 {
7505         return kvm_emulate_halt(vcpu);
7506 }
7507
7508 static int handle_vmcall(struct kvm_vcpu *vcpu)
7509 {
7510         return kvm_emulate_hypercall(vcpu);
7511 }
7512
7513 static int handle_invd(struct kvm_vcpu *vcpu)
7514 {
7515         return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7516 }
7517
7518 static int handle_invlpg(struct kvm_vcpu *vcpu)
7519 {
7520         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7521
7522         kvm_mmu_invlpg(vcpu, exit_qualification);
7523         return kvm_skip_emulated_instruction(vcpu);
7524 }
7525
7526 static int handle_rdpmc(struct kvm_vcpu *vcpu)
7527 {
7528         int err;
7529
7530         err = kvm_rdpmc(vcpu);
7531         return kvm_complete_insn_gp(vcpu, err);
7532 }
7533
7534 static int handle_wbinvd(struct kvm_vcpu *vcpu)
7535 {
7536         return kvm_emulate_wbinvd(vcpu);
7537 }
7538
7539 static int handle_xsetbv(struct kvm_vcpu *vcpu)
7540 {
7541         u64 new_bv = kvm_read_edx_eax(vcpu);
7542         u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
7543
7544         if (kvm_set_xcr(vcpu, index, new_bv) == 0)
7545                 return kvm_skip_emulated_instruction(vcpu);
7546         return 1;
7547 }
7548
7549 static int handle_xsaves(struct kvm_vcpu *vcpu)
7550 {
7551         kvm_skip_emulated_instruction(vcpu);
7552         WARN(1, "this should never happen\n");
7553         return 1;
7554 }
7555
7556 static int handle_xrstors(struct kvm_vcpu *vcpu)
7557 {
7558         kvm_skip_emulated_instruction(vcpu);
7559         WARN(1, "this should never happen\n");
7560         return 1;
7561 }
7562
7563 static int handle_apic_access(struct kvm_vcpu *vcpu)
7564 {
7565         if (likely(fasteoi)) {
7566                 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7567                 int access_type, offset;
7568
7569                 access_type = exit_qualification & APIC_ACCESS_TYPE;
7570                 offset = exit_qualification & APIC_ACCESS_OFFSET;
7571                 /*
7572                  * Sane guest uses MOV to write EOI, with written value
7573                  * not cared. So make a short-circuit here by avoiding
7574                  * heavy instruction emulation.
7575                  */
7576                 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
7577                     (offset == APIC_EOI)) {
7578                         kvm_lapic_set_eoi(vcpu);
7579                         return kvm_skip_emulated_instruction(vcpu);
7580                 }
7581         }
7582         return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7583 }
7584
7585 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
7586 {
7587         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7588         int vector = exit_qualification & 0xff;
7589
7590         /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
7591         kvm_apic_set_eoi_accelerated(vcpu, vector);
7592         return 1;
7593 }
7594
7595 static int handle_apic_write(struct kvm_vcpu *vcpu)
7596 {
7597         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7598         u32 offset = exit_qualification & 0xfff;
7599
7600         /* APIC-write VM exit is trap-like and thus no need to adjust IP */
7601         kvm_apic_write_nodecode(vcpu, offset);
7602         return 1;
7603 }
7604
7605 static int handle_task_switch(struct kvm_vcpu *vcpu)
7606 {
7607         struct vcpu_vmx *vmx = to_vmx(vcpu);
7608         unsigned long exit_qualification;
7609         bool has_error_code = false;
7610         u32 error_code = 0;
7611         u16 tss_selector;
7612         int reason, type, idt_v, idt_index;
7613
7614         idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
7615         idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
7616         type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
7617
7618         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7619
7620         reason = (u32)exit_qualification >> 30;
7621         if (reason == TASK_SWITCH_GATE && idt_v) {
7622                 switch (type) {
7623                 case INTR_TYPE_NMI_INTR:
7624                         vcpu->arch.nmi_injected = false;
7625                         vmx_set_nmi_mask(vcpu, true);
7626                         break;
7627                 case INTR_TYPE_EXT_INTR:
7628                 case INTR_TYPE_SOFT_INTR:
7629                         kvm_clear_interrupt_queue(vcpu);
7630                         break;
7631                 case INTR_TYPE_HARD_EXCEPTION:
7632                         if (vmx->idt_vectoring_info &
7633                             VECTORING_INFO_DELIVER_CODE_MASK) {
7634                                 has_error_code = true;
7635                                 error_code =
7636                                         vmcs_read32(IDT_VECTORING_ERROR_CODE);
7637                         }
7638                         /* fall through */
7639                 case INTR_TYPE_SOFT_EXCEPTION:
7640                         kvm_clear_exception_queue(vcpu);
7641                         break;
7642                 default:
7643                         break;
7644                 }
7645         }
7646         tss_selector = exit_qualification;
7647
7648         if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
7649                        type != INTR_TYPE_EXT_INTR &&
7650                        type != INTR_TYPE_NMI_INTR))
7651                 skip_emulated_instruction(vcpu);
7652
7653         if (kvm_task_switch(vcpu, tss_selector,
7654                             type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
7655                             has_error_code, error_code) == EMULATE_FAIL) {
7656                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7657                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7658                 vcpu->run->internal.ndata = 0;
7659                 return 0;
7660         }
7661
7662         /*
7663          * TODO: What about debug traps on tss switch?
7664          *       Are we supposed to inject them and update dr6?
7665          */
7666
7667         return 1;
7668 }
7669
7670 static int handle_ept_violation(struct kvm_vcpu *vcpu)
7671 {
7672         unsigned long exit_qualification;
7673         gpa_t gpa;
7674         u64 error_code;
7675
7676         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7677
7678         /*
7679          * EPT violation happened while executing iret from NMI,
7680          * "blocked by NMI" bit has to be set before next VM entry.
7681          * There are errata that may cause this bit to not be set:
7682          * AAK134, BY25.
7683          */
7684         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
7685                         enable_vnmi &&
7686                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
7687                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
7688
7689         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
7690         trace_kvm_page_fault(gpa, exit_qualification);
7691
7692         /* Is it a read fault? */
7693         error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
7694                      ? PFERR_USER_MASK : 0;
7695         /* Is it a write fault? */
7696         error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
7697                       ? PFERR_WRITE_MASK : 0;
7698         /* Is it a fetch fault? */
7699         error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
7700                       ? PFERR_FETCH_MASK : 0;
7701         /* ept page table entry is present? */
7702         error_code |= (exit_qualification &
7703                        (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
7704                         EPT_VIOLATION_EXECUTABLE))
7705                       ? PFERR_PRESENT_MASK : 0;
7706
7707         error_code |= (exit_qualification & 0x100) != 0 ?
7708                PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
7709
7710         vcpu->arch.exit_qualification = exit_qualification;
7711         return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
7712 }
7713
7714 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
7715 {
7716         gpa_t gpa;
7717
7718         /*
7719          * A nested guest cannot optimize MMIO vmexits, because we have an
7720          * nGPA here instead of the required GPA.
7721          */
7722         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
7723         if (!is_guest_mode(vcpu) &&
7724             !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
7725                 trace_kvm_fast_mmio(gpa);
7726                 /*
7727                  * Doing kvm_skip_emulated_instruction() depends on undefined
7728                  * behavior: Intel's manual doesn't mandate
7729                  * VM_EXIT_INSTRUCTION_LEN to be set in VMCS when EPT MISCONFIG
7730                  * occurs and while on real hardware it was observed to be set,
7731                  * other hypervisors (namely Hyper-V) don't set it, we end up
7732                  * advancing IP with some random value. Disable fast mmio when
7733                  * running nested and keep it for real hardware in hope that
7734                  * VM_EXIT_INSTRUCTION_LEN will always be set correctly.
7735                  */
7736                 if (!static_cpu_has(X86_FEATURE_HYPERVISOR))
7737                         return kvm_skip_emulated_instruction(vcpu);
7738                 else
7739                         return kvm_emulate_instruction(vcpu, EMULTYPE_SKIP) ==
7740                                                                 EMULATE_DONE;
7741         }
7742
7743         return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
7744 }
7745
7746 static int handle_nmi_window(struct kvm_vcpu *vcpu)
7747 {
7748         WARN_ON_ONCE(!enable_vnmi);
7749         vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7750                         CPU_BASED_VIRTUAL_NMI_PENDING);
7751         ++vcpu->stat.nmi_window_exits;
7752         kvm_make_request(KVM_REQ_EVENT, vcpu);
7753
7754         return 1;
7755 }
7756
7757 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
7758 {
7759         struct vcpu_vmx *vmx = to_vmx(vcpu);
7760         enum emulation_result err = EMULATE_DONE;
7761         int ret = 1;
7762         u32 cpu_exec_ctrl;
7763         bool intr_window_requested;
7764         unsigned count = 130;
7765
7766         /*
7767          * We should never reach the point where we are emulating L2
7768          * due to invalid guest state as that means we incorrectly
7769          * allowed a nested VMEntry with an invalid vmcs12.
7770          */
7771         WARN_ON_ONCE(vmx->emulation_required && vmx->nested.nested_run_pending);
7772
7773         cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
7774         intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
7775
7776         while (vmx->emulation_required && count-- != 0) {
7777                 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
7778                         return handle_interrupt_window(&vmx->vcpu);
7779
7780                 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
7781                         return 1;
7782
7783                 err = kvm_emulate_instruction(vcpu, 0);
7784
7785                 if (err == EMULATE_USER_EXIT) {
7786                         ++vcpu->stat.mmio_exits;
7787                         ret = 0;
7788                         goto out;
7789                 }
7790
7791                 if (err != EMULATE_DONE)
7792                         goto emulation_error;
7793
7794                 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
7795                     vcpu->arch.exception.pending)
7796                         goto emulation_error;
7797
7798                 if (vcpu->arch.halt_request) {
7799                         vcpu->arch.halt_request = 0;
7800                         ret = kvm_vcpu_halt(vcpu);
7801                         goto out;
7802                 }
7803
7804                 if (signal_pending(current))
7805                         goto out;
7806                 if (need_resched())
7807                         schedule();
7808         }
7809
7810 out:
7811         return ret;
7812
7813 emulation_error:
7814         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7815         vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7816         vcpu->run->internal.ndata = 0;
7817         return 0;
7818 }
7819
7820 static void grow_ple_window(struct kvm_vcpu *vcpu)
7821 {
7822         struct vcpu_vmx *vmx = to_vmx(vcpu);
7823         int old = vmx->ple_window;
7824
7825         vmx->ple_window = __grow_ple_window(old, ple_window,
7826                                             ple_window_grow,
7827                                             ple_window_max);
7828
7829         if (vmx->ple_window != old)
7830                 vmx->ple_window_dirty = true;
7831
7832         trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
7833 }
7834
7835 static void shrink_ple_window(struct kvm_vcpu *vcpu)
7836 {
7837         struct vcpu_vmx *vmx = to_vmx(vcpu);
7838         int old = vmx->ple_window;
7839
7840         vmx->ple_window = __shrink_ple_window(old, ple_window,
7841                                               ple_window_shrink,
7842                                               ple_window);
7843
7844         if (vmx->ple_window != old)
7845                 vmx->ple_window_dirty = true;
7846
7847         trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
7848 }
7849
7850 /*
7851  * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
7852  */
7853 static void wakeup_handler(void)
7854 {
7855         struct kvm_vcpu *vcpu;
7856         int cpu = smp_processor_id();
7857
7858         spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
7859         list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
7860                         blocked_vcpu_list) {
7861                 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7862
7863                 if (pi_test_on(pi_desc) == 1)
7864                         kvm_vcpu_kick(vcpu);
7865         }
7866         spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
7867 }
7868
7869 static void vmx_enable_tdp(void)
7870 {
7871         kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
7872                 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
7873                 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
7874                 0ull, VMX_EPT_EXECUTABLE_MASK,
7875                 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
7876                 VMX_EPT_RWX_MASK, 0ull);
7877
7878         ept_set_mmio_spte_mask();
7879         kvm_enable_tdp();
7880 }
7881
7882 static __init int hardware_setup(void)
7883 {
7884         unsigned long host_bndcfgs;
7885         int r = -ENOMEM, i;
7886
7887         rdmsrl_safe(MSR_EFER, &host_efer);
7888
7889         for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7890                 kvm_define_shared_msr(i, vmx_msr_index[i]);
7891
7892         for (i = 0; i < VMX_BITMAP_NR; i++) {
7893                 vmx_bitmap[i] = (unsigned long *)__get_free_page(GFP_KERNEL);
7894                 if (!vmx_bitmap[i])
7895                         goto out;
7896         }
7897
7898         memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
7899         memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
7900
7901         if (setup_vmcs_config(&vmcs_config) < 0) {
7902                 r = -EIO;
7903                 goto out;
7904         }
7905
7906         if (boot_cpu_has(X86_FEATURE_NX))
7907                 kvm_enable_efer_bits(EFER_NX);
7908
7909         if (boot_cpu_has(X86_FEATURE_MPX)) {
7910                 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7911                 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7912         }
7913
7914         if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7915                 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7916                 enable_vpid = 0;
7917
7918         if (!cpu_has_vmx_ept() ||
7919             !cpu_has_vmx_ept_4levels() ||
7920             !cpu_has_vmx_ept_mt_wb() ||
7921             !cpu_has_vmx_invept_global())
7922                 enable_ept = 0;
7923
7924         if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7925                 enable_ept_ad_bits = 0;
7926
7927         if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7928                 enable_unrestricted_guest = 0;
7929
7930         if (!cpu_has_vmx_flexpriority())
7931                 flexpriority_enabled = 0;
7932
7933         if (!cpu_has_virtual_nmis())
7934                 enable_vnmi = 0;
7935
7936         /*
7937          * set_apic_access_page_addr() is used to reload apic access
7938          * page upon invalidation.  No need to do anything if not
7939          * using the APIC_ACCESS_ADDR VMCS field.
7940          */
7941         if (!flexpriority_enabled)
7942                 kvm_x86_ops->set_apic_access_page_addr = NULL;
7943
7944         if (!cpu_has_vmx_tpr_shadow())
7945                 kvm_x86_ops->update_cr8_intercept = NULL;
7946
7947         if (enable_ept && !cpu_has_vmx_ept_2m_page())
7948                 kvm_disable_largepages();
7949
7950 #if IS_ENABLED(CONFIG_HYPERV)
7951         if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7952             && enable_ept)
7953                 kvm_x86_ops->tlb_remote_flush = vmx_hv_remote_flush_tlb;
7954 #endif
7955
7956         if (!cpu_has_vmx_ple()) {
7957                 ple_gap = 0;
7958                 ple_window = 0;
7959                 ple_window_grow = 0;
7960                 ple_window_max = 0;
7961                 ple_window_shrink = 0;
7962         }
7963
7964         if (!cpu_has_vmx_apicv()) {
7965                 enable_apicv = 0;
7966                 kvm_x86_ops->sync_pir_to_irr = NULL;
7967         }
7968
7969         if (cpu_has_vmx_tsc_scaling()) {
7970                 kvm_has_tsc_control = true;
7971                 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7972                 kvm_tsc_scaling_ratio_frac_bits = 48;
7973         }
7974
7975         set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7976
7977         if (enable_ept)
7978                 vmx_enable_tdp();
7979         else
7980                 kvm_disable_tdp();
7981
7982         if (!nested) {
7983                 kvm_x86_ops->get_nested_state = NULL;
7984                 kvm_x86_ops->set_nested_state = NULL;
7985         }
7986
7987         /*
7988          * Only enable PML when hardware supports PML feature, and both EPT
7989          * and EPT A/D bit features are enabled -- PML depends on them to work.
7990          */
7991         if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7992                 enable_pml = 0;
7993
7994         if (!enable_pml) {
7995                 kvm_x86_ops->slot_enable_log_dirty = NULL;
7996                 kvm_x86_ops->slot_disable_log_dirty = NULL;
7997                 kvm_x86_ops->flush_log_dirty = NULL;
7998                 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
7999         }
8000
8001         if (!cpu_has_vmx_preemption_timer())
8002                 kvm_x86_ops->request_immediate_exit = __kvm_request_immediate_exit;
8003
8004         if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
8005                 u64 vmx_msr;
8006
8007                 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
8008                 cpu_preemption_timer_multi =
8009                          vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
8010         } else {
8011                 kvm_x86_ops->set_hv_timer = NULL;
8012                 kvm_x86_ops->cancel_hv_timer = NULL;
8013         }
8014
8015         if (!cpu_has_vmx_shadow_vmcs())
8016                 enable_shadow_vmcs = 0;
8017         if (enable_shadow_vmcs)
8018                 init_vmcs_shadow_fields();
8019
8020         kvm_set_posted_intr_wakeup_handler(wakeup_handler);
8021         nested_vmx_setup_ctls_msrs(&vmcs_config.nested, enable_apicv);
8022
8023         kvm_mce_cap_supported |= MCG_LMCE_P;
8024
8025         return alloc_kvm_area();
8026
8027 out:
8028         for (i = 0; i < VMX_BITMAP_NR; i++)
8029                 free_page((unsigned long)vmx_bitmap[i]);
8030
8031     return r;
8032 }
8033
8034 static __exit void hardware_unsetup(void)
8035 {
8036         int i;
8037
8038         for (i = 0; i < VMX_BITMAP_NR; i++)
8039                 free_page((unsigned long)vmx_bitmap[i]);
8040
8041         free_kvm_area();
8042 }
8043
8044 /*
8045  * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
8046  * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
8047  */
8048 static int handle_pause(struct kvm_vcpu *vcpu)
8049 {
8050         if (!kvm_pause_in_guest(vcpu->kvm))
8051                 grow_ple_window(vcpu);
8052
8053         /*
8054          * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
8055          * VM-execution control is ignored if CPL > 0. OTOH, KVM
8056          * never set PAUSE_EXITING and just set PLE if supported,
8057          * so the vcpu must be CPL=0 if it gets a PAUSE exit.
8058          */
8059         kvm_vcpu_on_spin(vcpu, true);
8060         return kvm_skip_emulated_instruction(vcpu);
8061 }
8062
8063 static int handle_nop(struct kvm_vcpu *vcpu)
8064 {
8065         return kvm_skip_emulated_instruction(vcpu);
8066 }
8067
8068 static int handle_mwait(struct kvm_vcpu *vcpu)
8069 {
8070         printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
8071         return handle_nop(vcpu);
8072 }
8073
8074 static int handle_invalid_op(struct kvm_vcpu *vcpu)
8075 {
8076         kvm_queue_exception(vcpu, UD_VECTOR);
8077         return 1;
8078 }
8079
8080 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
8081 {
8082         return 1;
8083 }
8084
8085 static int handle_monitor(struct kvm_vcpu *vcpu)
8086 {
8087         printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
8088         return handle_nop(vcpu);
8089 }
8090
8091 /*
8092  * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
8093  * set the success or error code of an emulated VMX instruction (as specified
8094  * by Vol 2B, VMX Instruction Reference, "Conventions"), and skip the emulated
8095  * instruction.
8096  */
8097 static int nested_vmx_succeed(struct kvm_vcpu *vcpu)
8098 {
8099         vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
8100                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
8101                             X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
8102         return kvm_skip_emulated_instruction(vcpu);
8103 }
8104
8105 static int nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
8106 {
8107         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
8108                         & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
8109                             X86_EFLAGS_SF | X86_EFLAGS_OF))
8110                         | X86_EFLAGS_CF);
8111         return kvm_skip_emulated_instruction(vcpu);
8112 }
8113
8114 static int nested_vmx_failValid(struct kvm_vcpu *vcpu,
8115                                 u32 vm_instruction_error)
8116 {
8117         struct vcpu_vmx *vmx = to_vmx(vcpu);
8118
8119         /*
8120          * failValid writes the error number to the current VMCS, which
8121          * can't be done if there isn't a current VMCS.
8122          */
8123         if (vmx->nested.current_vmptr == -1ull && !vmx->nested.hv_evmcs)
8124                 return nested_vmx_failInvalid(vcpu);
8125
8126         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
8127                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
8128                             X86_EFLAGS_SF | X86_EFLAGS_OF))
8129                         | X86_EFLAGS_ZF);
8130         get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
8131         /*
8132          * We don't need to force a shadow sync because
8133          * VM_INSTRUCTION_ERROR is not shadowed
8134          */
8135         return kvm_skip_emulated_instruction(vcpu);
8136 }
8137
8138 static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
8139 {
8140         /* TODO: not to reset guest simply here. */
8141         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8142         pr_debug_ratelimited("kvm: nested vmx abort, indicator %d\n", indicator);
8143 }
8144
8145 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
8146 {
8147         struct vcpu_vmx *vmx =
8148                 container_of(timer, struct vcpu_vmx, nested.preemption_timer);
8149
8150         vmx->nested.preemption_timer_expired = true;
8151         kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
8152         kvm_vcpu_kick(&vmx->vcpu);
8153
8154         return HRTIMER_NORESTART;
8155 }
8156
8157 /*
8158  * Decode the memory-address operand of a vmx instruction, as recorded on an
8159  * exit caused by such an instruction (run by a guest hypervisor).
8160  * On success, returns 0. When the operand is invalid, returns 1 and throws
8161  * #UD or #GP.
8162  */
8163 static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
8164                                  unsigned long exit_qualification,
8165                                  u32 vmx_instruction_info, bool wr, gva_t *ret)
8166 {
8167         gva_t off;
8168         bool exn;
8169         struct kvm_segment s;
8170
8171         /*
8172          * According to Vol. 3B, "Information for VM Exits Due to Instruction
8173          * Execution", on an exit, vmx_instruction_info holds most of the
8174          * addressing components of the operand. Only the displacement part
8175          * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
8176          * For how an actual address is calculated from all these components,
8177          * refer to Vol. 1, "Operand Addressing".
8178          */
8179         int  scaling = vmx_instruction_info & 3;
8180         int  addr_size = (vmx_instruction_info >> 7) & 7;
8181         bool is_reg = vmx_instruction_info & (1u << 10);
8182         int  seg_reg = (vmx_instruction_info >> 15) & 7;
8183         int  index_reg = (vmx_instruction_info >> 18) & 0xf;
8184         bool index_is_valid = !(vmx_instruction_info & (1u << 22));
8185         int  base_reg       = (vmx_instruction_info >> 23) & 0xf;
8186         bool base_is_valid  = !(vmx_instruction_info & (1u << 27));
8187
8188         if (is_reg) {
8189                 kvm_queue_exception(vcpu, UD_VECTOR);
8190                 return 1;
8191         }
8192
8193         /* Addr = segment_base + offset */
8194         /* offset = base + [index * scale] + displacement */
8195         off = exit_qualification; /* holds the displacement */
8196         if (base_is_valid)
8197                 off += kvm_register_read(vcpu, base_reg);
8198         if (index_is_valid)
8199                 off += kvm_register_read(vcpu, index_reg)<<scaling;
8200         vmx_get_segment(vcpu, &s, seg_reg);
8201         *ret = s.base + off;
8202
8203         if (addr_size == 1) /* 32 bit */
8204                 *ret &= 0xffffffff;
8205
8206         /* Checks for #GP/#SS exceptions. */
8207         exn = false;
8208         if (is_long_mode(vcpu)) {
8209                 /* Long mode: #GP(0)/#SS(0) if the memory address is in a
8210                  * non-canonical form. This is the only check on the memory
8211                  * destination for long mode!
8212                  */
8213                 exn = is_noncanonical_address(*ret, vcpu);
8214         } else if (is_protmode(vcpu)) {
8215                 /* Protected mode: apply checks for segment validity in the
8216                  * following order:
8217                  * - segment type check (#GP(0) may be thrown)
8218                  * - usability check (#GP(0)/#SS(0))
8219                  * - limit check (#GP(0)/#SS(0))
8220                  */
8221                 if (wr)
8222                         /* #GP(0) if the destination operand is located in a
8223                          * read-only data segment or any code segment.
8224                          */
8225                         exn = ((s.type & 0xa) == 0 || (s.type & 8));
8226                 else
8227                         /* #GP(0) if the source operand is located in an
8228                          * execute-only code segment
8229                          */
8230                         exn = ((s.type & 0xa) == 8);
8231                 if (exn) {
8232                         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
8233                         return 1;
8234                 }
8235                 /* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
8236                  */
8237                 exn = (s.unusable != 0);
8238                 /* Protected mode: #GP(0)/#SS(0) if the memory
8239                  * operand is outside the segment limit.
8240                  */
8241                 exn = exn || (off + sizeof(u64) > s.limit);
8242         }
8243         if (exn) {
8244                 kvm_queue_exception_e(vcpu,
8245                                       seg_reg == VCPU_SREG_SS ?
8246                                                 SS_VECTOR : GP_VECTOR,
8247                                       0);
8248                 return 1;
8249         }
8250
8251         return 0;
8252 }
8253
8254 static int nested_vmx_get_vmptr(struct kvm_vcpu *vcpu, gpa_t *vmpointer)
8255 {
8256         gva_t gva;
8257         struct x86_exception e;
8258
8259         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
8260                         vmcs_read32(VMX_INSTRUCTION_INFO), false, &gva))
8261                 return 1;
8262
8263         if (kvm_read_guest_virt(vcpu, gva, vmpointer, sizeof(*vmpointer), &e)) {
8264                 kvm_inject_page_fault(vcpu, &e);
8265                 return 1;
8266         }
8267
8268         return 0;
8269 }
8270
8271 /*
8272  * Allocate a shadow VMCS and associate it with the currently loaded
8273  * VMCS, unless such a shadow VMCS already exists. The newly allocated
8274  * VMCS is also VMCLEARed, so that it is ready for use.
8275  */
8276 static struct vmcs *alloc_shadow_vmcs(struct kvm_vcpu *vcpu)
8277 {
8278         struct vcpu_vmx *vmx = to_vmx(vcpu);
8279         struct loaded_vmcs *loaded_vmcs = vmx->loaded_vmcs;
8280
8281         /*
8282          * We should allocate a shadow vmcs for vmcs01 only when L1
8283          * executes VMXON and free it when L1 executes VMXOFF.
8284          * As it is invalid to execute VMXON twice, we shouldn't reach
8285          * here when vmcs01 already have an allocated shadow vmcs.
8286          */
8287         WARN_ON(loaded_vmcs == &vmx->vmcs01 && loaded_vmcs->shadow_vmcs);
8288
8289         if (!loaded_vmcs->shadow_vmcs) {
8290                 loaded_vmcs->shadow_vmcs = alloc_vmcs(true);
8291                 if (loaded_vmcs->shadow_vmcs)
8292                         vmcs_clear(loaded_vmcs->shadow_vmcs);
8293         }
8294         return loaded_vmcs->shadow_vmcs;
8295 }
8296
8297 static int enter_vmx_operation(struct kvm_vcpu *vcpu)
8298 {
8299         struct vcpu_vmx *vmx = to_vmx(vcpu);
8300         int r;
8301
8302         r = alloc_loaded_vmcs(&vmx->nested.vmcs02);
8303         if (r < 0)
8304                 goto out_vmcs02;
8305
8306         vmx->nested.cached_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
8307         if (!vmx->nested.cached_vmcs12)
8308                 goto out_cached_vmcs12;
8309
8310         vmx->nested.cached_shadow_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
8311         if (!vmx->nested.cached_shadow_vmcs12)
8312                 goto out_cached_shadow_vmcs12;
8313
8314         if (enable_shadow_vmcs && !alloc_shadow_vmcs(vcpu))
8315                 goto out_shadow_vmcs;
8316
8317         hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
8318                      HRTIMER_MODE_REL_PINNED);
8319         vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
8320
8321         vmx->nested.vpid02 = allocate_vpid();
8322
8323         vmx->nested.vmcs02_initialized = false;
8324         vmx->nested.vmxon = true;
8325         return 0;
8326
8327 out_shadow_vmcs:
8328         kfree(vmx->nested.cached_shadow_vmcs12);
8329
8330 out_cached_shadow_vmcs12:
8331         kfree(vmx->nested.cached_vmcs12);
8332
8333 out_cached_vmcs12:
8334         free_loaded_vmcs(&vmx->nested.vmcs02);
8335
8336 out_vmcs02:
8337         return -ENOMEM;
8338 }
8339
8340 /*
8341  * Emulate the VMXON instruction.
8342  * Currently, we just remember that VMX is active, and do not save or even
8343  * inspect the argument to VMXON (the so-called "VMXON pointer") because we
8344  * do not currently need to store anything in that guest-allocated memory
8345  * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
8346  * argument is different from the VMXON pointer (which the spec says they do).
8347  */
8348 static int handle_vmon(struct kvm_vcpu *vcpu)
8349 {
8350         int ret;
8351         gpa_t vmptr;
8352         struct page *page;
8353         struct vcpu_vmx *vmx = to_vmx(vcpu);
8354         const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
8355                 | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
8356
8357         /*
8358          * The Intel VMX Instruction Reference lists a bunch of bits that are
8359          * prerequisite to running VMXON, most notably cr4.VMXE must be set to
8360          * 1 (see vmx_set_cr4() for when we allow the guest to set this).
8361          * Otherwise, we should fail with #UD.  But most faulting conditions
8362          * have already been checked by hardware, prior to the VM-exit for
8363          * VMXON.  We do test guest cr4.VMXE because processor CR4 always has
8364          * that bit set to 1 in non-root mode.
8365          */
8366         if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) {
8367                 kvm_queue_exception(vcpu, UD_VECTOR);
8368                 return 1;
8369         }
8370
8371         /* CPL=0 must be checked manually. */
8372         if (vmx_get_cpl(vcpu)) {
8373                 kvm_inject_gp(vcpu, 0);
8374                 return 1;
8375         }
8376
8377         if (vmx->nested.vmxon)
8378                 return nested_vmx_failValid(vcpu,
8379                         VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
8380
8381         if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
8382                         != VMXON_NEEDED_FEATURES) {
8383                 kvm_inject_gp(vcpu, 0);
8384                 return 1;
8385         }
8386
8387         if (nested_vmx_get_vmptr(vcpu, &vmptr))
8388                 return 1;
8389
8390         /*
8391          * SDM 3: 24.11.5
8392          * The first 4 bytes of VMXON region contain the supported
8393          * VMCS revision identifier
8394          *
8395          * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
8396          * which replaces physical address width with 32
8397          */
8398         if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu)))
8399                 return nested_vmx_failInvalid(vcpu);
8400
8401         page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
8402         if (is_error_page(page))
8403                 return nested_vmx_failInvalid(vcpu);
8404
8405         if (*(u32 *)kmap(page) != VMCS12_REVISION) {
8406                 kunmap(page);
8407                 kvm_release_page_clean(page);
8408                 return nested_vmx_failInvalid(vcpu);
8409         }
8410         kunmap(page);
8411         kvm_release_page_clean(page);
8412
8413         vmx->nested.vmxon_ptr = vmptr;
8414         ret = enter_vmx_operation(vcpu);
8415         if (ret)
8416                 return ret;
8417
8418         return nested_vmx_succeed(vcpu);
8419 }
8420
8421 /*
8422  * Intel's VMX Instruction Reference specifies a common set of prerequisites
8423  * for running VMX instructions (except VMXON, whose prerequisites are
8424  * slightly different). It also specifies what exception to inject otherwise.
8425  * Note that many of these exceptions have priority over VM exits, so they
8426  * don't have to be checked again here.
8427  */
8428 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
8429 {
8430         if (!to_vmx(vcpu)->nested.vmxon) {
8431                 kvm_queue_exception(vcpu, UD_VECTOR);
8432                 return 0;
8433         }
8434
8435         if (vmx_get_cpl(vcpu)) {
8436                 kvm_inject_gp(vcpu, 0);
8437                 return 0;
8438         }
8439
8440         return 1;
8441 }
8442
8443 static void vmx_disable_shadow_vmcs(struct vcpu_vmx *vmx)
8444 {
8445         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL, SECONDARY_EXEC_SHADOW_VMCS);
8446         vmcs_write64(VMCS_LINK_POINTER, -1ull);
8447 }
8448
8449 static inline void nested_release_evmcs(struct kvm_vcpu *vcpu)
8450 {
8451         struct vcpu_vmx *vmx = to_vmx(vcpu);
8452
8453         if (!vmx->nested.hv_evmcs)
8454                 return;
8455
8456         kunmap(vmx->nested.hv_evmcs_page);
8457         kvm_release_page_dirty(vmx->nested.hv_evmcs_page);
8458         vmx->nested.hv_evmcs_vmptr = -1ull;
8459         vmx->nested.hv_evmcs_page = NULL;
8460         vmx->nested.hv_evmcs = NULL;
8461 }
8462
8463 static inline void nested_release_vmcs12(struct kvm_vcpu *vcpu)
8464 {
8465         struct vcpu_vmx *vmx = to_vmx(vcpu);
8466
8467         if (vmx->nested.current_vmptr == -1ull)
8468                 return;
8469
8470         if (enable_shadow_vmcs) {
8471                 /* copy to memory all shadowed fields in case
8472                    they were modified */
8473                 copy_shadow_to_vmcs12(vmx);
8474                 vmx->nested.need_vmcs12_sync = false;
8475                 vmx_disable_shadow_vmcs(vmx);
8476         }
8477         vmx->nested.posted_intr_nv = -1;
8478
8479         /* Flush VMCS12 to guest memory */
8480         kvm_vcpu_write_guest_page(vcpu,
8481                                   vmx->nested.current_vmptr >> PAGE_SHIFT,
8482                                   vmx->nested.cached_vmcs12, 0, VMCS12_SIZE);
8483
8484         kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
8485
8486         vmx->nested.current_vmptr = -1ull;
8487 }
8488
8489 /*
8490  * Free whatever needs to be freed from vmx->nested when L1 goes down, or
8491  * just stops using VMX.
8492  */
8493 static void free_nested(struct kvm_vcpu *vcpu)
8494 {
8495         struct vcpu_vmx *vmx = to_vmx(vcpu);
8496
8497         if (!vmx->nested.vmxon && !vmx->nested.smm.vmxon)
8498                 return;
8499
8500         vmx->nested.vmxon = false;
8501         vmx->nested.smm.vmxon = false;
8502         free_vpid(vmx->nested.vpid02);
8503         vmx->nested.posted_intr_nv = -1;
8504         vmx->nested.current_vmptr = -1ull;
8505         if (enable_shadow_vmcs) {
8506                 vmx_disable_shadow_vmcs(vmx);
8507                 vmcs_clear(vmx->vmcs01.shadow_vmcs);
8508                 free_vmcs(vmx->vmcs01.shadow_vmcs);
8509                 vmx->vmcs01.shadow_vmcs = NULL;
8510         }
8511         kfree(vmx->nested.cached_vmcs12);
8512         kfree(vmx->nested.cached_shadow_vmcs12);
8513         /* Unpin physical memory we referred to in the vmcs02 */
8514         if (vmx->nested.apic_access_page) {
8515                 kvm_release_page_dirty(vmx->nested.apic_access_page);
8516                 vmx->nested.apic_access_page = NULL;
8517         }
8518         if (vmx->nested.virtual_apic_page) {
8519                 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
8520                 vmx->nested.virtual_apic_page = NULL;
8521         }
8522         if (vmx->nested.pi_desc_page) {
8523                 kunmap(vmx->nested.pi_desc_page);
8524                 kvm_release_page_dirty(vmx->nested.pi_desc_page);
8525                 vmx->nested.pi_desc_page = NULL;
8526                 vmx->nested.pi_desc = NULL;
8527         }
8528
8529         kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
8530
8531         nested_release_evmcs(vcpu);
8532
8533         free_loaded_vmcs(&vmx->nested.vmcs02);
8534 }
8535
8536 /* Emulate the VMXOFF instruction */
8537 static int handle_vmoff(struct kvm_vcpu *vcpu)
8538 {
8539         if (!nested_vmx_check_permission(vcpu))
8540                 return 1;
8541         free_nested(vcpu);
8542         return nested_vmx_succeed(vcpu);
8543 }
8544
8545 /* Emulate the VMCLEAR instruction */
8546 static int handle_vmclear(struct kvm_vcpu *vcpu)
8547 {
8548         struct vcpu_vmx *vmx = to_vmx(vcpu);
8549         u32 zero = 0;
8550         gpa_t vmptr;
8551
8552         if (!nested_vmx_check_permission(vcpu))
8553                 return 1;
8554
8555         if (nested_vmx_get_vmptr(vcpu, &vmptr))
8556                 return 1;
8557
8558         if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu)))
8559                 return nested_vmx_failValid(vcpu,
8560                         VMXERR_VMCLEAR_INVALID_ADDRESS);
8561
8562         if (vmptr == vmx->nested.vmxon_ptr)
8563                 return nested_vmx_failValid(vcpu,
8564                         VMXERR_VMCLEAR_VMXON_POINTER);
8565
8566         if (vmx->nested.hv_evmcs_page) {
8567                 if (vmptr == vmx->nested.hv_evmcs_vmptr)
8568                         nested_release_evmcs(vcpu);
8569         } else {
8570                 if (vmptr == vmx->nested.current_vmptr)
8571                         nested_release_vmcs12(vcpu);
8572
8573                 kvm_vcpu_write_guest(vcpu,
8574                                      vmptr + offsetof(struct vmcs12,
8575                                                       launch_state),
8576                                      &zero, sizeof(zero));
8577         }
8578
8579         return nested_vmx_succeed(vcpu);
8580 }
8581
8582 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
8583
8584 /* Emulate the VMLAUNCH instruction */
8585 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
8586 {
8587         return nested_vmx_run(vcpu, true);
8588 }
8589
8590 /* Emulate the VMRESUME instruction */
8591 static int handle_vmresume(struct kvm_vcpu *vcpu)
8592 {
8593
8594         return nested_vmx_run(vcpu, false);
8595 }
8596
8597 /*
8598  * Read a vmcs12 field. Since these can have varying lengths and we return
8599  * one type, we chose the biggest type (u64) and zero-extend the return value
8600  * to that size. Note that the caller, handle_vmread, might need to use only
8601  * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
8602  * 64-bit fields are to be returned).
8603  */
8604 static inline int vmcs12_read_any(struct vmcs12 *vmcs12,
8605                                   unsigned long field, u64 *ret)
8606 {
8607         short offset = vmcs_field_to_offset(field);
8608         char *p;
8609
8610         if (offset < 0)
8611                 return offset;
8612
8613         p = (char *)vmcs12 + offset;
8614
8615         switch (vmcs_field_width(field)) {
8616         case VMCS_FIELD_WIDTH_NATURAL_WIDTH:
8617                 *ret = *((natural_width *)p);
8618                 return 0;
8619         case VMCS_FIELD_WIDTH_U16:
8620                 *ret = *((u16 *)p);
8621                 return 0;
8622         case VMCS_FIELD_WIDTH_U32:
8623                 *ret = *((u32 *)p);
8624                 return 0;
8625         case VMCS_FIELD_WIDTH_U64:
8626                 *ret = *((u64 *)p);
8627                 return 0;
8628         default:
8629                 WARN_ON(1);
8630                 return -ENOENT;
8631         }
8632 }
8633
8634
8635 static inline int vmcs12_write_any(struct vmcs12 *vmcs12,
8636                                    unsigned long field, u64 field_value){
8637         short offset = vmcs_field_to_offset(field);
8638         char *p = (char *)vmcs12 + offset;
8639         if (offset < 0)
8640                 return offset;
8641
8642         switch (vmcs_field_width(field)) {
8643         case VMCS_FIELD_WIDTH_U16:
8644                 *(u16 *)p = field_value;
8645                 return 0;
8646         case VMCS_FIELD_WIDTH_U32:
8647                 *(u32 *)p = field_value;
8648                 return 0;
8649         case VMCS_FIELD_WIDTH_U64:
8650                 *(u64 *)p = field_value;
8651                 return 0;
8652         case VMCS_FIELD_WIDTH_NATURAL_WIDTH:
8653                 *(natural_width *)p = field_value;
8654                 return 0;
8655         default:
8656                 WARN_ON(1);
8657                 return -ENOENT;
8658         }
8659
8660 }
8661
8662 static int copy_enlightened_to_vmcs12(struct vcpu_vmx *vmx)
8663 {
8664         struct vmcs12 *vmcs12 = vmx->nested.cached_vmcs12;
8665         struct hv_enlightened_vmcs *evmcs = vmx->nested.hv_evmcs;
8666
8667         vmcs12->hdr.revision_id = evmcs->revision_id;
8668
8669         /* HV_VMX_ENLIGHTENED_CLEAN_FIELD_NONE */
8670         vmcs12->tpr_threshold = evmcs->tpr_threshold;
8671         vmcs12->guest_rip = evmcs->guest_rip;
8672
8673         if (unlikely(!(evmcs->hv_clean_fields &
8674                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_BASIC))) {
8675                 vmcs12->guest_rsp = evmcs->guest_rsp;
8676                 vmcs12->guest_rflags = evmcs->guest_rflags;
8677                 vmcs12->guest_interruptibility_info =
8678                         evmcs->guest_interruptibility_info;
8679         }
8680
8681         if (unlikely(!(evmcs->hv_clean_fields &
8682                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_PROC))) {
8683                 vmcs12->cpu_based_vm_exec_control =
8684                         evmcs->cpu_based_vm_exec_control;
8685         }
8686
8687         if (unlikely(!(evmcs->hv_clean_fields &
8688                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_PROC))) {
8689                 vmcs12->exception_bitmap = evmcs->exception_bitmap;
8690         }
8691
8692         if (unlikely(!(evmcs->hv_clean_fields &
8693                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_ENTRY))) {
8694                 vmcs12->vm_entry_controls = evmcs->vm_entry_controls;
8695         }
8696
8697         if (unlikely(!(evmcs->hv_clean_fields &
8698                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_EVENT))) {
8699                 vmcs12->vm_entry_intr_info_field =
8700                         evmcs->vm_entry_intr_info_field;
8701                 vmcs12->vm_entry_exception_error_code =
8702                         evmcs->vm_entry_exception_error_code;
8703                 vmcs12->vm_entry_instruction_len =
8704                         evmcs->vm_entry_instruction_len;
8705         }
8706
8707         if (unlikely(!(evmcs->hv_clean_fields &
8708                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_HOST_GRP1))) {
8709                 vmcs12->host_ia32_pat = evmcs->host_ia32_pat;
8710                 vmcs12->host_ia32_efer = evmcs->host_ia32_efer;
8711                 vmcs12->host_cr0 = evmcs->host_cr0;
8712                 vmcs12->host_cr3 = evmcs->host_cr3;
8713                 vmcs12->host_cr4 = evmcs->host_cr4;
8714                 vmcs12->host_ia32_sysenter_esp = evmcs->host_ia32_sysenter_esp;
8715                 vmcs12->host_ia32_sysenter_eip = evmcs->host_ia32_sysenter_eip;
8716                 vmcs12->host_rip = evmcs->host_rip;
8717                 vmcs12->host_ia32_sysenter_cs = evmcs->host_ia32_sysenter_cs;
8718                 vmcs12->host_es_selector = evmcs->host_es_selector;
8719                 vmcs12->host_cs_selector = evmcs->host_cs_selector;
8720                 vmcs12->host_ss_selector = evmcs->host_ss_selector;
8721                 vmcs12->host_ds_selector = evmcs->host_ds_selector;
8722                 vmcs12->host_fs_selector = evmcs->host_fs_selector;
8723                 vmcs12->host_gs_selector = evmcs->host_gs_selector;
8724                 vmcs12->host_tr_selector = evmcs->host_tr_selector;
8725         }
8726
8727         if (unlikely(!(evmcs->hv_clean_fields &
8728                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_HOST_GRP1))) {
8729                 vmcs12->pin_based_vm_exec_control =
8730                         evmcs->pin_based_vm_exec_control;
8731                 vmcs12->vm_exit_controls = evmcs->vm_exit_controls;
8732                 vmcs12->secondary_vm_exec_control =
8733                         evmcs->secondary_vm_exec_control;
8734         }
8735
8736         if (unlikely(!(evmcs->hv_clean_fields &
8737                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_IO_BITMAP))) {
8738                 vmcs12->io_bitmap_a = evmcs->io_bitmap_a;
8739                 vmcs12->io_bitmap_b = evmcs->io_bitmap_b;
8740         }
8741
8742         if (unlikely(!(evmcs->hv_clean_fields &
8743                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP))) {
8744                 vmcs12->msr_bitmap = evmcs->msr_bitmap;
8745         }
8746
8747         if (unlikely(!(evmcs->hv_clean_fields &
8748                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2))) {
8749                 vmcs12->guest_es_base = evmcs->guest_es_base;
8750                 vmcs12->guest_cs_base = evmcs->guest_cs_base;
8751                 vmcs12->guest_ss_base = evmcs->guest_ss_base;
8752                 vmcs12->guest_ds_base = evmcs->guest_ds_base;
8753                 vmcs12->guest_fs_base = evmcs->guest_fs_base;
8754                 vmcs12->guest_gs_base = evmcs->guest_gs_base;
8755                 vmcs12->guest_ldtr_base = evmcs->guest_ldtr_base;
8756                 vmcs12->guest_tr_base = evmcs->guest_tr_base;
8757                 vmcs12->guest_gdtr_base = evmcs->guest_gdtr_base;
8758                 vmcs12->guest_idtr_base = evmcs->guest_idtr_base;
8759                 vmcs12->guest_es_limit = evmcs->guest_es_limit;
8760                 vmcs12->guest_cs_limit = evmcs->guest_cs_limit;
8761                 vmcs12->guest_ss_limit = evmcs->guest_ss_limit;
8762                 vmcs12->guest_ds_limit = evmcs->guest_ds_limit;
8763                 vmcs12->guest_fs_limit = evmcs->guest_fs_limit;
8764                 vmcs12->guest_gs_limit = evmcs->guest_gs_limit;
8765                 vmcs12->guest_ldtr_limit = evmcs->guest_ldtr_limit;
8766                 vmcs12->guest_tr_limit = evmcs->guest_tr_limit;
8767                 vmcs12->guest_gdtr_limit = evmcs->guest_gdtr_limit;
8768                 vmcs12->guest_idtr_limit = evmcs->guest_idtr_limit;
8769                 vmcs12->guest_es_ar_bytes = evmcs->guest_es_ar_bytes;
8770                 vmcs12->guest_cs_ar_bytes = evmcs->guest_cs_ar_bytes;
8771                 vmcs12->guest_ss_ar_bytes = evmcs->guest_ss_ar_bytes;
8772                 vmcs12->guest_ds_ar_bytes = evmcs->guest_ds_ar_bytes;
8773                 vmcs12->guest_fs_ar_bytes = evmcs->guest_fs_ar_bytes;
8774                 vmcs12->guest_gs_ar_bytes = evmcs->guest_gs_ar_bytes;
8775                 vmcs12->guest_ldtr_ar_bytes = evmcs->guest_ldtr_ar_bytes;
8776                 vmcs12->guest_tr_ar_bytes = evmcs->guest_tr_ar_bytes;
8777                 vmcs12->guest_es_selector = evmcs->guest_es_selector;
8778                 vmcs12->guest_cs_selector = evmcs->guest_cs_selector;
8779                 vmcs12->guest_ss_selector = evmcs->guest_ss_selector;
8780                 vmcs12->guest_ds_selector = evmcs->guest_ds_selector;
8781                 vmcs12->guest_fs_selector = evmcs->guest_fs_selector;
8782                 vmcs12->guest_gs_selector = evmcs->guest_gs_selector;
8783                 vmcs12->guest_ldtr_selector = evmcs->guest_ldtr_selector;
8784                 vmcs12->guest_tr_selector = evmcs->guest_tr_selector;
8785         }
8786
8787         if (unlikely(!(evmcs->hv_clean_fields &
8788                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_GRP2))) {
8789                 vmcs12->tsc_offset = evmcs->tsc_offset;
8790                 vmcs12->virtual_apic_page_addr = evmcs->virtual_apic_page_addr;
8791                 vmcs12->xss_exit_bitmap = evmcs->xss_exit_bitmap;
8792         }
8793
8794         if (unlikely(!(evmcs->hv_clean_fields &
8795                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CRDR))) {
8796                 vmcs12->cr0_guest_host_mask = evmcs->cr0_guest_host_mask;
8797                 vmcs12->cr4_guest_host_mask = evmcs->cr4_guest_host_mask;
8798                 vmcs12->cr0_read_shadow = evmcs->cr0_read_shadow;
8799                 vmcs12->cr4_read_shadow = evmcs->cr4_read_shadow;
8800                 vmcs12->guest_cr0 = evmcs->guest_cr0;
8801                 vmcs12->guest_cr3 = evmcs->guest_cr3;
8802                 vmcs12->guest_cr4 = evmcs->guest_cr4;
8803                 vmcs12->guest_dr7 = evmcs->guest_dr7;
8804         }
8805
8806         if (unlikely(!(evmcs->hv_clean_fields &
8807                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_HOST_POINTER))) {
8808                 vmcs12->host_fs_base = evmcs->host_fs_base;
8809                 vmcs12->host_gs_base = evmcs->host_gs_base;
8810                 vmcs12->host_tr_base = evmcs->host_tr_base;
8811                 vmcs12->host_gdtr_base = evmcs->host_gdtr_base;
8812                 vmcs12->host_idtr_base = evmcs->host_idtr_base;
8813                 vmcs12->host_rsp = evmcs->host_rsp;
8814         }
8815
8816         if (unlikely(!(evmcs->hv_clean_fields &
8817                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_XLAT))) {
8818                 vmcs12->ept_pointer = evmcs->ept_pointer;
8819                 vmcs12->virtual_processor_id = evmcs->virtual_processor_id;
8820         }
8821
8822         if (unlikely(!(evmcs->hv_clean_fields &
8823                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1))) {
8824                 vmcs12->vmcs_link_pointer = evmcs->vmcs_link_pointer;
8825                 vmcs12->guest_ia32_debugctl = evmcs->guest_ia32_debugctl;
8826                 vmcs12->guest_ia32_pat = evmcs->guest_ia32_pat;
8827                 vmcs12->guest_ia32_efer = evmcs->guest_ia32_efer;
8828                 vmcs12->guest_pdptr0 = evmcs->guest_pdptr0;
8829                 vmcs12->guest_pdptr1 = evmcs->guest_pdptr1;
8830                 vmcs12->guest_pdptr2 = evmcs->guest_pdptr2;
8831                 vmcs12->guest_pdptr3 = evmcs->guest_pdptr3;
8832                 vmcs12->guest_pending_dbg_exceptions =
8833                         evmcs->guest_pending_dbg_exceptions;
8834                 vmcs12->guest_sysenter_esp = evmcs->guest_sysenter_esp;
8835                 vmcs12->guest_sysenter_eip = evmcs->guest_sysenter_eip;
8836                 vmcs12->guest_bndcfgs = evmcs->guest_bndcfgs;
8837                 vmcs12->guest_activity_state = evmcs->guest_activity_state;
8838                 vmcs12->guest_sysenter_cs = evmcs->guest_sysenter_cs;
8839         }
8840
8841         /*
8842          * Not used?
8843          * vmcs12->vm_exit_msr_store_addr = evmcs->vm_exit_msr_store_addr;
8844          * vmcs12->vm_exit_msr_load_addr = evmcs->vm_exit_msr_load_addr;
8845          * vmcs12->vm_entry_msr_load_addr = evmcs->vm_entry_msr_load_addr;
8846          * vmcs12->cr3_target_value0 = evmcs->cr3_target_value0;
8847          * vmcs12->cr3_target_value1 = evmcs->cr3_target_value1;
8848          * vmcs12->cr3_target_value2 = evmcs->cr3_target_value2;
8849          * vmcs12->cr3_target_value3 = evmcs->cr3_target_value3;
8850          * vmcs12->page_fault_error_code_mask =
8851          *              evmcs->page_fault_error_code_mask;
8852          * vmcs12->page_fault_error_code_match =
8853          *              evmcs->page_fault_error_code_match;
8854          * vmcs12->cr3_target_count = evmcs->cr3_target_count;
8855          * vmcs12->vm_exit_msr_store_count = evmcs->vm_exit_msr_store_count;
8856          * vmcs12->vm_exit_msr_load_count = evmcs->vm_exit_msr_load_count;
8857          * vmcs12->vm_entry_msr_load_count = evmcs->vm_entry_msr_load_count;
8858          */
8859
8860         /*
8861          * Read only fields:
8862          * vmcs12->guest_physical_address = evmcs->guest_physical_address;
8863          * vmcs12->vm_instruction_error = evmcs->vm_instruction_error;
8864          * vmcs12->vm_exit_reason = evmcs->vm_exit_reason;
8865          * vmcs12->vm_exit_intr_info = evmcs->vm_exit_intr_info;
8866          * vmcs12->vm_exit_intr_error_code = evmcs->vm_exit_intr_error_code;
8867          * vmcs12->idt_vectoring_info_field = evmcs->idt_vectoring_info_field;
8868          * vmcs12->idt_vectoring_error_code = evmcs->idt_vectoring_error_code;
8869          * vmcs12->vm_exit_instruction_len = evmcs->vm_exit_instruction_len;
8870          * vmcs12->vmx_instruction_info = evmcs->vmx_instruction_info;
8871          * vmcs12->exit_qualification = evmcs->exit_qualification;
8872          * vmcs12->guest_linear_address = evmcs->guest_linear_address;
8873          *
8874          * Not present in struct vmcs12:
8875          * vmcs12->exit_io_instruction_ecx = evmcs->exit_io_instruction_ecx;
8876          * vmcs12->exit_io_instruction_esi = evmcs->exit_io_instruction_esi;
8877          * vmcs12->exit_io_instruction_edi = evmcs->exit_io_instruction_edi;
8878          * vmcs12->exit_io_instruction_eip = evmcs->exit_io_instruction_eip;
8879          */
8880
8881         return 0;
8882 }
8883
8884 static int copy_vmcs12_to_enlightened(struct vcpu_vmx *vmx)
8885 {
8886         struct vmcs12 *vmcs12 = vmx->nested.cached_vmcs12;
8887         struct hv_enlightened_vmcs *evmcs = vmx->nested.hv_evmcs;
8888
8889         /*
8890          * Should not be changed by KVM:
8891          *
8892          * evmcs->host_es_selector = vmcs12->host_es_selector;
8893          * evmcs->host_cs_selector = vmcs12->host_cs_selector;
8894          * evmcs->host_ss_selector = vmcs12->host_ss_selector;
8895          * evmcs->host_ds_selector = vmcs12->host_ds_selector;
8896          * evmcs->host_fs_selector = vmcs12->host_fs_selector;
8897          * evmcs->host_gs_selector = vmcs12->host_gs_selector;
8898          * evmcs->host_tr_selector = vmcs12->host_tr_selector;
8899          * evmcs->host_ia32_pat = vmcs12->host_ia32_pat;
8900          * evmcs->host_ia32_efer = vmcs12->host_ia32_efer;
8901          * evmcs->host_cr0 = vmcs12->host_cr0;
8902          * evmcs->host_cr3 = vmcs12->host_cr3;
8903          * evmcs->host_cr4 = vmcs12->host_cr4;
8904          * evmcs->host_ia32_sysenter_esp = vmcs12->host_ia32_sysenter_esp;
8905          * evmcs->host_ia32_sysenter_eip = vmcs12->host_ia32_sysenter_eip;
8906          * evmcs->host_rip = vmcs12->host_rip;
8907          * evmcs->host_ia32_sysenter_cs = vmcs12->host_ia32_sysenter_cs;
8908          * evmcs->host_fs_base = vmcs12->host_fs_base;
8909          * evmcs->host_gs_base = vmcs12->host_gs_base;
8910          * evmcs->host_tr_base = vmcs12->host_tr_base;
8911          * evmcs->host_gdtr_base = vmcs12->host_gdtr_base;
8912          * evmcs->host_idtr_base = vmcs12->host_idtr_base;
8913          * evmcs->host_rsp = vmcs12->host_rsp;
8914          * sync_vmcs12() doesn't read these:
8915          * evmcs->io_bitmap_a = vmcs12->io_bitmap_a;
8916          * evmcs->io_bitmap_b = vmcs12->io_bitmap_b;
8917          * evmcs->msr_bitmap = vmcs12->msr_bitmap;
8918          * evmcs->ept_pointer = vmcs12->ept_pointer;
8919          * evmcs->xss_exit_bitmap = vmcs12->xss_exit_bitmap;
8920          * evmcs->vm_exit_msr_store_addr = vmcs12->vm_exit_msr_store_addr;
8921          * evmcs->vm_exit_msr_load_addr = vmcs12->vm_exit_msr_load_addr;
8922          * evmcs->vm_entry_msr_load_addr = vmcs12->vm_entry_msr_load_addr;
8923          * evmcs->cr3_target_value0 = vmcs12->cr3_target_value0;
8924          * evmcs->cr3_target_value1 = vmcs12->cr3_target_value1;
8925          * evmcs->cr3_target_value2 = vmcs12->cr3_target_value2;
8926          * evmcs->cr3_target_value3 = vmcs12->cr3_target_value3;
8927          * evmcs->tpr_threshold = vmcs12->tpr_threshold;
8928          * evmcs->virtual_processor_id = vmcs12->virtual_processor_id;
8929          * evmcs->exception_bitmap = vmcs12->exception_bitmap;
8930          * evmcs->vmcs_link_pointer = vmcs12->vmcs_link_pointer;
8931          * evmcs->pin_based_vm_exec_control = vmcs12->pin_based_vm_exec_control;
8932          * evmcs->vm_exit_controls = vmcs12->vm_exit_controls;
8933          * evmcs->secondary_vm_exec_control = vmcs12->secondary_vm_exec_control;
8934          * evmcs->page_fault_error_code_mask =
8935          *              vmcs12->page_fault_error_code_mask;
8936          * evmcs->page_fault_error_code_match =
8937          *              vmcs12->page_fault_error_code_match;
8938          * evmcs->cr3_target_count = vmcs12->cr3_target_count;
8939          * evmcs->virtual_apic_page_addr = vmcs12->virtual_apic_page_addr;
8940          * evmcs->tsc_offset = vmcs12->tsc_offset;
8941          * evmcs->guest_ia32_debugctl = vmcs12->guest_ia32_debugctl;
8942          * evmcs->cr0_guest_host_mask = vmcs12->cr0_guest_host_mask;
8943          * evmcs->cr4_guest_host_mask = vmcs12->cr4_guest_host_mask;
8944          * evmcs->cr0_read_shadow = vmcs12->cr0_read_shadow;
8945          * evmcs->cr4_read_shadow = vmcs12->cr4_read_shadow;
8946          * evmcs->vm_exit_msr_store_count = vmcs12->vm_exit_msr_store_count;
8947          * evmcs->vm_exit_msr_load_count = vmcs12->vm_exit_msr_load_count;
8948          * evmcs->vm_entry_msr_load_count = vmcs12->vm_entry_msr_load_count;
8949          *
8950          * Not present in struct vmcs12:
8951          * evmcs->exit_io_instruction_ecx = vmcs12->exit_io_instruction_ecx;
8952          * evmcs->exit_io_instruction_esi = vmcs12->exit_io_instruction_esi;
8953          * evmcs->exit_io_instruction_edi = vmcs12->exit_io_instruction_edi;
8954          * evmcs->exit_io_instruction_eip = vmcs12->exit_io_instruction_eip;
8955          */
8956
8957         evmcs->guest_es_selector = vmcs12->guest_es_selector;
8958         evmcs->guest_cs_selector = vmcs12->guest_cs_selector;
8959         evmcs->guest_ss_selector = vmcs12->guest_ss_selector;
8960         evmcs->guest_ds_selector = vmcs12->guest_ds_selector;
8961         evmcs->guest_fs_selector = vmcs12->guest_fs_selector;
8962         evmcs->guest_gs_selector = vmcs12->guest_gs_selector;
8963         evmcs->guest_ldtr_selector = vmcs12->guest_ldtr_selector;
8964         evmcs->guest_tr_selector = vmcs12->guest_tr_selector;
8965
8966         evmcs->guest_es_limit = vmcs12->guest_es_limit;
8967         evmcs->guest_cs_limit = vmcs12->guest_cs_limit;
8968         evmcs->guest_ss_limit = vmcs12->guest_ss_limit;
8969         evmcs->guest_ds_limit = vmcs12->guest_ds_limit;
8970         evmcs->guest_fs_limit = vmcs12->guest_fs_limit;
8971         evmcs->guest_gs_limit = vmcs12->guest_gs_limit;
8972         evmcs->guest_ldtr_limit = vmcs12->guest_ldtr_limit;
8973         evmcs->guest_tr_limit = vmcs12->guest_tr_limit;
8974         evmcs->guest_gdtr_limit = vmcs12->guest_gdtr_limit;
8975         evmcs->guest_idtr_limit = vmcs12->guest_idtr_limit;
8976
8977         evmcs->guest_es_ar_bytes = vmcs12->guest_es_ar_bytes;
8978         evmcs->guest_cs_ar_bytes = vmcs12->guest_cs_ar_bytes;
8979         evmcs->guest_ss_ar_bytes = vmcs12->guest_ss_ar_bytes;
8980         evmcs->guest_ds_ar_bytes = vmcs12->guest_ds_ar_bytes;
8981         evmcs->guest_fs_ar_bytes = vmcs12->guest_fs_ar_bytes;
8982         evmcs->guest_gs_ar_bytes = vmcs12->guest_gs_ar_bytes;
8983         evmcs->guest_ldtr_ar_bytes = vmcs12->guest_ldtr_ar_bytes;
8984         evmcs->guest_tr_ar_bytes = vmcs12->guest_tr_ar_bytes;
8985
8986         evmcs->guest_es_base = vmcs12->guest_es_base;
8987         evmcs->guest_cs_base = vmcs12->guest_cs_base;
8988         evmcs->guest_ss_base = vmcs12->guest_ss_base;
8989         evmcs->guest_ds_base = vmcs12->guest_ds_base;
8990         evmcs->guest_fs_base = vmcs12->guest_fs_base;
8991         evmcs->guest_gs_base = vmcs12->guest_gs_base;
8992         evmcs->guest_ldtr_base = vmcs12->guest_ldtr_base;
8993         evmcs->guest_tr_base = vmcs12->guest_tr_base;
8994         evmcs->guest_gdtr_base = vmcs12->guest_gdtr_base;
8995         evmcs->guest_idtr_base = vmcs12->guest_idtr_base;
8996
8997         evmcs->guest_ia32_pat = vmcs12->guest_ia32_pat;
8998         evmcs->guest_ia32_efer = vmcs12->guest_ia32_efer;
8999
9000         evmcs->guest_pdptr0 = vmcs12->guest_pdptr0;
9001         evmcs->guest_pdptr1 = vmcs12->guest_pdptr1;
9002         evmcs->guest_pdptr2 = vmcs12->guest_pdptr2;
9003         evmcs->guest_pdptr3 = vmcs12->guest_pdptr3;
9004
9005         evmcs->guest_pending_dbg_exceptions =
9006                 vmcs12->guest_pending_dbg_exceptions;
9007         evmcs->guest_sysenter_esp = vmcs12->guest_sysenter_esp;
9008         evmcs->guest_sysenter_eip = vmcs12->guest_sysenter_eip;
9009
9010         evmcs->guest_activity_state = vmcs12->guest_activity_state;
9011         evmcs->guest_sysenter_cs = vmcs12->guest_sysenter_cs;
9012
9013         evmcs->guest_cr0 = vmcs12->guest_cr0;
9014         evmcs->guest_cr3 = vmcs12->guest_cr3;
9015         evmcs->guest_cr4 = vmcs12->guest_cr4;
9016         evmcs->guest_dr7 = vmcs12->guest_dr7;
9017
9018         evmcs->guest_physical_address = vmcs12->guest_physical_address;
9019
9020         evmcs->vm_instruction_error = vmcs12->vm_instruction_error;
9021         evmcs->vm_exit_reason = vmcs12->vm_exit_reason;
9022         evmcs->vm_exit_intr_info = vmcs12->vm_exit_intr_info;
9023         evmcs->vm_exit_intr_error_code = vmcs12->vm_exit_intr_error_code;
9024         evmcs->idt_vectoring_info_field = vmcs12->idt_vectoring_info_field;
9025         evmcs->idt_vectoring_error_code = vmcs12->idt_vectoring_error_code;
9026         evmcs->vm_exit_instruction_len = vmcs12->vm_exit_instruction_len;
9027         evmcs->vmx_instruction_info = vmcs12->vmx_instruction_info;
9028
9029         evmcs->exit_qualification = vmcs12->exit_qualification;
9030
9031         evmcs->guest_linear_address = vmcs12->guest_linear_address;
9032         evmcs->guest_rsp = vmcs12->guest_rsp;
9033         evmcs->guest_rflags = vmcs12->guest_rflags;
9034
9035         evmcs->guest_interruptibility_info =
9036                 vmcs12->guest_interruptibility_info;
9037         evmcs->cpu_based_vm_exec_control = vmcs12->cpu_based_vm_exec_control;
9038         evmcs->vm_entry_controls = vmcs12->vm_entry_controls;
9039         evmcs->vm_entry_intr_info_field = vmcs12->vm_entry_intr_info_field;
9040         evmcs->vm_entry_exception_error_code =
9041                 vmcs12->vm_entry_exception_error_code;
9042         evmcs->vm_entry_instruction_len = vmcs12->vm_entry_instruction_len;
9043
9044         evmcs->guest_rip = vmcs12->guest_rip;
9045
9046         evmcs->guest_bndcfgs = vmcs12->guest_bndcfgs;
9047
9048         return 0;
9049 }
9050
9051 /*
9052  * Copy the writable VMCS shadow fields back to the VMCS12, in case
9053  * they have been modified by the L1 guest. Note that the "read-only"
9054  * VM-exit information fields are actually writable if the vCPU is
9055  * configured to support "VMWRITE to any supported field in the VMCS."
9056  */
9057 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
9058 {
9059         const u16 *fields[] = {
9060                 shadow_read_write_fields,
9061                 shadow_read_only_fields
9062         };
9063         const int max_fields[] = {
9064                 max_shadow_read_write_fields,
9065                 max_shadow_read_only_fields
9066         };
9067         int i, q;
9068         unsigned long field;
9069         u64 field_value;
9070         struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
9071
9072         preempt_disable();
9073
9074         vmcs_load(shadow_vmcs);
9075
9076         for (q = 0; q < ARRAY_SIZE(fields); q++) {
9077                 for (i = 0; i < max_fields[q]; i++) {
9078                         field = fields[q][i];
9079                         field_value = __vmcs_readl(field);
9080                         vmcs12_write_any(get_vmcs12(&vmx->vcpu), field, field_value);
9081                 }
9082                 /*
9083                  * Skip the VM-exit information fields if they are read-only.
9084                  */
9085                 if (!nested_cpu_has_vmwrite_any_field(&vmx->vcpu))
9086                         break;
9087         }
9088
9089         vmcs_clear(shadow_vmcs);
9090         vmcs_load(vmx->loaded_vmcs->vmcs);
9091
9092         preempt_enable();
9093 }
9094
9095 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
9096 {
9097         const u16 *fields[] = {
9098                 shadow_read_write_fields,
9099                 shadow_read_only_fields
9100         };
9101         const int max_fields[] = {
9102                 max_shadow_read_write_fields,
9103                 max_shadow_read_only_fields
9104         };
9105         int i, q;
9106         unsigned long field;
9107         u64 field_value = 0;
9108         struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
9109
9110         vmcs_load(shadow_vmcs);
9111
9112         for (q = 0; q < ARRAY_SIZE(fields); q++) {
9113                 for (i = 0; i < max_fields[q]; i++) {
9114                         field = fields[q][i];
9115                         vmcs12_read_any(get_vmcs12(&vmx->vcpu), field, &field_value);
9116                         __vmcs_writel(field, field_value);
9117                 }
9118         }
9119
9120         vmcs_clear(shadow_vmcs);
9121         vmcs_load(vmx->loaded_vmcs->vmcs);
9122 }
9123
9124 static int handle_vmread(struct kvm_vcpu *vcpu)
9125 {
9126         unsigned long field;
9127         u64 field_value;
9128         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9129         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9130         gva_t gva = 0;
9131         struct vmcs12 *vmcs12;
9132
9133         if (!nested_vmx_check_permission(vcpu))
9134                 return 1;
9135
9136         if (to_vmx(vcpu)->nested.current_vmptr == -1ull)
9137                 return nested_vmx_failInvalid(vcpu);
9138
9139         if (!is_guest_mode(vcpu))
9140                 vmcs12 = get_vmcs12(vcpu);
9141         else {
9142                 /*
9143                  * When vmcs->vmcs_link_pointer is -1ull, any VMREAD
9144                  * to shadowed-field sets the ALU flags for VMfailInvalid.
9145                  */
9146                 if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull)
9147                         return nested_vmx_failInvalid(vcpu);
9148                 vmcs12 = get_shadow_vmcs12(vcpu);
9149         }
9150
9151         /* Decode instruction info and find the field to read */
9152         field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
9153         /* Read the field, zero-extended to a u64 field_value */
9154         if (vmcs12_read_any(vmcs12, field, &field_value) < 0)
9155                 return nested_vmx_failValid(vcpu,
9156                         VMXERR_UNSUPPORTED_VMCS_COMPONENT);
9157
9158         /*
9159          * Now copy part of this value to register or memory, as requested.
9160          * Note that the number of bits actually copied is 32 or 64 depending
9161          * on the guest's mode (32 or 64 bit), not on the given field's length.
9162          */
9163         if (vmx_instruction_info & (1u << 10)) {
9164                 kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
9165                         field_value);
9166         } else {
9167                 if (get_vmx_mem_address(vcpu, exit_qualification,
9168                                 vmx_instruction_info, true, &gva))
9169                         return 1;
9170                 /* _system ok, nested_vmx_check_permission has verified cpl=0 */
9171                 kvm_write_guest_virt_system(vcpu, gva, &field_value,
9172                                             (is_long_mode(vcpu) ? 8 : 4), NULL);
9173         }
9174
9175         return nested_vmx_succeed(vcpu);
9176 }
9177
9178
9179 static int handle_vmwrite(struct kvm_vcpu *vcpu)
9180 {
9181         unsigned long field;
9182         gva_t gva;
9183         struct vcpu_vmx *vmx = to_vmx(vcpu);
9184         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9185         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9186
9187         /* The value to write might be 32 or 64 bits, depending on L1's long
9188          * mode, and eventually we need to write that into a field of several
9189          * possible lengths. The code below first zero-extends the value to 64
9190          * bit (field_value), and then copies only the appropriate number of
9191          * bits into the vmcs12 field.
9192          */
9193         u64 field_value = 0;
9194         struct x86_exception e;
9195         struct vmcs12 *vmcs12;
9196
9197         if (!nested_vmx_check_permission(vcpu))
9198                 return 1;
9199
9200         if (vmx->nested.current_vmptr == -1ull)
9201                 return nested_vmx_failInvalid(vcpu);
9202
9203         if (vmx_instruction_info & (1u << 10))
9204                 field_value = kvm_register_readl(vcpu,
9205                         (((vmx_instruction_info) >> 3) & 0xf));
9206         else {
9207                 if (get_vmx_mem_address(vcpu, exit_qualification,
9208                                 vmx_instruction_info, false, &gva))
9209                         return 1;
9210                 if (kvm_read_guest_virt(vcpu, gva, &field_value,
9211                                         (is_64_bit_mode(vcpu) ? 8 : 4), &e)) {
9212                         kvm_inject_page_fault(vcpu, &e);
9213                         return 1;
9214                 }
9215         }
9216
9217
9218         field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
9219         /*
9220          * If the vCPU supports "VMWRITE to any supported field in the
9221          * VMCS," then the "read-only" fields are actually read/write.
9222          */
9223         if (vmcs_field_readonly(field) &&
9224             !nested_cpu_has_vmwrite_any_field(vcpu))
9225                 return nested_vmx_failValid(vcpu,
9226                         VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
9227
9228         if (!is_guest_mode(vcpu))
9229                 vmcs12 = get_vmcs12(vcpu);
9230         else {
9231                 /*
9232                  * When vmcs->vmcs_link_pointer is -1ull, any VMWRITE
9233                  * to shadowed-field sets the ALU flags for VMfailInvalid.
9234                  */
9235                 if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull)
9236                         return nested_vmx_failInvalid(vcpu);
9237                 vmcs12 = get_shadow_vmcs12(vcpu);
9238         }
9239
9240         if (vmcs12_write_any(vmcs12, field, field_value) < 0)
9241                 return nested_vmx_failValid(vcpu,
9242                         VMXERR_UNSUPPORTED_VMCS_COMPONENT);
9243
9244         /*
9245          * Do not track vmcs12 dirty-state if in guest-mode
9246          * as we actually dirty shadow vmcs12 instead of vmcs12.
9247          */
9248         if (!is_guest_mode(vcpu)) {
9249                 switch (field) {
9250 #define SHADOW_FIELD_RW(x) case x:
9251 #include "vmx_shadow_fields.h"
9252                         /*
9253                          * The fields that can be updated by L1 without a vmexit are
9254                          * always updated in the vmcs02, the others go down the slow
9255                          * path of prepare_vmcs02.
9256                          */
9257                         break;
9258                 default:
9259                         vmx->nested.dirty_vmcs12 = true;
9260                         break;
9261                 }
9262         }
9263
9264         return nested_vmx_succeed(vcpu);
9265 }
9266
9267 static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
9268 {
9269         vmx->nested.current_vmptr = vmptr;
9270         if (enable_shadow_vmcs) {
9271                 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
9272                               SECONDARY_EXEC_SHADOW_VMCS);
9273                 vmcs_write64(VMCS_LINK_POINTER,
9274                              __pa(vmx->vmcs01.shadow_vmcs));
9275                 vmx->nested.need_vmcs12_sync = true;
9276         }
9277         vmx->nested.dirty_vmcs12 = true;
9278 }
9279
9280 /* Emulate the VMPTRLD instruction */
9281 static int handle_vmptrld(struct kvm_vcpu *vcpu)
9282 {
9283         struct vcpu_vmx *vmx = to_vmx(vcpu);
9284         gpa_t vmptr;
9285
9286         if (!nested_vmx_check_permission(vcpu))
9287                 return 1;
9288
9289         if (nested_vmx_get_vmptr(vcpu, &vmptr))
9290                 return 1;
9291
9292         if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu)))
9293                 return nested_vmx_failValid(vcpu,
9294                         VMXERR_VMPTRLD_INVALID_ADDRESS);
9295
9296         if (vmptr == vmx->nested.vmxon_ptr)
9297                 return nested_vmx_failValid(vcpu,
9298                         VMXERR_VMPTRLD_VMXON_POINTER);
9299
9300         /* Forbid normal VMPTRLD if Enlightened version was used */
9301         if (vmx->nested.hv_evmcs)
9302                 return 1;
9303
9304         if (vmx->nested.current_vmptr != vmptr) {
9305                 struct vmcs12 *new_vmcs12;
9306                 struct page *page;
9307                 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
9308                 if (is_error_page(page))
9309                         return nested_vmx_failInvalid(vcpu);
9310
9311                 new_vmcs12 = kmap(page);
9312                 if (new_vmcs12->hdr.revision_id != VMCS12_REVISION ||
9313                     (new_vmcs12->hdr.shadow_vmcs &&
9314                      !nested_cpu_has_vmx_shadow_vmcs(vcpu))) {
9315                         kunmap(page);
9316                         kvm_release_page_clean(page);
9317                         return nested_vmx_failValid(vcpu,
9318                                 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
9319                 }
9320
9321                 nested_release_vmcs12(vcpu);
9322
9323                 /*
9324                  * Load VMCS12 from guest memory since it is not already
9325                  * cached.
9326                  */
9327                 memcpy(vmx->nested.cached_vmcs12, new_vmcs12, VMCS12_SIZE);
9328                 kunmap(page);
9329                 kvm_release_page_clean(page);
9330
9331                 set_current_vmptr(vmx, vmptr);
9332         }
9333
9334         return nested_vmx_succeed(vcpu);
9335 }
9336
9337 /*
9338  * This is an equivalent of the nested hypervisor executing the vmptrld
9339  * instruction.
9340  */
9341 static int nested_vmx_handle_enlightened_vmptrld(struct kvm_vcpu *vcpu)
9342 {
9343         struct vcpu_vmx *vmx = to_vmx(vcpu);
9344         struct hv_vp_assist_page assist_page;
9345
9346         if (likely(!vmx->nested.enlightened_vmcs_enabled))
9347                 return 1;
9348
9349         if (unlikely(!kvm_hv_get_assist_page(vcpu, &assist_page)))
9350                 return 1;
9351
9352         if (unlikely(!assist_page.enlighten_vmentry))
9353                 return 1;
9354
9355         if (unlikely(assist_page.current_nested_vmcs !=
9356                      vmx->nested.hv_evmcs_vmptr)) {
9357
9358                 if (!vmx->nested.hv_evmcs)
9359                         vmx->nested.current_vmptr = -1ull;
9360
9361                 nested_release_evmcs(vcpu);
9362
9363                 vmx->nested.hv_evmcs_page = kvm_vcpu_gpa_to_page(
9364                         vcpu, assist_page.current_nested_vmcs);
9365
9366                 if (unlikely(is_error_page(vmx->nested.hv_evmcs_page)))
9367                         return 0;
9368
9369                 vmx->nested.hv_evmcs = kmap(vmx->nested.hv_evmcs_page);
9370
9371                 if (vmx->nested.hv_evmcs->revision_id != VMCS12_REVISION) {
9372                         nested_release_evmcs(vcpu);
9373                         return 0;
9374                 }
9375
9376                 vmx->nested.dirty_vmcs12 = true;
9377                 /*
9378                  * As we keep L2 state for one guest only 'hv_clean_fields' mask
9379                  * can't be used when we switch between them. Reset it here for
9380                  * simplicity.
9381                  */
9382                 vmx->nested.hv_evmcs->hv_clean_fields &=
9383                         ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
9384                 vmx->nested.hv_evmcs_vmptr = assist_page.current_nested_vmcs;
9385
9386                 /*
9387                  * Unlike normal vmcs12, enlightened vmcs12 is not fully
9388                  * reloaded from guest's memory (read only fields, fields not
9389                  * present in struct hv_enlightened_vmcs, ...). Make sure there
9390                  * are no leftovers.
9391                  */
9392                 memset(vmx->nested.cached_vmcs12, 0,
9393                        sizeof(*vmx->nested.cached_vmcs12));
9394
9395         }
9396         return 1;
9397 }
9398
9399 /* Emulate the VMPTRST instruction */
9400 static int handle_vmptrst(struct kvm_vcpu *vcpu)
9401 {
9402         unsigned long exit_qual = vmcs_readl(EXIT_QUALIFICATION);
9403         u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9404         gpa_t current_vmptr = to_vmx(vcpu)->nested.current_vmptr;
9405         struct x86_exception e;
9406         gva_t gva;
9407
9408         if (!nested_vmx_check_permission(vcpu))
9409                 return 1;
9410
9411         if (unlikely(to_vmx(vcpu)->nested.hv_evmcs))
9412                 return 1;
9413
9414         if (get_vmx_mem_address(vcpu, exit_qual, instr_info, true, &gva))
9415                 return 1;
9416         /* *_system ok, nested_vmx_check_permission has verified cpl=0 */
9417         if (kvm_write_guest_virt_system(vcpu, gva, (void *)&current_vmptr,
9418                                         sizeof(gpa_t), &e)) {
9419                 kvm_inject_page_fault(vcpu, &e);
9420                 return 1;
9421         }
9422         return nested_vmx_succeed(vcpu);
9423 }
9424
9425 /* Emulate the INVEPT instruction */
9426 static int handle_invept(struct kvm_vcpu *vcpu)
9427 {
9428         struct vcpu_vmx *vmx = to_vmx(vcpu);
9429         u32 vmx_instruction_info, types;
9430         unsigned long type;
9431         gva_t gva;
9432         struct x86_exception e;
9433         struct {
9434                 u64 eptp, gpa;
9435         } operand;
9436
9437         if (!(vmx->nested.msrs.secondary_ctls_high &
9438               SECONDARY_EXEC_ENABLE_EPT) ||
9439             !(vmx->nested.msrs.ept_caps & VMX_EPT_INVEPT_BIT)) {
9440                 kvm_queue_exception(vcpu, UD_VECTOR);
9441                 return 1;
9442         }
9443
9444         if (!nested_vmx_check_permission(vcpu))
9445                 return 1;
9446
9447         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9448         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9449
9450         types = (vmx->nested.msrs.ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
9451
9452         if (type >= 32 || !(types & (1 << type)))
9453                 return nested_vmx_failValid(vcpu,
9454                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9455
9456         /* According to the Intel VMX instruction reference, the memory
9457          * operand is read even if it isn't needed (e.g., for type==global)
9458          */
9459         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9460                         vmx_instruction_info, false, &gva))
9461                 return 1;
9462         if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9463                 kvm_inject_page_fault(vcpu, &e);
9464                 return 1;
9465         }
9466
9467         switch (type) {
9468         case VMX_EPT_EXTENT_GLOBAL:
9469         /*
9470          * TODO: track mappings and invalidate
9471          * single context requests appropriately
9472          */
9473         case VMX_EPT_EXTENT_CONTEXT:
9474                 kvm_mmu_sync_roots(vcpu);
9475                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
9476                 break;
9477         default:
9478                 BUG_ON(1);
9479                 break;
9480         }
9481
9482         return nested_vmx_succeed(vcpu);
9483 }
9484
9485 static u16 nested_get_vpid02(struct kvm_vcpu *vcpu)
9486 {
9487         struct vcpu_vmx *vmx = to_vmx(vcpu);
9488
9489         return vmx->nested.vpid02 ? vmx->nested.vpid02 : vmx->vpid;
9490 }
9491
9492 static int handle_invvpid(struct kvm_vcpu *vcpu)
9493 {
9494         struct vcpu_vmx *vmx = to_vmx(vcpu);
9495         u32 vmx_instruction_info;
9496         unsigned long type, types;
9497         gva_t gva;
9498         struct x86_exception e;
9499         struct {
9500                 u64 vpid;
9501                 u64 gla;
9502         } operand;
9503         u16 vpid02;
9504
9505         if (!(vmx->nested.msrs.secondary_ctls_high &
9506               SECONDARY_EXEC_ENABLE_VPID) ||
9507                         !(vmx->nested.msrs.vpid_caps & VMX_VPID_INVVPID_BIT)) {
9508                 kvm_queue_exception(vcpu, UD_VECTOR);
9509                 return 1;
9510         }
9511
9512         if (!nested_vmx_check_permission(vcpu))
9513                 return 1;
9514
9515         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9516         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9517
9518         types = (vmx->nested.msrs.vpid_caps &
9519                         VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
9520
9521         if (type >= 32 || !(types & (1 << type)))
9522                 return nested_vmx_failValid(vcpu,
9523                         VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9524
9525         /* according to the intel vmx instruction reference, the memory
9526          * operand is read even if it isn't needed (e.g., for type==global)
9527          */
9528         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9529                         vmx_instruction_info, false, &gva))
9530                 return 1;
9531         if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9532                 kvm_inject_page_fault(vcpu, &e);
9533                 return 1;
9534         }
9535         if (operand.vpid >> 16)
9536                 return nested_vmx_failValid(vcpu,
9537                         VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9538
9539         vpid02 = nested_get_vpid02(vcpu);
9540         switch (type) {
9541         case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
9542                 if (!operand.vpid ||
9543                     is_noncanonical_address(operand.gla, vcpu))
9544                         return nested_vmx_failValid(vcpu,
9545                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9546                 if (cpu_has_vmx_invvpid_individual_addr()) {
9547                         __invvpid(VMX_VPID_EXTENT_INDIVIDUAL_ADDR,
9548                                 vpid02, operand.gla);
9549                 } else
9550                         __vmx_flush_tlb(vcpu, vpid02, false);
9551                 break;
9552         case VMX_VPID_EXTENT_SINGLE_CONTEXT:
9553         case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
9554                 if (!operand.vpid)
9555                         return nested_vmx_failValid(vcpu,
9556                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9557                 __vmx_flush_tlb(vcpu, vpid02, false);
9558                 break;
9559         case VMX_VPID_EXTENT_ALL_CONTEXT:
9560                 __vmx_flush_tlb(vcpu, vpid02, false);
9561                 break;
9562         default:
9563                 WARN_ON_ONCE(1);
9564                 return kvm_skip_emulated_instruction(vcpu);
9565         }
9566
9567         return nested_vmx_succeed(vcpu);
9568 }
9569
9570 static int handle_invpcid(struct kvm_vcpu *vcpu)
9571 {
9572         u32 vmx_instruction_info;
9573         unsigned long type;
9574         bool pcid_enabled;
9575         gva_t gva;
9576         struct x86_exception e;
9577         unsigned i;
9578         unsigned long roots_to_free = 0;
9579         struct {
9580                 u64 pcid;
9581                 u64 gla;
9582         } operand;
9583
9584         if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
9585                 kvm_queue_exception(vcpu, UD_VECTOR);
9586                 return 1;
9587         }
9588
9589         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9590         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9591
9592         if (type > 3) {
9593                 kvm_inject_gp(vcpu, 0);
9594                 return 1;
9595         }
9596
9597         /* According to the Intel instruction reference, the memory operand
9598          * is read even if it isn't needed (e.g., for type==all)
9599          */
9600         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9601                                 vmx_instruction_info, false, &gva))
9602                 return 1;
9603
9604         if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9605                 kvm_inject_page_fault(vcpu, &e);
9606                 return 1;
9607         }
9608
9609         if (operand.pcid >> 12 != 0) {
9610                 kvm_inject_gp(vcpu, 0);
9611                 return 1;
9612         }
9613
9614         pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
9615
9616         switch (type) {
9617         case INVPCID_TYPE_INDIV_ADDR:
9618                 if ((!pcid_enabled && (operand.pcid != 0)) ||
9619                     is_noncanonical_address(operand.gla, vcpu)) {
9620                         kvm_inject_gp(vcpu, 0);
9621                         return 1;
9622                 }
9623                 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
9624                 return kvm_skip_emulated_instruction(vcpu);
9625
9626         case INVPCID_TYPE_SINGLE_CTXT:
9627                 if (!pcid_enabled && (operand.pcid != 0)) {
9628                         kvm_inject_gp(vcpu, 0);
9629                         return 1;
9630                 }
9631
9632                 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
9633                         kvm_mmu_sync_roots(vcpu);
9634                         kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
9635                 }
9636
9637                 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
9638                         if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].cr3)
9639                             == operand.pcid)
9640                                 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
9641
9642                 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
9643                 /*
9644                  * If neither the current cr3 nor any of the prev_roots use the
9645                  * given PCID, then nothing needs to be done here because a
9646                  * resync will happen anyway before switching to any other CR3.
9647                  */
9648
9649                 return kvm_skip_emulated_instruction(vcpu);
9650
9651         case INVPCID_TYPE_ALL_NON_GLOBAL:
9652                 /*
9653                  * Currently, KVM doesn't mark global entries in the shadow
9654                  * page tables, so a non-global flush just degenerates to a
9655                  * global flush. If needed, we could optimize this later by
9656                  * keeping track of global entries in shadow page tables.
9657                  */
9658
9659                 /* fall-through */
9660         case INVPCID_TYPE_ALL_INCL_GLOBAL:
9661                 kvm_mmu_unload(vcpu);
9662                 return kvm_skip_emulated_instruction(vcpu);
9663
9664         default:
9665                 BUG(); /* We have already checked above that type <= 3 */
9666         }
9667 }
9668
9669 static int handle_pml_full(struct kvm_vcpu *vcpu)
9670 {
9671         unsigned long exit_qualification;
9672
9673         trace_kvm_pml_full(vcpu->vcpu_id);
9674
9675         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9676
9677         /*
9678          * PML buffer FULL happened while executing iret from NMI,
9679          * "blocked by NMI" bit has to be set before next VM entry.
9680          */
9681         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
9682                         enable_vnmi &&
9683                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
9684                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
9685                                 GUEST_INTR_STATE_NMI);
9686
9687         /*
9688          * PML buffer already flushed at beginning of VMEXIT. Nothing to do
9689          * here.., and there's no userspace involvement needed for PML.
9690          */
9691         return 1;
9692 }
9693
9694 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
9695 {
9696         if (!to_vmx(vcpu)->req_immediate_exit)
9697                 kvm_lapic_expired_hv_timer(vcpu);
9698         return 1;
9699 }
9700
9701 static bool valid_ept_address(struct kvm_vcpu *vcpu, u64 address)
9702 {
9703         struct vcpu_vmx *vmx = to_vmx(vcpu);
9704         int maxphyaddr = cpuid_maxphyaddr(vcpu);
9705
9706         /* Check for memory type validity */
9707         switch (address & VMX_EPTP_MT_MASK) {
9708         case VMX_EPTP_MT_UC:
9709                 if (!(vmx->nested.msrs.ept_caps & VMX_EPTP_UC_BIT))
9710                         return false;
9711                 break;
9712         case VMX_EPTP_MT_WB:
9713                 if (!(vmx->nested.msrs.ept_caps & VMX_EPTP_WB_BIT))
9714                         return false;
9715                 break;
9716         default:
9717                 return false;
9718         }
9719
9720         /* only 4 levels page-walk length are valid */
9721         if ((address & VMX_EPTP_PWL_MASK) != VMX_EPTP_PWL_4)
9722                 return false;
9723
9724         /* Reserved bits should not be set */
9725         if (address >> maxphyaddr || ((address >> 7) & 0x1f))
9726                 return false;
9727
9728         /* AD, if set, should be supported */
9729         if (address & VMX_EPTP_AD_ENABLE_BIT) {
9730                 if (!(vmx->nested.msrs.ept_caps & VMX_EPT_AD_BIT))
9731                         return false;
9732         }
9733
9734         return true;
9735 }
9736
9737 static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
9738                                      struct vmcs12 *vmcs12)
9739 {
9740         u32 index = vcpu->arch.regs[VCPU_REGS_RCX];
9741         u64 address;
9742         bool accessed_dirty;
9743         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
9744
9745         if (!nested_cpu_has_eptp_switching(vmcs12) ||
9746             !nested_cpu_has_ept(vmcs12))
9747                 return 1;
9748
9749         if (index >= VMFUNC_EPTP_ENTRIES)
9750                 return 1;
9751
9752
9753         if (kvm_vcpu_read_guest_page(vcpu, vmcs12->eptp_list_address >> PAGE_SHIFT,
9754                                      &address, index * 8, 8))
9755                 return 1;
9756
9757         accessed_dirty = !!(address & VMX_EPTP_AD_ENABLE_BIT);
9758
9759         /*
9760          * If the (L2) guest does a vmfunc to the currently
9761          * active ept pointer, we don't have to do anything else
9762          */
9763         if (vmcs12->ept_pointer != address) {
9764                 if (!valid_ept_address(vcpu, address))
9765                         return 1;
9766
9767                 kvm_mmu_unload(vcpu);
9768                 mmu->ept_ad = accessed_dirty;
9769                 mmu->mmu_role.base.ad_disabled = !accessed_dirty;
9770                 vmcs12->ept_pointer = address;
9771                 /*
9772                  * TODO: Check what's the correct approach in case
9773                  * mmu reload fails. Currently, we just let the next
9774                  * reload potentially fail
9775                  */
9776                 kvm_mmu_reload(vcpu);
9777         }
9778
9779         return 0;
9780 }
9781
9782 static int handle_vmfunc(struct kvm_vcpu *vcpu)
9783 {
9784         struct vcpu_vmx *vmx = to_vmx(vcpu);
9785         struct vmcs12 *vmcs12;
9786         u32 function = vcpu->arch.regs[VCPU_REGS_RAX];
9787
9788         /*
9789          * VMFUNC is only supported for nested guests, but we always enable the
9790          * secondary control for simplicity; for non-nested mode, fake that we
9791          * didn't by injecting #UD.
9792          */
9793         if (!is_guest_mode(vcpu)) {
9794                 kvm_queue_exception(vcpu, UD_VECTOR);
9795                 return 1;
9796         }
9797
9798         vmcs12 = get_vmcs12(vcpu);
9799         if ((vmcs12->vm_function_control & (1 << function)) == 0)
9800                 goto fail;
9801
9802         switch (function) {
9803         case 0:
9804                 if (nested_vmx_eptp_switching(vcpu, vmcs12))
9805                         goto fail;
9806                 break;
9807         default:
9808                 goto fail;
9809         }
9810         return kvm_skip_emulated_instruction(vcpu);
9811
9812 fail:
9813         nested_vmx_vmexit(vcpu, vmx->exit_reason,
9814                           vmcs_read32(VM_EXIT_INTR_INFO),
9815                           vmcs_readl(EXIT_QUALIFICATION));
9816         return 1;
9817 }
9818
9819 static int handle_encls(struct kvm_vcpu *vcpu)
9820 {
9821         /*
9822          * SGX virtualization is not yet supported.  There is no software
9823          * enable bit for SGX, so we have to trap ENCLS and inject a #UD
9824          * to prevent the guest from executing ENCLS.
9825          */
9826         kvm_queue_exception(vcpu, UD_VECTOR);
9827         return 1;
9828 }
9829
9830 /*
9831  * The exit handlers return 1 if the exit was handled fully and guest execution
9832  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
9833  * to be done to userspace and return 0.
9834  */
9835 static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
9836         [EXIT_REASON_EXCEPTION_NMI]           = handle_exception,
9837         [EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
9838         [EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
9839         [EXIT_REASON_NMI_WINDOW]              = handle_nmi_window,
9840         [EXIT_REASON_IO_INSTRUCTION]          = handle_io,
9841         [EXIT_REASON_CR_ACCESS]               = handle_cr,
9842         [EXIT_REASON_DR_ACCESS]               = handle_dr,
9843         [EXIT_REASON_CPUID]                   = handle_cpuid,
9844         [EXIT_REASON_MSR_READ]                = handle_rdmsr,
9845         [EXIT_REASON_MSR_WRITE]               = handle_wrmsr,
9846         [EXIT_REASON_PENDING_INTERRUPT]       = handle_interrupt_window,
9847         [EXIT_REASON_HLT]                     = handle_halt,
9848         [EXIT_REASON_INVD]                    = handle_invd,
9849         [EXIT_REASON_INVLPG]                  = handle_invlpg,
9850         [EXIT_REASON_RDPMC]                   = handle_rdpmc,
9851         [EXIT_REASON_VMCALL]                  = handle_vmcall,
9852         [EXIT_REASON_VMCLEAR]                 = handle_vmclear,
9853         [EXIT_REASON_VMLAUNCH]                = handle_vmlaunch,
9854         [EXIT_REASON_VMPTRLD]                 = handle_vmptrld,
9855         [EXIT_REASON_VMPTRST]                 = handle_vmptrst,
9856         [EXIT_REASON_VMREAD]                  = handle_vmread,
9857         [EXIT_REASON_VMRESUME]                = handle_vmresume,
9858         [EXIT_REASON_VMWRITE]                 = handle_vmwrite,
9859         [EXIT_REASON_VMOFF]                   = handle_vmoff,
9860         [EXIT_REASON_VMON]                    = handle_vmon,
9861         [EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
9862         [EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
9863         [EXIT_REASON_APIC_WRITE]              = handle_apic_write,
9864         [EXIT_REASON_EOI_INDUCED]             = handle_apic_eoi_induced,
9865         [EXIT_REASON_WBINVD]                  = handle_wbinvd,
9866         [EXIT_REASON_XSETBV]                  = handle_xsetbv,
9867         [EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
9868         [EXIT_REASON_MCE_DURING_VMENTRY]      = handle_machine_check,
9869         [EXIT_REASON_GDTR_IDTR]               = handle_desc,
9870         [EXIT_REASON_LDTR_TR]                 = handle_desc,
9871         [EXIT_REASON_EPT_VIOLATION]           = handle_ept_violation,
9872         [EXIT_REASON_EPT_MISCONFIG]           = handle_ept_misconfig,
9873         [EXIT_REASON_PAUSE_INSTRUCTION]       = handle_pause,
9874         [EXIT_REASON_MWAIT_INSTRUCTION]       = handle_mwait,
9875         [EXIT_REASON_MONITOR_TRAP_FLAG]       = handle_monitor_trap,
9876         [EXIT_REASON_MONITOR_INSTRUCTION]     = handle_monitor,
9877         [EXIT_REASON_INVEPT]                  = handle_invept,
9878         [EXIT_REASON_INVVPID]                 = handle_invvpid,
9879         [EXIT_REASON_RDRAND]                  = handle_invalid_op,
9880         [EXIT_REASON_RDSEED]                  = handle_invalid_op,
9881         [EXIT_REASON_XSAVES]                  = handle_xsaves,
9882         [EXIT_REASON_XRSTORS]                 = handle_xrstors,
9883         [EXIT_REASON_PML_FULL]                = handle_pml_full,
9884         [EXIT_REASON_INVPCID]                 = handle_invpcid,
9885         [EXIT_REASON_VMFUNC]                  = handle_vmfunc,
9886         [EXIT_REASON_PREEMPTION_TIMER]        = handle_preemption_timer,
9887         [EXIT_REASON_ENCLS]                   = handle_encls,
9888 };
9889
9890 static const int kvm_vmx_max_exit_handlers =
9891         ARRAY_SIZE(kvm_vmx_exit_handlers);
9892
9893 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
9894                                        struct vmcs12 *vmcs12)
9895 {
9896         unsigned long exit_qualification;
9897         gpa_t bitmap, last_bitmap;
9898         unsigned int port;
9899         int size;
9900         u8 b;
9901
9902         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
9903                 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
9904
9905         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9906
9907         port = exit_qualification >> 16;
9908         size = (exit_qualification & 7) + 1;
9909
9910         last_bitmap = (gpa_t)-1;
9911         b = -1;
9912
9913         while (size > 0) {
9914                 if (port < 0x8000)
9915                         bitmap = vmcs12->io_bitmap_a;
9916                 else if (port < 0x10000)
9917                         bitmap = vmcs12->io_bitmap_b;
9918                 else
9919                         return true;
9920                 bitmap += (port & 0x7fff) / 8;
9921
9922                 if (last_bitmap != bitmap)
9923                         if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
9924                                 return true;
9925                 if (b & (1 << (port & 7)))
9926                         return true;
9927
9928                 port++;
9929                 size--;
9930                 last_bitmap = bitmap;
9931         }
9932
9933         return false;
9934 }
9935
9936 /*
9937  * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
9938  * rather than handle it ourselves in L0. I.e., check whether L1 expressed
9939  * disinterest in the current event (read or write a specific MSR) by using an
9940  * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
9941  */
9942 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
9943         struct vmcs12 *vmcs12, u32 exit_reason)
9944 {
9945         u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
9946         gpa_t bitmap;
9947
9948         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
9949                 return true;
9950
9951         /*
9952          * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
9953          * for the four combinations of read/write and low/high MSR numbers.
9954          * First we need to figure out which of the four to use:
9955          */
9956         bitmap = vmcs12->msr_bitmap;
9957         if (exit_reason == EXIT_REASON_MSR_WRITE)
9958                 bitmap += 2048;
9959         if (msr_index >= 0xc0000000) {
9960                 msr_index -= 0xc0000000;
9961                 bitmap += 1024;
9962         }
9963
9964         /* Then read the msr_index'th bit from this bitmap: */
9965         if (msr_index < 1024*8) {
9966                 unsigned char b;
9967                 if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
9968                         return true;
9969                 return 1 & (b >> (msr_index & 7));
9970         } else
9971                 return true; /* let L1 handle the wrong parameter */
9972 }
9973
9974 /*
9975  * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
9976  * rather than handle it ourselves in L0. I.e., check if L1 wanted to
9977  * intercept (via guest_host_mask etc.) the current event.
9978  */
9979 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
9980         struct vmcs12 *vmcs12)
9981 {
9982         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9983         int cr = exit_qualification & 15;
9984         int reg;
9985         unsigned long val;
9986
9987         switch ((exit_qualification >> 4) & 3) {
9988         case 0: /* mov to cr */
9989                 reg = (exit_qualification >> 8) & 15;
9990                 val = kvm_register_readl(vcpu, reg);
9991                 switch (cr) {
9992                 case 0:
9993                         if (vmcs12->cr0_guest_host_mask &
9994                             (val ^ vmcs12->cr0_read_shadow))
9995                                 return true;
9996                         break;
9997                 case 3:
9998                         if ((vmcs12->cr3_target_count >= 1 &&
9999                                         vmcs12->cr3_target_value0 == val) ||
10000                                 (vmcs12->cr3_target_count >= 2 &&
10001                                         vmcs12->cr3_target_value1 == val) ||
10002                                 (vmcs12->cr3_target_count >= 3 &&
10003                                         vmcs12->cr3_target_value2 == val) ||
10004                                 (vmcs12->cr3_target_count >= 4 &&
10005                                         vmcs12->cr3_target_value3 == val))
10006                                 return false;
10007                         if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
10008                                 return true;
10009                         break;
10010                 case 4:
10011                         if (vmcs12->cr4_guest_host_mask &
10012                             (vmcs12->cr4_read_shadow ^ val))
10013                                 return true;
10014                         break;
10015                 case 8:
10016                         if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
10017                                 return true;
10018                         break;
10019                 }
10020                 break;
10021         case 2: /* clts */
10022                 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
10023                     (vmcs12->cr0_read_shadow & X86_CR0_TS))
10024                         return true;
10025                 break;
10026         case 1: /* mov from cr */
10027                 switch (cr) {
10028                 case 3:
10029                         if (vmcs12->cpu_based_vm_exec_control &
10030                             CPU_BASED_CR3_STORE_EXITING)
10031                                 return true;
10032                         break;
10033                 case 8:
10034                         if (vmcs12->cpu_based_vm_exec_control &
10035                             CPU_BASED_CR8_STORE_EXITING)
10036                                 return true;
10037                         break;
10038                 }
10039                 break;
10040         case 3: /* lmsw */
10041                 /*
10042                  * lmsw can change bits 1..3 of cr0, and only set bit 0 of
10043                  * cr0. Other attempted changes are ignored, with no exit.
10044                  */
10045                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
10046                 if (vmcs12->cr0_guest_host_mask & 0xe &
10047                     (val ^ vmcs12->cr0_read_shadow))
10048                         return true;
10049                 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
10050                     !(vmcs12->cr0_read_shadow & 0x1) &&
10051                     (val & 0x1))
10052                         return true;
10053                 break;
10054         }
10055         return false;
10056 }
10057
10058 static bool nested_vmx_exit_handled_vmcs_access(struct kvm_vcpu *vcpu,
10059         struct vmcs12 *vmcs12, gpa_t bitmap)
10060 {
10061         u32 vmx_instruction_info;
10062         unsigned long field;
10063         u8 b;
10064
10065         if (!nested_cpu_has_shadow_vmcs(vmcs12))
10066                 return true;
10067
10068         /* Decode instruction info and find the field to access */
10069         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
10070         field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
10071
10072         /* Out-of-range fields always cause a VM exit from L2 to L1 */
10073         if (field >> 15)
10074                 return true;
10075
10076         if (kvm_vcpu_read_guest(vcpu, bitmap + field/8, &b, 1))
10077                 return true;
10078
10079         return 1 & (b >> (field & 7));
10080 }
10081
10082 /*
10083  * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
10084  * should handle it ourselves in L0 (and then continue L2). Only call this
10085  * when in is_guest_mode (L2).
10086  */
10087 static bool nested_vmx_exit_reflected(struct kvm_vcpu *vcpu, u32 exit_reason)
10088 {
10089         u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10090         struct vcpu_vmx *vmx = to_vmx(vcpu);
10091         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10092
10093         if (vmx->nested.nested_run_pending)
10094                 return false;
10095
10096         if (unlikely(vmx->fail)) {
10097                 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
10098                                     vmcs_read32(VM_INSTRUCTION_ERROR));
10099                 return true;
10100         }
10101
10102         /*
10103          * The host physical addresses of some pages of guest memory
10104          * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
10105          * Page). The CPU may write to these pages via their host
10106          * physical address while L2 is running, bypassing any
10107          * address-translation-based dirty tracking (e.g. EPT write
10108          * protection).
10109          *
10110          * Mark them dirty on every exit from L2 to prevent them from
10111          * getting out of sync with dirty tracking.
10112          */
10113         nested_mark_vmcs12_pages_dirty(vcpu);
10114
10115         trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
10116                                 vmcs_readl(EXIT_QUALIFICATION),
10117                                 vmx->idt_vectoring_info,
10118                                 intr_info,
10119                                 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
10120                                 KVM_ISA_VMX);
10121
10122         switch (exit_reason) {
10123         case EXIT_REASON_EXCEPTION_NMI:
10124                 if (is_nmi(intr_info))
10125                         return false;
10126                 else if (is_page_fault(intr_info))
10127                         return !vmx->vcpu.arch.apf.host_apf_reason && enable_ept;
10128                 else if (is_debug(intr_info) &&
10129                          vcpu->guest_debug &
10130                          (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
10131                         return false;
10132                 else if (is_breakpoint(intr_info) &&
10133                          vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
10134                         return false;
10135                 return vmcs12->exception_bitmap &
10136                                 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
10137         case EXIT_REASON_EXTERNAL_INTERRUPT:
10138                 return false;
10139         case EXIT_REASON_TRIPLE_FAULT:
10140                 return true;
10141         case EXIT_REASON_PENDING_INTERRUPT:
10142                 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
10143         case EXIT_REASON_NMI_WINDOW:
10144                 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
10145         case EXIT_REASON_TASK_SWITCH:
10146                 return true;
10147         case EXIT_REASON_CPUID:
10148                 return true;
10149         case EXIT_REASON_HLT:
10150                 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
10151         case EXIT_REASON_INVD:
10152                 return true;
10153         case EXIT_REASON_INVLPG:
10154                 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
10155         case EXIT_REASON_RDPMC:
10156                 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
10157         case EXIT_REASON_RDRAND:
10158                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDRAND_EXITING);
10159         case EXIT_REASON_RDSEED:
10160                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDSEED_EXITING);
10161         case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
10162                 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
10163         case EXIT_REASON_VMREAD:
10164                 return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
10165                         vmcs12->vmread_bitmap);
10166         case EXIT_REASON_VMWRITE:
10167                 return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
10168                         vmcs12->vmwrite_bitmap);
10169         case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
10170         case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
10171         case EXIT_REASON_VMPTRST: case EXIT_REASON_VMRESUME:
10172         case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
10173         case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
10174                 /*
10175                  * VMX instructions trap unconditionally. This allows L1 to
10176                  * emulate them for its L2 guest, i.e., allows 3-level nesting!
10177                  */
10178                 return true;
10179         case EXIT_REASON_CR_ACCESS:
10180                 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
10181         case EXIT_REASON_DR_ACCESS:
10182                 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
10183         case EXIT_REASON_IO_INSTRUCTION:
10184                 return nested_vmx_exit_handled_io(vcpu, vmcs12);
10185         case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
10186                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
10187         case EXIT_REASON_MSR_READ:
10188         case EXIT_REASON_MSR_WRITE:
10189                 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
10190         case EXIT_REASON_INVALID_STATE:
10191                 return true;
10192         case EXIT_REASON_MWAIT_INSTRUCTION:
10193                 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
10194         case EXIT_REASON_MONITOR_TRAP_FLAG:
10195                 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG);
10196         case EXIT_REASON_MONITOR_INSTRUCTION:
10197                 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
10198         case EXIT_REASON_PAUSE_INSTRUCTION:
10199                 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
10200                         nested_cpu_has2(vmcs12,
10201                                 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
10202         case EXIT_REASON_MCE_DURING_VMENTRY:
10203                 return false;
10204         case EXIT_REASON_TPR_BELOW_THRESHOLD:
10205                 return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
10206         case EXIT_REASON_APIC_ACCESS:
10207         case EXIT_REASON_APIC_WRITE:
10208         case EXIT_REASON_EOI_INDUCED:
10209                 /*
10210                  * The controls for "virtualize APIC accesses," "APIC-
10211                  * register virtualization," and "virtual-interrupt
10212                  * delivery" only come from vmcs12.
10213                  */
10214                 return true;
10215         case EXIT_REASON_EPT_VIOLATION:
10216                 /*
10217                  * L0 always deals with the EPT violation. If nested EPT is
10218                  * used, and the nested mmu code discovers that the address is
10219                  * missing in the guest EPT table (EPT12), the EPT violation
10220                  * will be injected with nested_ept_inject_page_fault()
10221                  */
10222                 return false;
10223         case EXIT_REASON_EPT_MISCONFIG:
10224                 /*
10225                  * L2 never uses directly L1's EPT, but rather L0's own EPT
10226                  * table (shadow on EPT) or a merged EPT table that L0 built
10227                  * (EPT on EPT). So any problems with the structure of the
10228                  * table is L0's fault.
10229                  */
10230                 return false;
10231         case EXIT_REASON_INVPCID:
10232                 return
10233                         nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_INVPCID) &&
10234                         nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
10235         case EXIT_REASON_WBINVD:
10236                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
10237         case EXIT_REASON_XSETBV:
10238                 return true;
10239         case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
10240                 /*
10241                  * This should never happen, since it is not possible to
10242                  * set XSS to a non-zero value---neither in L1 nor in L2.
10243                  * If if it were, XSS would have to be checked against
10244                  * the XSS exit bitmap in vmcs12.
10245                  */
10246                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
10247         case EXIT_REASON_PREEMPTION_TIMER:
10248                 return false;
10249         case EXIT_REASON_PML_FULL:
10250                 /* We emulate PML support to L1. */
10251                 return false;
10252         case EXIT_REASON_VMFUNC:
10253                 /* VM functions are emulated through L2->L0 vmexits. */
10254                 return false;
10255         case EXIT_REASON_ENCLS:
10256                 /* SGX is never exposed to L1 */
10257                 return false;
10258         default:
10259                 return true;
10260         }
10261 }
10262
10263 static int nested_vmx_reflect_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason)
10264 {
10265         u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10266
10267         /*
10268          * At this point, the exit interruption info in exit_intr_info
10269          * is only valid for EXCEPTION_NMI exits.  For EXTERNAL_INTERRUPT
10270          * we need to query the in-kernel LAPIC.
10271          */
10272         WARN_ON(exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT);
10273         if ((exit_intr_info &
10274              (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
10275             (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) {
10276                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10277                 vmcs12->vm_exit_intr_error_code =
10278                         vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
10279         }
10280
10281         nested_vmx_vmexit(vcpu, exit_reason, exit_intr_info,
10282                           vmcs_readl(EXIT_QUALIFICATION));
10283         return 1;
10284 }
10285
10286 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
10287 {
10288         *info1 = vmcs_readl(EXIT_QUALIFICATION);
10289         *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
10290 }
10291
10292 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
10293 {
10294         if (vmx->pml_pg) {
10295                 __free_page(vmx->pml_pg);
10296                 vmx->pml_pg = NULL;
10297         }
10298 }
10299
10300 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
10301 {
10302         struct vcpu_vmx *vmx = to_vmx(vcpu);
10303         u64 *pml_buf;
10304         u16 pml_idx;
10305
10306         pml_idx = vmcs_read16(GUEST_PML_INDEX);
10307
10308         /* Do nothing if PML buffer is empty */
10309         if (pml_idx == (PML_ENTITY_NUM - 1))
10310                 return;
10311
10312         /* PML index always points to next available PML buffer entity */
10313         if (pml_idx >= PML_ENTITY_NUM)
10314                 pml_idx = 0;
10315         else
10316                 pml_idx++;
10317
10318         pml_buf = page_address(vmx->pml_pg);
10319         for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
10320                 u64 gpa;
10321
10322                 gpa = pml_buf[pml_idx];
10323                 WARN_ON(gpa & (PAGE_SIZE - 1));
10324                 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
10325         }
10326
10327         /* reset PML index */
10328         vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
10329 }
10330
10331 /*
10332  * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
10333  * Called before reporting dirty_bitmap to userspace.
10334  */
10335 static void kvm_flush_pml_buffers(struct kvm *kvm)
10336 {
10337         int i;
10338         struct kvm_vcpu *vcpu;
10339         /*
10340          * We only need to kick vcpu out of guest mode here, as PML buffer
10341          * is flushed at beginning of all VMEXITs, and it's obvious that only
10342          * vcpus running in guest are possible to have unflushed GPAs in PML
10343          * buffer.
10344          */
10345         kvm_for_each_vcpu(i, vcpu, kvm)
10346                 kvm_vcpu_kick(vcpu);
10347 }
10348
10349 static void vmx_dump_sel(char *name, uint32_t sel)
10350 {
10351         pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
10352                name, vmcs_read16(sel),
10353                vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
10354                vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
10355                vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
10356 }
10357
10358 static void vmx_dump_dtsel(char *name, uint32_t limit)
10359 {
10360         pr_err("%s                           limit=0x%08x, base=0x%016lx\n",
10361                name, vmcs_read32(limit),
10362                vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
10363 }
10364
10365 static void dump_vmcs(void)
10366 {
10367         u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
10368         u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
10369         u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
10370         u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
10371         u32 secondary_exec_control = 0;
10372         unsigned long cr4 = vmcs_readl(GUEST_CR4);
10373         u64 efer = vmcs_read64(GUEST_IA32_EFER);
10374         int i, n;
10375
10376         if (cpu_has_secondary_exec_ctrls())
10377                 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
10378
10379         pr_err("*** Guest State ***\n");
10380         pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
10381                vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
10382                vmcs_readl(CR0_GUEST_HOST_MASK));
10383         pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
10384                cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
10385         pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
10386         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
10387             (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
10388         {
10389                 pr_err("PDPTR0 = 0x%016llx  PDPTR1 = 0x%016llx\n",
10390                        vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
10391                 pr_err("PDPTR2 = 0x%016llx  PDPTR3 = 0x%016llx\n",
10392                        vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
10393         }
10394         pr_err("RSP = 0x%016lx  RIP = 0x%016lx\n",
10395                vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
10396         pr_err("RFLAGS=0x%08lx         DR7 = 0x%016lx\n",
10397                vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
10398         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
10399                vmcs_readl(GUEST_SYSENTER_ESP),
10400                vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
10401         vmx_dump_sel("CS:  ", GUEST_CS_SELECTOR);
10402         vmx_dump_sel("DS:  ", GUEST_DS_SELECTOR);
10403         vmx_dump_sel("SS:  ", GUEST_SS_SELECTOR);
10404         vmx_dump_sel("ES:  ", GUEST_ES_SELECTOR);
10405         vmx_dump_sel("FS:  ", GUEST_FS_SELECTOR);
10406         vmx_dump_sel("GS:  ", GUEST_GS_SELECTOR);
10407         vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
10408         vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
10409         vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
10410         vmx_dump_sel("TR:  ", GUEST_TR_SELECTOR);
10411         if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
10412             (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
10413                 pr_err("EFER =     0x%016llx  PAT = 0x%016llx\n",
10414                        efer, vmcs_read64(GUEST_IA32_PAT));
10415         pr_err("DebugCtl = 0x%016llx  DebugExceptions = 0x%016lx\n",
10416                vmcs_read64(GUEST_IA32_DEBUGCTL),
10417                vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
10418         if (cpu_has_load_perf_global_ctrl &&
10419             vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
10420                 pr_err("PerfGlobCtl = 0x%016llx\n",
10421                        vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
10422         if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
10423                 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
10424         pr_err("Interruptibility = %08x  ActivityState = %08x\n",
10425                vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
10426                vmcs_read32(GUEST_ACTIVITY_STATE));
10427         if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
10428                 pr_err("InterruptStatus = %04x\n",
10429                        vmcs_read16(GUEST_INTR_STATUS));
10430
10431         pr_err("*** Host State ***\n");
10432         pr_err("RIP = 0x%016lx  RSP = 0x%016lx\n",
10433                vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
10434         pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
10435                vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
10436                vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
10437                vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
10438                vmcs_read16(HOST_TR_SELECTOR));
10439         pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
10440                vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
10441                vmcs_readl(HOST_TR_BASE));
10442         pr_err("GDTBase=%016lx IDTBase=%016lx\n",
10443                vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
10444         pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
10445                vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
10446                vmcs_readl(HOST_CR4));
10447         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
10448                vmcs_readl(HOST_IA32_SYSENTER_ESP),
10449                vmcs_read32(HOST_IA32_SYSENTER_CS),
10450                vmcs_readl(HOST_IA32_SYSENTER_EIP));
10451         if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
10452                 pr_err("EFER = 0x%016llx  PAT = 0x%016llx\n",
10453                        vmcs_read64(HOST_IA32_EFER),
10454                        vmcs_read64(HOST_IA32_PAT));
10455         if (cpu_has_load_perf_global_ctrl &&
10456             vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
10457                 pr_err("PerfGlobCtl = 0x%016llx\n",
10458                        vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
10459
10460         pr_err("*** Control State ***\n");
10461         pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
10462                pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
10463         pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
10464         pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
10465                vmcs_read32(EXCEPTION_BITMAP),
10466                vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
10467                vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
10468         pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
10469                vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
10470                vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
10471                vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
10472         pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
10473                vmcs_read32(VM_EXIT_INTR_INFO),
10474                vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
10475                vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
10476         pr_err("        reason=%08x qualification=%016lx\n",
10477                vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
10478         pr_err("IDTVectoring: info=%08x errcode=%08x\n",
10479                vmcs_read32(IDT_VECTORING_INFO_FIELD),
10480                vmcs_read32(IDT_VECTORING_ERROR_CODE));
10481         pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
10482         if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
10483                 pr_err("TSC Multiplier = 0x%016llx\n",
10484                        vmcs_read64(TSC_MULTIPLIER));
10485         if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
10486                 pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
10487         if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
10488                 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
10489         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
10490                 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
10491         n = vmcs_read32(CR3_TARGET_COUNT);
10492         for (i = 0; i + 1 < n; i += 4)
10493                 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
10494                        i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
10495                        i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
10496         if (i < n)
10497                 pr_err("CR3 target%u=%016lx\n",
10498                        i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
10499         if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
10500                 pr_err("PLE Gap=%08x Window=%08x\n",
10501                        vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
10502         if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
10503                 pr_err("Virtual processor ID = 0x%04x\n",
10504                        vmcs_read16(VIRTUAL_PROCESSOR_ID));
10505 }
10506
10507 /*
10508  * The guest has exited.  See if we can fix it or if we need userspace
10509  * assistance.
10510  */
10511 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
10512 {
10513         struct vcpu_vmx *vmx = to_vmx(vcpu);
10514         u32 exit_reason = vmx->exit_reason;
10515         u32 vectoring_info = vmx->idt_vectoring_info;
10516
10517         trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
10518
10519         /*
10520          * Flush logged GPAs PML buffer, this will make dirty_bitmap more
10521          * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
10522          * querying dirty_bitmap, we only need to kick all vcpus out of guest
10523          * mode as if vcpus is in root mode, the PML buffer must has been
10524          * flushed already.
10525          */
10526         if (enable_pml)
10527                 vmx_flush_pml_buffer(vcpu);
10528
10529         /* If guest state is invalid, start emulating */
10530         if (vmx->emulation_required)
10531                 return handle_invalid_guest_state(vcpu);
10532
10533         if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
10534                 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
10535
10536         if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
10537                 dump_vmcs();
10538                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
10539                 vcpu->run->fail_entry.hardware_entry_failure_reason
10540                         = exit_reason;
10541                 return 0;
10542         }
10543
10544         if (unlikely(vmx->fail)) {
10545                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
10546                 vcpu->run->fail_entry.hardware_entry_failure_reason
10547                         = vmcs_read32(VM_INSTRUCTION_ERROR);
10548                 return 0;
10549         }
10550
10551         /*
10552          * Note:
10553          * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
10554          * delivery event since it indicates guest is accessing MMIO.
10555          * The vm-exit can be triggered again after return to guest that
10556          * will cause infinite loop.
10557          */
10558         if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
10559                         (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
10560                         exit_reason != EXIT_REASON_EPT_VIOLATION &&
10561                         exit_reason != EXIT_REASON_PML_FULL &&
10562                         exit_reason != EXIT_REASON_TASK_SWITCH)) {
10563                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
10564                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
10565                 vcpu->run->internal.ndata = 3;
10566                 vcpu->run->internal.data[0] = vectoring_info;
10567                 vcpu->run->internal.data[1] = exit_reason;
10568                 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
10569                 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
10570                         vcpu->run->internal.ndata++;
10571                         vcpu->run->internal.data[3] =
10572                                 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
10573                 }
10574                 return 0;
10575         }
10576
10577         if (unlikely(!enable_vnmi &&
10578                      vmx->loaded_vmcs->soft_vnmi_blocked)) {
10579                 if (vmx_interrupt_allowed(vcpu)) {
10580                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
10581                 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
10582                            vcpu->arch.nmi_pending) {
10583                         /*
10584                          * This CPU don't support us in finding the end of an
10585                          * NMI-blocked window if the guest runs with IRQs
10586                          * disabled. So we pull the trigger after 1 s of
10587                          * futile waiting, but inform the user about this.
10588                          */
10589                         printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
10590                                "state on VCPU %d after 1 s timeout\n",
10591                                __func__, vcpu->vcpu_id);
10592                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
10593                 }
10594         }
10595
10596         if (exit_reason < kvm_vmx_max_exit_handlers
10597             && kvm_vmx_exit_handlers[exit_reason])
10598                 return kvm_vmx_exit_handlers[exit_reason](vcpu);
10599         else {
10600                 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
10601                                 exit_reason);
10602                 kvm_queue_exception(vcpu, UD_VECTOR);
10603                 return 1;
10604         }
10605 }
10606
10607 /*
10608  * Software based L1D cache flush which is used when microcode providing
10609  * the cache control MSR is not loaded.
10610  *
10611  * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
10612  * flush it is required to read in 64 KiB because the replacement algorithm
10613  * is not exactly LRU. This could be sized at runtime via topology
10614  * information but as all relevant affected CPUs have 32KiB L1D cache size
10615  * there is no point in doing so.
10616  */
10617 static void vmx_l1d_flush(struct kvm_vcpu *vcpu)
10618 {
10619         int size = PAGE_SIZE << L1D_CACHE_ORDER;
10620
10621         /*
10622          * This code is only executed when the the flush mode is 'cond' or
10623          * 'always'
10624          */
10625         if (static_branch_likely(&vmx_l1d_flush_cond)) {
10626                 bool flush_l1d;
10627
10628                 /*
10629                  * Clear the per-vcpu flush bit, it gets set again
10630                  * either from vcpu_run() or from one of the unsafe
10631                  * VMEXIT handlers.
10632                  */
10633                 flush_l1d = vcpu->arch.l1tf_flush_l1d;
10634                 vcpu->arch.l1tf_flush_l1d = false;
10635
10636                 /*
10637                  * Clear the per-cpu flush bit, it gets set again from
10638                  * the interrupt handlers.
10639                  */
10640                 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
10641                 kvm_clear_cpu_l1tf_flush_l1d();
10642
10643                 if (!flush_l1d)
10644                         return;
10645         }
10646
10647         vcpu->stat.l1d_flush++;
10648
10649         if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
10650                 wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
10651                 return;
10652         }
10653
10654         asm volatile(
10655                 /* First ensure the pages are in the TLB */
10656                 "xorl   %%eax, %%eax\n"
10657                 ".Lpopulate_tlb:\n\t"
10658                 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
10659                 "addl   $4096, %%eax\n\t"
10660                 "cmpl   %%eax, %[size]\n\t"
10661                 "jne    .Lpopulate_tlb\n\t"
10662                 "xorl   %%eax, %%eax\n\t"
10663                 "cpuid\n\t"
10664                 /* Now fill the cache */
10665                 "xorl   %%eax, %%eax\n"
10666                 ".Lfill_cache:\n"
10667                 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
10668                 "addl   $64, %%eax\n\t"
10669                 "cmpl   %%eax, %[size]\n\t"
10670                 "jne    .Lfill_cache\n\t"
10671                 "lfence\n"
10672                 :: [flush_pages] "r" (vmx_l1d_flush_pages),
10673                     [size] "r" (size)
10674                 : "eax", "ebx", "ecx", "edx");
10675 }
10676
10677 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
10678 {
10679         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10680
10681         if (is_guest_mode(vcpu) &&
10682                 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10683                 return;
10684
10685         if (irr == -1 || tpr < irr) {
10686                 vmcs_write32(TPR_THRESHOLD, 0);
10687                 return;
10688         }
10689
10690         vmcs_write32(TPR_THRESHOLD, irr);
10691 }
10692
10693 static void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
10694 {
10695         u32 sec_exec_control;
10696
10697         if (!lapic_in_kernel(vcpu))
10698                 return;
10699
10700         if (!flexpriority_enabled &&
10701             !cpu_has_vmx_virtualize_x2apic_mode())
10702                 return;
10703
10704         /* Postpone execution until vmcs01 is the current VMCS. */
10705         if (is_guest_mode(vcpu)) {
10706                 to_vmx(vcpu)->nested.change_vmcs01_virtual_apic_mode = true;
10707                 return;
10708         }
10709
10710         sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
10711         sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
10712                               SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
10713
10714         switch (kvm_get_apic_mode(vcpu)) {
10715         case LAPIC_MODE_INVALID:
10716                 WARN_ONCE(true, "Invalid local APIC state");
10717         case LAPIC_MODE_DISABLED:
10718                 break;
10719         case LAPIC_MODE_XAPIC:
10720                 if (flexpriority_enabled) {
10721                         sec_exec_control |=
10722                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
10723                         vmx_flush_tlb(vcpu, true);
10724                 }
10725                 break;
10726         case LAPIC_MODE_X2APIC:
10727                 if (cpu_has_vmx_virtualize_x2apic_mode())
10728                         sec_exec_control |=
10729                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
10730                 break;
10731         }
10732         vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
10733
10734         vmx_update_msr_bitmap(vcpu);
10735 }
10736
10737 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
10738 {
10739         if (!is_guest_mode(vcpu)) {
10740                 vmcs_write64(APIC_ACCESS_ADDR, hpa);
10741                 vmx_flush_tlb(vcpu, true);
10742         }
10743 }
10744
10745 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
10746 {
10747         u16 status;
10748         u8 old;
10749
10750         if (max_isr == -1)
10751                 max_isr = 0;
10752
10753         status = vmcs_read16(GUEST_INTR_STATUS);
10754         old = status >> 8;
10755         if (max_isr != old) {
10756                 status &= 0xff;
10757                 status |= max_isr << 8;
10758                 vmcs_write16(GUEST_INTR_STATUS, status);
10759         }
10760 }
10761
10762 static void vmx_set_rvi(int vector)
10763 {
10764         u16 status;
10765         u8 old;
10766
10767         if (vector == -1)
10768                 vector = 0;
10769
10770         status = vmcs_read16(GUEST_INTR_STATUS);
10771         old = (u8)status & 0xff;
10772         if ((u8)vector != old) {
10773                 status &= ~0xff;
10774                 status |= (u8)vector;
10775                 vmcs_write16(GUEST_INTR_STATUS, status);
10776         }
10777 }
10778
10779 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
10780 {
10781         /*
10782          * When running L2, updating RVI is only relevant when
10783          * vmcs12 virtual-interrupt-delivery enabled.
10784          * However, it can be enabled only when L1 also
10785          * intercepts external-interrupts and in that case
10786          * we should not update vmcs02 RVI but instead intercept
10787          * interrupt. Therefore, do nothing when running L2.
10788          */
10789         if (!is_guest_mode(vcpu))
10790                 vmx_set_rvi(max_irr);
10791 }
10792
10793 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
10794 {
10795         struct vcpu_vmx *vmx = to_vmx(vcpu);
10796         int max_irr;
10797         bool max_irr_updated;
10798
10799         WARN_ON(!vcpu->arch.apicv_active);
10800         if (pi_test_on(&vmx->pi_desc)) {
10801                 pi_clear_on(&vmx->pi_desc);
10802                 /*
10803                  * IOMMU can write to PIR.ON, so the barrier matters even on UP.
10804                  * But on x86 this is just a compiler barrier anyway.
10805                  */
10806                 smp_mb__after_atomic();
10807                 max_irr_updated =
10808                         kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
10809
10810                 /*
10811                  * If we are running L2 and L1 has a new pending interrupt
10812                  * which can be injected, we should re-evaluate
10813                  * what should be done with this new L1 interrupt.
10814                  * If L1 intercepts external-interrupts, we should
10815                  * exit from L2 to L1. Otherwise, interrupt should be
10816                  * delivered directly to L2.
10817                  */
10818                 if (is_guest_mode(vcpu) && max_irr_updated) {
10819                         if (nested_exit_on_intr(vcpu))
10820                                 kvm_vcpu_exiting_guest_mode(vcpu);
10821                         else
10822                                 kvm_make_request(KVM_REQ_EVENT, vcpu);
10823                 }
10824         } else {
10825                 max_irr = kvm_lapic_find_highest_irr(vcpu);
10826         }
10827         vmx_hwapic_irr_update(vcpu, max_irr);
10828         return max_irr;
10829 }
10830
10831 static u8 vmx_has_apicv_interrupt(struct kvm_vcpu *vcpu)
10832 {
10833         u8 rvi = vmx_get_rvi();
10834         u8 vppr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_PROCPRI);
10835
10836         return ((rvi & 0xf0) > (vppr & 0xf0));
10837 }
10838
10839 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
10840 {
10841         if (!kvm_vcpu_apicv_active(vcpu))
10842                 return;
10843
10844         vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
10845         vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
10846         vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
10847         vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
10848 }
10849
10850 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
10851 {
10852         struct vcpu_vmx *vmx = to_vmx(vcpu);
10853
10854         pi_clear_on(&vmx->pi_desc);
10855         memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
10856 }
10857
10858 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
10859 {
10860         u32 exit_intr_info = 0;
10861         u16 basic_exit_reason = (u16)vmx->exit_reason;
10862
10863         if (!(basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
10864               || basic_exit_reason == EXIT_REASON_EXCEPTION_NMI))
10865                 return;
10866
10867         if (!(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
10868                 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10869         vmx->exit_intr_info = exit_intr_info;
10870
10871         /* if exit due to PF check for async PF */
10872         if (is_page_fault(exit_intr_info))
10873                 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
10874
10875         /* Handle machine checks before interrupts are enabled */
10876         if (basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY ||
10877             is_machine_check(exit_intr_info))
10878                 kvm_machine_check();
10879
10880         /* We need to handle NMIs before interrupts are enabled */
10881         if (is_nmi(exit_intr_info)) {
10882                 kvm_before_interrupt(&vmx->vcpu);
10883                 asm("int $2");
10884                 kvm_after_interrupt(&vmx->vcpu);
10885         }
10886 }
10887
10888 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
10889 {
10890         u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10891
10892         if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
10893                         == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
10894                 unsigned int vector;
10895                 unsigned long entry;
10896                 gate_desc *desc;
10897                 struct vcpu_vmx *vmx = to_vmx(vcpu);
10898 #ifdef CONFIG_X86_64
10899                 unsigned long tmp;
10900 #endif
10901
10902                 vector =  exit_intr_info & INTR_INFO_VECTOR_MASK;
10903                 desc = (gate_desc *)vmx->host_idt_base + vector;
10904                 entry = gate_offset(desc);
10905                 asm volatile(
10906 #ifdef CONFIG_X86_64
10907                         "mov %%" _ASM_SP ", %[sp]\n\t"
10908                         "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
10909                         "push $%c[ss]\n\t"
10910                         "push %[sp]\n\t"
10911 #endif
10912                         "pushf\n\t"
10913                         __ASM_SIZE(push) " $%c[cs]\n\t"
10914                         CALL_NOSPEC
10915                         :
10916 #ifdef CONFIG_X86_64
10917                         [sp]"=&r"(tmp),
10918 #endif
10919                         ASM_CALL_CONSTRAINT
10920                         :
10921                         THUNK_TARGET(entry),
10922                         [ss]"i"(__KERNEL_DS),
10923                         [cs]"i"(__KERNEL_CS)
10924                         );
10925         }
10926 }
10927 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
10928
10929 static bool vmx_has_emulated_msr(int index)
10930 {
10931         switch (index) {
10932         case MSR_IA32_SMBASE:
10933                 /*
10934                  * We cannot do SMM unless we can run the guest in big
10935                  * real mode.
10936                  */
10937                 return enable_unrestricted_guest || emulate_invalid_guest_state;
10938         case MSR_AMD64_VIRT_SPEC_CTRL:
10939                 /* This is AMD only.  */
10940                 return false;
10941         default:
10942                 return true;
10943         }
10944 }
10945
10946 static bool vmx_mpx_supported(void)
10947 {
10948         return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
10949                 (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
10950 }
10951
10952 static bool vmx_xsaves_supported(void)
10953 {
10954         return vmcs_config.cpu_based_2nd_exec_ctrl &
10955                 SECONDARY_EXEC_XSAVES;
10956 }
10957
10958 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
10959 {
10960         u32 exit_intr_info;
10961         bool unblock_nmi;
10962         u8 vector;
10963         bool idtv_info_valid;
10964
10965         idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
10966
10967         if (enable_vnmi) {
10968                 if (vmx->loaded_vmcs->nmi_known_unmasked)
10969                         return;
10970                 /*
10971                  * Can't use vmx->exit_intr_info since we're not sure what
10972                  * the exit reason is.
10973                  */
10974                 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10975                 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
10976                 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
10977                 /*
10978                  * SDM 3: 27.7.1.2 (September 2008)
10979                  * Re-set bit "block by NMI" before VM entry if vmexit caused by
10980                  * a guest IRET fault.
10981                  * SDM 3: 23.2.2 (September 2008)
10982                  * Bit 12 is undefined in any of the following cases:
10983                  *  If the VM exit sets the valid bit in the IDT-vectoring
10984                  *   information field.
10985                  *  If the VM exit is due to a double fault.
10986                  */
10987                 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
10988                     vector != DF_VECTOR && !idtv_info_valid)
10989                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
10990                                       GUEST_INTR_STATE_NMI);
10991                 else
10992                         vmx->loaded_vmcs->nmi_known_unmasked =
10993                                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
10994                                   & GUEST_INTR_STATE_NMI);
10995         } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
10996                 vmx->loaded_vmcs->vnmi_blocked_time +=
10997                         ktime_to_ns(ktime_sub(ktime_get(),
10998                                               vmx->loaded_vmcs->entry_time));
10999 }
11000
11001 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
11002                                       u32 idt_vectoring_info,
11003                                       int instr_len_field,
11004                                       int error_code_field)
11005 {
11006         u8 vector;
11007         int type;
11008         bool idtv_info_valid;
11009
11010         idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
11011
11012         vcpu->arch.nmi_injected = false;
11013         kvm_clear_exception_queue(vcpu);
11014         kvm_clear_interrupt_queue(vcpu);
11015
11016         if (!idtv_info_valid)
11017                 return;
11018
11019         kvm_make_request(KVM_REQ_EVENT, vcpu);
11020
11021         vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
11022         type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
11023
11024         switch (type) {
11025         case INTR_TYPE_NMI_INTR:
11026                 vcpu->arch.nmi_injected = true;
11027                 /*
11028                  * SDM 3: 27.7.1.2 (September 2008)
11029                  * Clear bit "block by NMI" before VM entry if a NMI
11030                  * delivery faulted.
11031                  */
11032                 vmx_set_nmi_mask(vcpu, false);
11033                 break;
11034         case INTR_TYPE_SOFT_EXCEPTION:
11035                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
11036                 /* fall through */
11037         case INTR_TYPE_HARD_EXCEPTION:
11038                 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
11039                         u32 err = vmcs_read32(error_code_field);
11040                         kvm_requeue_exception_e(vcpu, vector, err);
11041                 } else
11042                         kvm_requeue_exception(vcpu, vector);
11043                 break;
11044         case INTR_TYPE_SOFT_INTR:
11045                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
11046                 /* fall through */
11047         case INTR_TYPE_EXT_INTR:
11048                 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
11049                 break;
11050         default:
11051                 break;
11052         }
11053 }
11054
11055 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
11056 {
11057         __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
11058                                   VM_EXIT_INSTRUCTION_LEN,
11059                                   IDT_VECTORING_ERROR_CODE);
11060 }
11061
11062 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
11063 {
11064         __vmx_complete_interrupts(vcpu,
11065                                   vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
11066                                   VM_ENTRY_INSTRUCTION_LEN,
11067                                   VM_ENTRY_EXCEPTION_ERROR_CODE);
11068
11069         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
11070 }
11071
11072 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
11073 {
11074         int i, nr_msrs;
11075         struct perf_guest_switch_msr *msrs;
11076
11077         msrs = perf_guest_get_msrs(&nr_msrs);
11078
11079         if (!msrs)
11080                 return;
11081
11082         for (i = 0; i < nr_msrs; i++)
11083                 if (msrs[i].host == msrs[i].guest)
11084                         clear_atomic_switch_msr(vmx, msrs[i].msr);
11085                 else
11086                         add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
11087                                         msrs[i].host, false);
11088 }
11089
11090 static void vmx_arm_hv_timer(struct vcpu_vmx *vmx, u32 val)
11091 {
11092         vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, val);
11093         if (!vmx->loaded_vmcs->hv_timer_armed)
11094                 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
11095                               PIN_BASED_VMX_PREEMPTION_TIMER);
11096         vmx->loaded_vmcs->hv_timer_armed = true;
11097 }
11098
11099 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
11100 {
11101         struct vcpu_vmx *vmx = to_vmx(vcpu);
11102         u64 tscl;
11103         u32 delta_tsc;
11104
11105         if (vmx->req_immediate_exit) {
11106                 vmx_arm_hv_timer(vmx, 0);
11107                 return;
11108         }
11109
11110         if (vmx->hv_deadline_tsc != -1) {
11111                 tscl = rdtsc();
11112                 if (vmx->hv_deadline_tsc > tscl)
11113                         /* set_hv_timer ensures the delta fits in 32-bits */
11114                         delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
11115                                 cpu_preemption_timer_multi);
11116                 else
11117                         delta_tsc = 0;
11118
11119                 vmx_arm_hv_timer(vmx, delta_tsc);
11120                 return;
11121         }
11122
11123         if (vmx->loaded_vmcs->hv_timer_armed)
11124                 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
11125                                 PIN_BASED_VMX_PREEMPTION_TIMER);
11126         vmx->loaded_vmcs->hv_timer_armed = false;
11127 }
11128
11129 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
11130 {
11131         struct vcpu_vmx *vmx = to_vmx(vcpu);
11132         unsigned long cr3, cr4, evmcs_rsp;
11133
11134         /* Record the guest's net vcpu time for enforced NMI injections. */
11135         if (unlikely(!enable_vnmi &&
11136                      vmx->loaded_vmcs->soft_vnmi_blocked))
11137                 vmx->loaded_vmcs->entry_time = ktime_get();
11138
11139         /* Don't enter VMX if guest state is invalid, let the exit handler
11140            start emulation until we arrive back to a valid state */
11141         if (vmx->emulation_required)
11142                 return;
11143
11144         if (vmx->ple_window_dirty) {
11145                 vmx->ple_window_dirty = false;
11146                 vmcs_write32(PLE_WINDOW, vmx->ple_window);
11147         }
11148
11149         if (vmx->nested.need_vmcs12_sync) {
11150                 if (vmx->nested.hv_evmcs) {
11151                         copy_vmcs12_to_enlightened(vmx);
11152                         /* All fields are clean */
11153                         vmx->nested.hv_evmcs->hv_clean_fields |=
11154                                 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
11155                 } else {
11156                         copy_vmcs12_to_shadow(vmx);
11157                 }
11158                 vmx->nested.need_vmcs12_sync = false;
11159         }
11160
11161         if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
11162                 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
11163         if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
11164                 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
11165
11166         cr3 = __get_current_cr3_fast();
11167         if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
11168                 vmcs_writel(HOST_CR3, cr3);
11169                 vmx->loaded_vmcs->host_state.cr3 = cr3;
11170         }
11171
11172         cr4 = cr4_read_shadow();
11173         if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
11174                 vmcs_writel(HOST_CR4, cr4);
11175                 vmx->loaded_vmcs->host_state.cr4 = cr4;
11176         }
11177
11178         /* When single-stepping over STI and MOV SS, we must clear the
11179          * corresponding interruptibility bits in the guest state. Otherwise
11180          * vmentry fails as it then expects bit 14 (BS) in pending debug
11181          * exceptions being set, but that's not correct for the guest debugging
11182          * case. */
11183         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
11184                 vmx_set_interrupt_shadow(vcpu, 0);
11185
11186         if (static_cpu_has(X86_FEATURE_PKU) &&
11187             kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
11188             vcpu->arch.pkru != vmx->host_pkru)
11189                 __write_pkru(vcpu->arch.pkru);
11190
11191         atomic_switch_perf_msrs(vmx);
11192
11193         vmx_update_hv_timer(vcpu);
11194
11195         /*
11196          * If this vCPU has touched SPEC_CTRL, restore the guest's value if
11197          * it's non-zero. Since vmentry is serialising on affected CPUs, there
11198          * is no need to worry about the conditional branch over the wrmsr
11199          * being speculatively taken.
11200          */
11201         x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
11202
11203         vmx->__launched = vmx->loaded_vmcs->launched;
11204
11205         evmcs_rsp = static_branch_unlikely(&enable_evmcs) ?
11206                 (unsigned long)&current_evmcs->host_rsp : 0;
11207
11208         if (static_branch_unlikely(&vmx_l1d_should_flush))
11209                 vmx_l1d_flush(vcpu);
11210
11211         asm(
11212                 /* Store host registers */
11213                 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
11214                 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
11215                 "push %%" _ASM_CX " \n\t"
11216                 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
11217                 "je 1f \n\t"
11218                 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
11219                 /* Avoid VMWRITE when Enlightened VMCS is in use */
11220                 "test %%" _ASM_SI ", %%" _ASM_SI " \n\t"
11221                 "jz 2f \n\t"
11222                 "mov %%" _ASM_SP ", (%%" _ASM_SI ") \n\t"
11223                 "jmp 1f \n\t"
11224                 "2: \n\t"
11225                 __ex("vmwrite %%" _ASM_SP ", %%" _ASM_DX) "\n\t"
11226                 "1: \n\t"
11227                 /* Reload cr2 if changed */
11228                 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
11229                 "mov %%cr2, %%" _ASM_DX " \n\t"
11230                 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
11231                 "je 3f \n\t"
11232                 "mov %%" _ASM_AX", %%cr2 \n\t"
11233                 "3: \n\t"
11234                 /* Check if vmlaunch of vmresume is needed */
11235                 "cmpl $0, %c[launched](%0) \n\t"
11236                 /* Load guest registers.  Don't clobber flags. */
11237                 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
11238                 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
11239                 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
11240                 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
11241                 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
11242                 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
11243 #ifdef CONFIG_X86_64
11244                 "mov %c[r8](%0),  %%r8  \n\t"
11245                 "mov %c[r9](%0),  %%r9  \n\t"
11246                 "mov %c[r10](%0), %%r10 \n\t"
11247                 "mov %c[r11](%0), %%r11 \n\t"
11248                 "mov %c[r12](%0), %%r12 \n\t"
11249                 "mov %c[r13](%0), %%r13 \n\t"
11250                 "mov %c[r14](%0), %%r14 \n\t"
11251                 "mov %c[r15](%0), %%r15 \n\t"
11252 #endif
11253                 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
11254
11255                 /* Enter guest mode */
11256                 "jne 1f \n\t"
11257                 __ex("vmlaunch") "\n\t"
11258                 "jmp 2f \n\t"
11259                 "1: " __ex("vmresume") "\n\t"
11260                 "2: "
11261                 /* Save guest registers, load host registers, keep flags */
11262                 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
11263                 "pop %0 \n\t"
11264                 "setbe %c[fail](%0)\n\t"
11265                 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
11266                 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
11267                 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
11268                 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
11269                 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
11270                 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
11271                 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
11272 #ifdef CONFIG_X86_64
11273                 "mov %%r8,  %c[r8](%0) \n\t"
11274                 "mov %%r9,  %c[r9](%0) \n\t"
11275                 "mov %%r10, %c[r10](%0) \n\t"
11276                 "mov %%r11, %c[r11](%0) \n\t"
11277                 "mov %%r12, %c[r12](%0) \n\t"
11278                 "mov %%r13, %c[r13](%0) \n\t"
11279                 "mov %%r14, %c[r14](%0) \n\t"
11280                 "mov %%r15, %c[r15](%0) \n\t"
11281                 "xor %%r8d,  %%r8d \n\t"
11282                 "xor %%r9d,  %%r9d \n\t"
11283                 "xor %%r10d, %%r10d \n\t"
11284                 "xor %%r11d, %%r11d \n\t"
11285                 "xor %%r12d, %%r12d \n\t"
11286                 "xor %%r13d, %%r13d \n\t"
11287                 "xor %%r14d, %%r14d \n\t"
11288                 "xor %%r15d, %%r15d \n\t"
11289 #endif
11290                 "mov %%cr2, %%" _ASM_AX "   \n\t"
11291                 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
11292
11293                 "xor %%eax, %%eax \n\t"
11294                 "xor %%ebx, %%ebx \n\t"
11295                 "xor %%esi, %%esi \n\t"
11296                 "xor %%edi, %%edi \n\t"
11297                 "pop  %%" _ASM_BP "; pop  %%" _ASM_DX " \n\t"
11298                 ".pushsection .rodata \n\t"
11299                 ".global vmx_return \n\t"
11300                 "vmx_return: " _ASM_PTR " 2b \n\t"
11301                 ".popsection"
11302               : : "c"(vmx), "d"((unsigned long)HOST_RSP), "S"(evmcs_rsp),
11303                 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
11304                 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
11305                 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
11306                 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
11307                 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
11308                 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
11309                 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
11310                 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
11311                 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
11312                 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
11313 #ifdef CONFIG_X86_64
11314                 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
11315                 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
11316                 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
11317                 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
11318                 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
11319                 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
11320                 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
11321                 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
11322 #endif
11323                 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
11324                 [wordsize]"i"(sizeof(ulong))
11325               : "cc", "memory"
11326 #ifdef CONFIG_X86_64
11327                 , "rax", "rbx", "rdi"
11328                 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
11329 #else
11330                 , "eax", "ebx", "edi"
11331 #endif
11332               );
11333
11334         /*
11335          * We do not use IBRS in the kernel. If this vCPU has used the
11336          * SPEC_CTRL MSR it may have left it on; save the value and
11337          * turn it off. This is much more efficient than blindly adding
11338          * it to the atomic save/restore list. Especially as the former
11339          * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
11340          *
11341          * For non-nested case:
11342          * If the L01 MSR bitmap does not intercept the MSR, then we need to
11343          * save it.
11344          *
11345          * For nested case:
11346          * If the L02 MSR bitmap does not intercept the MSR, then we need to
11347          * save it.
11348          */
11349         if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
11350                 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
11351
11352         x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
11353
11354         /* Eliminate branch target predictions from guest mode */
11355         vmexit_fill_RSB();
11356
11357         /* All fields are clean at this point */
11358         if (static_branch_unlikely(&enable_evmcs))
11359                 current_evmcs->hv_clean_fields |=
11360                         HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
11361
11362         /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
11363         if (vmx->host_debugctlmsr)
11364                 update_debugctlmsr(vmx->host_debugctlmsr);
11365
11366 #ifndef CONFIG_X86_64
11367         /*
11368          * The sysexit path does not restore ds/es, so we must set them to
11369          * a reasonable value ourselves.
11370          *
11371          * We can't defer this to vmx_prepare_switch_to_host() since that
11372          * function may be executed in interrupt context, which saves and
11373          * restore segments around it, nullifying its effect.
11374          */
11375         loadsegment(ds, __USER_DS);
11376         loadsegment(es, __USER_DS);
11377 #endif
11378
11379         vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
11380                                   | (1 << VCPU_EXREG_RFLAGS)
11381                                   | (1 << VCPU_EXREG_PDPTR)
11382                                   | (1 << VCPU_EXREG_SEGMENTS)
11383                                   | (1 << VCPU_EXREG_CR3));
11384         vcpu->arch.regs_dirty = 0;
11385
11386         /*
11387          * eager fpu is enabled if PKEY is supported and CR4 is switched
11388          * back on host, so it is safe to read guest PKRU from current
11389          * XSAVE.
11390          */
11391         if (static_cpu_has(X86_FEATURE_PKU) &&
11392             kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
11393                 vcpu->arch.pkru = __read_pkru();
11394                 if (vcpu->arch.pkru != vmx->host_pkru)
11395                         __write_pkru(vmx->host_pkru);
11396         }
11397
11398         vmx->nested.nested_run_pending = 0;
11399         vmx->idt_vectoring_info = 0;
11400
11401         vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
11402         if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
11403                 return;
11404
11405         vmx->loaded_vmcs->launched = 1;
11406         vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
11407
11408         vmx_complete_atomic_exit(vmx);
11409         vmx_recover_nmi_blocking(vmx);
11410         vmx_complete_interrupts(vmx);
11411 }
11412 STACK_FRAME_NON_STANDARD(vmx_vcpu_run);
11413
11414 static struct kvm *vmx_vm_alloc(void)
11415 {
11416         struct kvm_vmx *kvm_vmx = vzalloc(sizeof(struct kvm_vmx));
11417         return &kvm_vmx->kvm;
11418 }
11419
11420 static void vmx_vm_free(struct kvm *kvm)
11421 {
11422         vfree(to_kvm_vmx(kvm));
11423 }
11424
11425 static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
11426 {
11427         struct vcpu_vmx *vmx = to_vmx(vcpu);
11428         int cpu;
11429
11430         if (vmx->loaded_vmcs == vmcs)
11431                 return;
11432
11433         cpu = get_cpu();
11434         vmx_vcpu_put(vcpu);
11435         vmx->loaded_vmcs = vmcs;
11436         vmx_vcpu_load(vcpu, cpu);
11437         put_cpu();
11438
11439         vm_entry_controls_reset_shadow(vmx);
11440         vm_exit_controls_reset_shadow(vmx);
11441         vmx_segment_cache_clear(vmx);
11442 }
11443
11444 /*
11445  * Ensure that the current vmcs of the logical processor is the
11446  * vmcs01 of the vcpu before calling free_nested().
11447  */
11448 static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu)
11449 {
11450         vcpu_load(vcpu);
11451         vmx_switch_vmcs(vcpu, &to_vmx(vcpu)->vmcs01);
11452         free_nested(vcpu);
11453         vcpu_put(vcpu);
11454 }
11455
11456 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
11457 {
11458         struct vcpu_vmx *vmx = to_vmx(vcpu);
11459
11460         if (enable_pml)
11461                 vmx_destroy_pml_buffer(vmx);
11462         free_vpid(vmx->vpid);
11463         leave_guest_mode(vcpu);
11464         vmx_free_vcpu_nested(vcpu);
11465         free_loaded_vmcs(vmx->loaded_vmcs);
11466         kfree(vmx->guest_msrs);
11467         kvm_vcpu_uninit(vcpu);
11468         kmem_cache_free(kvm_vcpu_cache, vmx);
11469 }
11470
11471 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
11472 {
11473         int err;
11474         struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
11475         unsigned long *msr_bitmap;
11476         int cpu;
11477
11478         if (!vmx)
11479                 return ERR_PTR(-ENOMEM);
11480
11481         vmx->vpid = allocate_vpid();
11482
11483         err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
11484         if (err)
11485                 goto free_vcpu;
11486
11487         err = -ENOMEM;
11488
11489         /*
11490          * If PML is turned on, failure on enabling PML just results in failure
11491          * of creating the vcpu, therefore we can simplify PML logic (by
11492          * avoiding dealing with cases, such as enabling PML partially on vcpus
11493          * for the guest, etc.
11494          */
11495         if (enable_pml) {
11496                 vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
11497                 if (!vmx->pml_pg)
11498                         goto uninit_vcpu;
11499         }
11500
11501         vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
11502         BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
11503                      > PAGE_SIZE);
11504
11505         if (!vmx->guest_msrs)
11506                 goto free_pml;
11507
11508         err = alloc_loaded_vmcs(&vmx->vmcs01);
11509         if (err < 0)
11510                 goto free_msrs;
11511
11512         msr_bitmap = vmx->vmcs01.msr_bitmap;
11513         vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
11514         vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
11515         vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
11516         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
11517         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
11518         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
11519         vmx->msr_bitmap_mode = 0;
11520
11521         vmx->loaded_vmcs = &vmx->vmcs01;
11522         cpu = get_cpu();
11523         vmx_vcpu_load(&vmx->vcpu, cpu);
11524         vmx->vcpu.cpu = cpu;
11525         vmx_vcpu_setup(vmx);
11526         vmx_vcpu_put(&vmx->vcpu);
11527         put_cpu();
11528         if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
11529                 err = alloc_apic_access_page(kvm);
11530                 if (err)
11531                         goto free_vmcs;
11532         }
11533
11534         if (enable_ept && !enable_unrestricted_guest) {
11535                 err = init_rmode_identity_map(kvm);
11536                 if (err)
11537                         goto free_vmcs;
11538         }
11539
11540         if (nested)
11541                 nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
11542                                            kvm_vcpu_apicv_active(&vmx->vcpu));
11543
11544         vmx->nested.posted_intr_nv = -1;
11545         vmx->nested.current_vmptr = -1ull;
11546
11547         vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
11548
11549         /*
11550          * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
11551          * or POSTED_INTR_WAKEUP_VECTOR.
11552          */
11553         vmx->pi_desc.nv = POSTED_INTR_VECTOR;
11554         vmx->pi_desc.sn = 1;
11555
11556         return &vmx->vcpu;
11557
11558 free_vmcs:
11559         free_loaded_vmcs(vmx->loaded_vmcs);
11560 free_msrs:
11561         kfree(vmx->guest_msrs);
11562 free_pml:
11563         vmx_destroy_pml_buffer(vmx);
11564 uninit_vcpu:
11565         kvm_vcpu_uninit(&vmx->vcpu);
11566 free_vcpu:
11567         free_vpid(vmx->vpid);
11568         kmem_cache_free(kvm_vcpu_cache, vmx);
11569         return ERR_PTR(err);
11570 }
11571
11572 #define L1TF_MSG_SMT "L1TF CPU bug present and SMT on, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/l1tf.html for details.\n"
11573 #define L1TF_MSG_L1D "L1TF CPU bug present and virtualization mitigation disabled, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/l1tf.html for details.\n"
11574
11575 static int vmx_vm_init(struct kvm *kvm)
11576 {
11577         spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
11578
11579         if (!ple_gap)
11580                 kvm->arch.pause_in_guest = true;
11581
11582         if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
11583                 switch (l1tf_mitigation) {
11584                 case L1TF_MITIGATION_OFF:
11585                 case L1TF_MITIGATION_FLUSH_NOWARN:
11586                         /* 'I explicitly don't care' is set */
11587                         break;
11588                 case L1TF_MITIGATION_FLUSH:
11589                 case L1TF_MITIGATION_FLUSH_NOSMT:
11590                 case L1TF_MITIGATION_FULL:
11591                         /*
11592                          * Warn upon starting the first VM in a potentially
11593                          * insecure environment.
11594                          */
11595                         if (cpu_smt_control == CPU_SMT_ENABLED)
11596                                 pr_warn_once(L1TF_MSG_SMT);
11597                         if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
11598                                 pr_warn_once(L1TF_MSG_L1D);
11599                         break;
11600                 case L1TF_MITIGATION_FULL_FORCE:
11601                         /* Flush is enforced */
11602                         break;
11603                 }
11604         }
11605         return 0;
11606 }
11607
11608 static void __init vmx_check_processor_compat(void *rtn)
11609 {
11610         struct vmcs_config vmcs_conf;
11611
11612         *(int *)rtn = 0;
11613         if (setup_vmcs_config(&vmcs_conf) < 0)
11614                 *(int *)rtn = -EIO;
11615         nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, enable_apicv);
11616         if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
11617                 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
11618                                 smp_processor_id());
11619                 *(int *)rtn = -EIO;
11620         }
11621 }
11622
11623 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
11624 {
11625         u8 cache;
11626         u64 ipat = 0;
11627
11628         /* For VT-d and EPT combination
11629          * 1. MMIO: always map as UC
11630          * 2. EPT with VT-d:
11631          *   a. VT-d without snooping control feature: can't guarantee the
11632          *      result, try to trust guest.
11633          *   b. VT-d with snooping control feature: snooping control feature of
11634          *      VT-d engine can guarantee the cache correctness. Just set it
11635          *      to WB to keep consistent with host. So the same as item 3.
11636          * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
11637          *    consistent with host MTRR
11638          */
11639         if (is_mmio) {
11640                 cache = MTRR_TYPE_UNCACHABLE;
11641                 goto exit;
11642         }
11643
11644         if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
11645                 ipat = VMX_EPT_IPAT_BIT;
11646                 cache = MTRR_TYPE_WRBACK;
11647                 goto exit;
11648         }
11649
11650         if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
11651                 ipat = VMX_EPT_IPAT_BIT;
11652                 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
11653                         cache = MTRR_TYPE_WRBACK;
11654                 else
11655                         cache = MTRR_TYPE_UNCACHABLE;
11656                 goto exit;
11657         }
11658
11659         cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
11660
11661 exit:
11662         return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
11663 }
11664
11665 static int vmx_get_lpage_level(void)
11666 {
11667         if (enable_ept && !cpu_has_vmx_ept_1g_page())
11668                 return PT_DIRECTORY_LEVEL;
11669         else
11670                 /* For shadow and EPT supported 1GB page */
11671                 return PT_PDPE_LEVEL;
11672 }
11673
11674 static void vmcs_set_secondary_exec_control(u32 new_ctl)
11675 {
11676         /*
11677          * These bits in the secondary execution controls field
11678          * are dynamic, the others are mostly based on the hypervisor
11679          * architecture and the guest's CPUID.  Do not touch the
11680          * dynamic bits.
11681          */
11682         u32 mask =
11683                 SECONDARY_EXEC_SHADOW_VMCS |
11684                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
11685                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
11686                 SECONDARY_EXEC_DESC;
11687
11688         u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
11689
11690         vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
11691                      (new_ctl & ~mask) | (cur_ctl & mask));
11692 }
11693
11694 /*
11695  * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
11696  * (indicating "allowed-1") if they are supported in the guest's CPUID.
11697  */
11698 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
11699 {
11700         struct vcpu_vmx *vmx = to_vmx(vcpu);
11701         struct kvm_cpuid_entry2 *entry;
11702
11703         vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
11704         vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
11705
11706 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do {            \
11707         if (entry && (entry->_reg & (_cpuid_mask)))                     \
11708                 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask);     \
11709 } while (0)
11710
11711         entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
11712         cr4_fixed1_update(X86_CR4_VME,        edx, bit(X86_FEATURE_VME));
11713         cr4_fixed1_update(X86_CR4_PVI,        edx, bit(X86_FEATURE_VME));
11714         cr4_fixed1_update(X86_CR4_TSD,        edx, bit(X86_FEATURE_TSC));
11715         cr4_fixed1_update(X86_CR4_DE,         edx, bit(X86_FEATURE_DE));
11716         cr4_fixed1_update(X86_CR4_PSE,        edx, bit(X86_FEATURE_PSE));
11717         cr4_fixed1_update(X86_CR4_PAE,        edx, bit(X86_FEATURE_PAE));
11718         cr4_fixed1_update(X86_CR4_MCE,        edx, bit(X86_FEATURE_MCE));
11719         cr4_fixed1_update(X86_CR4_PGE,        edx, bit(X86_FEATURE_PGE));
11720         cr4_fixed1_update(X86_CR4_OSFXSR,     edx, bit(X86_FEATURE_FXSR));
11721         cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
11722         cr4_fixed1_update(X86_CR4_VMXE,       ecx, bit(X86_FEATURE_VMX));
11723         cr4_fixed1_update(X86_CR4_SMXE,       ecx, bit(X86_FEATURE_SMX));
11724         cr4_fixed1_update(X86_CR4_PCIDE,      ecx, bit(X86_FEATURE_PCID));
11725         cr4_fixed1_update(X86_CR4_OSXSAVE,    ecx, bit(X86_FEATURE_XSAVE));
11726
11727         entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
11728         cr4_fixed1_update(X86_CR4_FSGSBASE,   ebx, bit(X86_FEATURE_FSGSBASE));
11729         cr4_fixed1_update(X86_CR4_SMEP,       ebx, bit(X86_FEATURE_SMEP));
11730         cr4_fixed1_update(X86_CR4_SMAP,       ebx, bit(X86_FEATURE_SMAP));
11731         cr4_fixed1_update(X86_CR4_PKE,        ecx, bit(X86_FEATURE_PKU));
11732         cr4_fixed1_update(X86_CR4_UMIP,       ecx, bit(X86_FEATURE_UMIP));
11733
11734 #undef cr4_fixed1_update
11735 }
11736
11737 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
11738 {
11739         struct vcpu_vmx *vmx = to_vmx(vcpu);
11740
11741         if (kvm_mpx_supported()) {
11742                 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
11743
11744                 if (mpx_enabled) {
11745                         vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
11746                         vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
11747                 } else {
11748                         vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
11749                         vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
11750                 }
11751         }
11752 }
11753
11754 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
11755 {
11756         struct vcpu_vmx *vmx = to_vmx(vcpu);
11757
11758         if (cpu_has_secondary_exec_ctrls()) {
11759                 vmx_compute_secondary_exec_control(vmx);
11760                 vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
11761         }
11762
11763         if (nested_vmx_allowed(vcpu))
11764                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
11765                         FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
11766         else
11767                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
11768                         ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
11769
11770         if (nested_vmx_allowed(vcpu)) {
11771                 nested_vmx_cr_fixed1_bits_update(vcpu);
11772                 nested_vmx_entry_exit_ctls_update(vcpu);
11773         }
11774 }
11775
11776 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
11777 {
11778         if (func == 1 && nested)
11779                 entry->ecx |= bit(X86_FEATURE_VMX);
11780 }
11781
11782 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
11783                 struct x86_exception *fault)
11784 {
11785         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11786         struct vcpu_vmx *vmx = to_vmx(vcpu);
11787         u32 exit_reason;
11788         unsigned long exit_qualification = vcpu->arch.exit_qualification;
11789
11790         if (vmx->nested.pml_full) {
11791                 exit_reason = EXIT_REASON_PML_FULL;
11792                 vmx->nested.pml_full = false;
11793                 exit_qualification &= INTR_INFO_UNBLOCK_NMI;
11794         } else if (fault->error_code & PFERR_RSVD_MASK)
11795                 exit_reason = EXIT_REASON_EPT_MISCONFIG;
11796         else
11797                 exit_reason = EXIT_REASON_EPT_VIOLATION;
11798
11799         nested_vmx_vmexit(vcpu, exit_reason, 0, exit_qualification);
11800         vmcs12->guest_physical_address = fault->address;
11801 }
11802
11803 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu)
11804 {
11805         return nested_ept_get_cr3(vcpu) & VMX_EPTP_AD_ENABLE_BIT;
11806 }
11807
11808 /* Callbacks for nested_ept_init_mmu_context: */
11809
11810 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
11811 {
11812         /* return the page table to be shadowed - in our case, EPT12 */
11813         return get_vmcs12(vcpu)->ept_pointer;
11814 }
11815
11816 static void nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
11817 {
11818         WARN_ON(mmu_is_nested(vcpu));
11819
11820         vcpu->arch.mmu = &vcpu->arch.guest_mmu;
11821         kvm_init_shadow_ept_mmu(vcpu,
11822                         to_vmx(vcpu)->nested.msrs.ept_caps &
11823                         VMX_EPT_EXECUTE_ONLY_BIT,
11824                         nested_ept_ad_enabled(vcpu),
11825                         nested_ept_get_cr3(vcpu));
11826         vcpu->arch.mmu->set_cr3           = vmx_set_cr3;
11827         vcpu->arch.mmu->get_cr3           = nested_ept_get_cr3;
11828         vcpu->arch.mmu->inject_page_fault = nested_ept_inject_page_fault;
11829         vcpu->arch.mmu->get_pdptr         = kvm_pdptr_read;
11830
11831         vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
11832 }
11833
11834 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
11835 {
11836         vcpu->arch.mmu = &vcpu->arch.root_mmu;
11837         vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
11838 }
11839
11840 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
11841                                             u16 error_code)
11842 {
11843         bool inequality, bit;
11844
11845         bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
11846         inequality =
11847                 (error_code & vmcs12->page_fault_error_code_mask) !=
11848                  vmcs12->page_fault_error_code_match;
11849         return inequality ^ bit;
11850 }
11851
11852 static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
11853                 struct x86_exception *fault)
11854 {
11855         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11856
11857         WARN_ON(!is_guest_mode(vcpu));
11858
11859         if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code) &&
11860                 !to_vmx(vcpu)->nested.nested_run_pending) {
11861                 vmcs12->vm_exit_intr_error_code = fault->error_code;
11862                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
11863                                   PF_VECTOR | INTR_TYPE_HARD_EXCEPTION |
11864                                   INTR_INFO_DELIVER_CODE_MASK | INTR_INFO_VALID_MASK,
11865                                   fault->address);
11866         } else {
11867                 kvm_inject_page_fault(vcpu, fault);
11868         }
11869 }
11870
11871 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
11872                                                  struct vmcs12 *vmcs12);
11873
11874 static void nested_get_vmcs12_pages(struct kvm_vcpu *vcpu)
11875 {
11876         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11877         struct vcpu_vmx *vmx = to_vmx(vcpu);
11878         struct page *page;
11879         u64 hpa;
11880
11881         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
11882                 /*
11883                  * Translate L1 physical address to host physical
11884                  * address for vmcs02. Keep the page pinned, so this
11885                  * physical address remains valid. We keep a reference
11886                  * to it so we can release it later.
11887                  */
11888                 if (vmx->nested.apic_access_page) { /* shouldn't happen */
11889                         kvm_release_page_dirty(vmx->nested.apic_access_page);
11890                         vmx->nested.apic_access_page = NULL;
11891                 }
11892                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->apic_access_addr);
11893                 /*
11894                  * If translation failed, no matter: This feature asks
11895                  * to exit when accessing the given address, and if it
11896                  * can never be accessed, this feature won't do
11897                  * anything anyway.
11898                  */
11899                 if (!is_error_page(page)) {
11900                         vmx->nested.apic_access_page = page;
11901                         hpa = page_to_phys(vmx->nested.apic_access_page);
11902                         vmcs_write64(APIC_ACCESS_ADDR, hpa);
11903                 } else {
11904                         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
11905                                         SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
11906                 }
11907         }
11908
11909         if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
11910                 if (vmx->nested.virtual_apic_page) { /* shouldn't happen */
11911                         kvm_release_page_dirty(vmx->nested.virtual_apic_page);
11912                         vmx->nested.virtual_apic_page = NULL;
11913                 }
11914                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->virtual_apic_page_addr);
11915
11916                 /*
11917                  * If translation failed, VM entry will fail because
11918                  * prepare_vmcs02 set VIRTUAL_APIC_PAGE_ADDR to -1ull.
11919                  * Failing the vm entry is _not_ what the processor
11920                  * does but it's basically the only possibility we
11921                  * have.  We could still enter the guest if CR8 load
11922                  * exits are enabled, CR8 store exits are enabled, and
11923                  * virtualize APIC access is disabled; in this case
11924                  * the processor would never use the TPR shadow and we
11925                  * could simply clear the bit from the execution
11926                  * control.  But such a configuration is useless, so
11927                  * let's keep the code simple.
11928                  */
11929                 if (!is_error_page(page)) {
11930                         vmx->nested.virtual_apic_page = page;
11931                         hpa = page_to_phys(vmx->nested.virtual_apic_page);
11932                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, hpa);
11933                 }
11934         }
11935
11936         if (nested_cpu_has_posted_intr(vmcs12)) {
11937                 if (vmx->nested.pi_desc_page) { /* shouldn't happen */
11938                         kunmap(vmx->nested.pi_desc_page);
11939                         kvm_release_page_dirty(vmx->nested.pi_desc_page);
11940                         vmx->nested.pi_desc_page = NULL;
11941                 }
11942                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->posted_intr_desc_addr);
11943                 if (is_error_page(page))
11944                         return;
11945                 vmx->nested.pi_desc_page = page;
11946                 vmx->nested.pi_desc = kmap(vmx->nested.pi_desc_page);
11947                 vmx->nested.pi_desc =
11948                         (struct pi_desc *)((void *)vmx->nested.pi_desc +
11949                         (unsigned long)(vmcs12->posted_intr_desc_addr &
11950                         (PAGE_SIZE - 1)));
11951                 vmcs_write64(POSTED_INTR_DESC_ADDR,
11952                         page_to_phys(vmx->nested.pi_desc_page) +
11953                         (unsigned long)(vmcs12->posted_intr_desc_addr &
11954                         (PAGE_SIZE - 1)));
11955         }
11956         if (nested_vmx_prepare_msr_bitmap(vcpu, vmcs12))
11957                 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
11958                               CPU_BASED_USE_MSR_BITMAPS);
11959         else
11960                 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
11961                                 CPU_BASED_USE_MSR_BITMAPS);
11962 }
11963
11964 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
11965 {
11966         u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
11967         struct vcpu_vmx *vmx = to_vmx(vcpu);
11968
11969         /*
11970          * A timer value of zero is architecturally guaranteed to cause
11971          * a VMExit prior to executing any instructions in the guest.
11972          */
11973         if (preemption_timeout == 0) {
11974                 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
11975                 return;
11976         }
11977
11978         if (vcpu->arch.virtual_tsc_khz == 0)
11979                 return;
11980
11981         preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
11982         preemption_timeout *= 1000000;
11983         do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
11984         hrtimer_start(&vmx->nested.preemption_timer,
11985                       ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
11986 }
11987
11988 static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,
11989                                                struct vmcs12 *vmcs12)
11990 {
11991         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
11992                 return 0;
11993
11994         if (!page_address_valid(vcpu, vmcs12->io_bitmap_a) ||
11995             !page_address_valid(vcpu, vmcs12->io_bitmap_b))
11996                 return -EINVAL;
11997
11998         return 0;
11999 }
12000
12001 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
12002                                                 struct vmcs12 *vmcs12)
12003 {
12004         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
12005                 return 0;
12006
12007         if (!page_address_valid(vcpu, vmcs12->msr_bitmap))
12008                 return -EINVAL;
12009
12010         return 0;
12011 }
12012
12013 static int nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu *vcpu,
12014                                                 struct vmcs12 *vmcs12)
12015 {
12016         if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
12017                 return 0;
12018
12019         if (!page_address_valid(vcpu, vmcs12->virtual_apic_page_addr))
12020                 return -EINVAL;
12021
12022         return 0;
12023 }
12024
12025 /*
12026  * Merge L0's and L1's MSR bitmap, return false to indicate that
12027  * we do not use the hardware.
12028  */
12029 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
12030                                                  struct vmcs12 *vmcs12)
12031 {
12032         int msr;
12033         struct page *page;
12034         unsigned long *msr_bitmap_l1;
12035         unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.vmcs02.msr_bitmap;
12036         /*
12037          * pred_cmd & spec_ctrl are trying to verify two things:
12038          *
12039          * 1. L0 gave a permission to L1 to actually passthrough the MSR. This
12040          *    ensures that we do not accidentally generate an L02 MSR bitmap
12041          *    from the L12 MSR bitmap that is too permissive.
12042          * 2. That L1 or L2s have actually used the MSR. This avoids
12043          *    unnecessarily merging of the bitmap if the MSR is unused. This
12044          *    works properly because we only update the L01 MSR bitmap lazily.
12045          *    So even if L0 should pass L1 these MSRs, the L01 bitmap is only
12046          *    updated to reflect this when L1 (or its L2s) actually write to
12047          *    the MSR.
12048          */
12049         bool pred_cmd = !msr_write_intercepted_l01(vcpu, MSR_IA32_PRED_CMD);
12050         bool spec_ctrl = !msr_write_intercepted_l01(vcpu, MSR_IA32_SPEC_CTRL);
12051
12052         /* Nothing to do if the MSR bitmap is not in use.  */
12053         if (!cpu_has_vmx_msr_bitmap() ||
12054             !nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
12055                 return false;
12056
12057         if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
12058             !pred_cmd && !spec_ctrl)
12059                 return false;
12060
12061         page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->msr_bitmap);
12062         if (is_error_page(page))
12063                 return false;
12064
12065         msr_bitmap_l1 = (unsigned long *)kmap(page);
12066         if (nested_cpu_has_apic_reg_virt(vmcs12)) {
12067                 /*
12068                  * L0 need not intercept reads for MSRs between 0x800 and 0x8ff, it
12069                  * just lets the processor take the value from the virtual-APIC page;
12070                  * take those 256 bits directly from the L1 bitmap.
12071                  */
12072                 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
12073                         unsigned word = msr / BITS_PER_LONG;
12074                         msr_bitmap_l0[word] = msr_bitmap_l1[word];
12075                         msr_bitmap_l0[word + (0x800 / sizeof(long))] = ~0;
12076                 }
12077         } else {
12078                 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
12079                         unsigned word = msr / BITS_PER_LONG;
12080                         msr_bitmap_l0[word] = ~0;
12081                         msr_bitmap_l0[word + (0x800 / sizeof(long))] = ~0;
12082                 }
12083         }
12084
12085         nested_vmx_disable_intercept_for_msr(
12086                 msr_bitmap_l1, msr_bitmap_l0,
12087                 X2APIC_MSR(APIC_TASKPRI),
12088                 MSR_TYPE_W);
12089
12090         if (nested_cpu_has_vid(vmcs12)) {
12091                 nested_vmx_disable_intercept_for_msr(
12092                         msr_bitmap_l1, msr_bitmap_l0,
12093                         X2APIC_MSR(APIC_EOI),
12094                         MSR_TYPE_W);
12095                 nested_vmx_disable_intercept_for_msr(
12096                         msr_bitmap_l1, msr_bitmap_l0,
12097                         X2APIC_MSR(APIC_SELF_IPI),
12098                         MSR_TYPE_W);
12099         }
12100
12101         if (spec_ctrl)
12102                 nested_vmx_disable_intercept_for_msr(
12103                                         msr_bitmap_l1, msr_bitmap_l0,
12104                                         MSR_IA32_SPEC_CTRL,
12105                                         MSR_TYPE_R | MSR_TYPE_W);
12106
12107         if (pred_cmd)
12108                 nested_vmx_disable_intercept_for_msr(
12109                                         msr_bitmap_l1, msr_bitmap_l0,
12110                                         MSR_IA32_PRED_CMD,
12111                                         MSR_TYPE_W);
12112
12113         kunmap(page);
12114         kvm_release_page_clean(page);
12115
12116         return true;
12117 }
12118
12119 static void nested_cache_shadow_vmcs12(struct kvm_vcpu *vcpu,
12120                                        struct vmcs12 *vmcs12)
12121 {
12122         struct vmcs12 *shadow;
12123         struct page *page;
12124
12125         if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
12126             vmcs12->vmcs_link_pointer == -1ull)
12127                 return;
12128
12129         shadow = get_shadow_vmcs12(vcpu);
12130         page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->vmcs_link_pointer);
12131
12132         memcpy(shadow, kmap(page), VMCS12_SIZE);
12133
12134         kunmap(page);
12135         kvm_release_page_clean(page);
12136 }
12137
12138 static void nested_flush_cached_shadow_vmcs12(struct kvm_vcpu *vcpu,
12139                                               struct vmcs12 *vmcs12)
12140 {
12141         struct vcpu_vmx *vmx = to_vmx(vcpu);
12142
12143         if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
12144             vmcs12->vmcs_link_pointer == -1ull)
12145                 return;
12146
12147         kvm_write_guest(vmx->vcpu.kvm, vmcs12->vmcs_link_pointer,
12148                         get_shadow_vmcs12(vcpu), VMCS12_SIZE);
12149 }
12150
12151 static int nested_vmx_check_apic_access_controls(struct kvm_vcpu *vcpu,
12152                                           struct vmcs12 *vmcs12)
12153 {
12154         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
12155             !page_address_valid(vcpu, vmcs12->apic_access_addr))
12156                 return -EINVAL;
12157         else
12158                 return 0;
12159 }
12160
12161 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
12162                                            struct vmcs12 *vmcs12)
12163 {
12164         if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
12165             !nested_cpu_has_apic_reg_virt(vmcs12) &&
12166             !nested_cpu_has_vid(vmcs12) &&
12167             !nested_cpu_has_posted_intr(vmcs12))
12168                 return 0;
12169
12170         /*
12171          * If virtualize x2apic mode is enabled,
12172          * virtualize apic access must be disabled.
12173          */
12174         if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
12175             nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
12176                 return -EINVAL;
12177
12178         /*
12179          * If virtual interrupt delivery is enabled,
12180          * we must exit on external interrupts.
12181          */
12182         if (nested_cpu_has_vid(vmcs12) &&
12183            !nested_exit_on_intr(vcpu))
12184                 return -EINVAL;
12185
12186         /*
12187          * bits 15:8 should be zero in posted_intr_nv,
12188          * the descriptor address has been already checked
12189          * in nested_get_vmcs12_pages.
12190          *
12191          * bits 5:0 of posted_intr_desc_addr should be zero.
12192          */
12193         if (nested_cpu_has_posted_intr(vmcs12) &&
12194            (!nested_cpu_has_vid(vmcs12) ||
12195             !nested_exit_intr_ack_set(vcpu) ||
12196             (vmcs12->posted_intr_nv & 0xff00) ||
12197             (vmcs12->posted_intr_desc_addr & 0x3f) ||
12198             (!page_address_valid(vcpu, vmcs12->posted_intr_desc_addr))))
12199                 return -EINVAL;
12200
12201         /* tpr shadow is needed by all apicv features. */
12202         if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
12203                 return -EINVAL;
12204
12205         return 0;
12206 }
12207
12208 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
12209                                        unsigned long count_field,
12210                                        unsigned long addr_field)
12211 {
12212         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
12213         int maxphyaddr;
12214         u64 count, addr;
12215
12216         if (vmcs12_read_any(vmcs12, count_field, &count) ||
12217             vmcs12_read_any(vmcs12, addr_field, &addr)) {
12218                 WARN_ON(1);
12219                 return -EINVAL;
12220         }
12221         if (count == 0)
12222                 return 0;
12223         maxphyaddr = cpuid_maxphyaddr(vcpu);
12224         if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
12225             (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
12226                 pr_debug_ratelimited(
12227                         "nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
12228                         addr_field, maxphyaddr, count, addr);
12229                 return -EINVAL;
12230         }
12231         return 0;
12232 }
12233
12234 static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
12235                                                 struct vmcs12 *vmcs12)
12236 {
12237         if (vmcs12->vm_exit_msr_load_count == 0 &&
12238             vmcs12->vm_exit_msr_store_count == 0 &&
12239             vmcs12->vm_entry_msr_load_count == 0)
12240                 return 0; /* Fast path */
12241         if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
12242                                         VM_EXIT_MSR_LOAD_ADDR) ||
12243             nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
12244                                         VM_EXIT_MSR_STORE_ADDR) ||
12245             nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
12246                                         VM_ENTRY_MSR_LOAD_ADDR))
12247                 return -EINVAL;
12248         return 0;
12249 }
12250
12251 static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
12252                                          struct vmcs12 *vmcs12)
12253 {
12254         if (!nested_cpu_has_pml(vmcs12))
12255                 return 0;
12256
12257         if (!nested_cpu_has_ept(vmcs12) ||
12258             !page_address_valid(vcpu, vmcs12->pml_address))
12259                 return -EINVAL;
12260
12261         return 0;
12262 }
12263
12264 static int nested_vmx_check_shadow_vmcs_controls(struct kvm_vcpu *vcpu,
12265                                                  struct vmcs12 *vmcs12)
12266 {
12267         if (!nested_cpu_has_shadow_vmcs(vmcs12))
12268                 return 0;
12269
12270         if (!page_address_valid(vcpu, vmcs12->vmread_bitmap) ||
12271             !page_address_valid(vcpu, vmcs12->vmwrite_bitmap))
12272                 return -EINVAL;
12273
12274         return 0;
12275 }
12276
12277 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
12278                                        struct vmx_msr_entry *e)
12279 {
12280         /* x2APIC MSR accesses are not allowed */
12281         if (vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8)
12282                 return -EINVAL;
12283         if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
12284             e->index == MSR_IA32_UCODE_REV)
12285                 return -EINVAL;
12286         if (e->reserved != 0)
12287                 return -EINVAL;
12288         return 0;
12289 }
12290
12291 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
12292                                      struct vmx_msr_entry *e)
12293 {
12294         if (e->index == MSR_FS_BASE ||
12295             e->index == MSR_GS_BASE ||
12296             e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
12297             nested_vmx_msr_check_common(vcpu, e))
12298                 return -EINVAL;
12299         return 0;
12300 }
12301
12302 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
12303                                       struct vmx_msr_entry *e)
12304 {
12305         if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
12306             nested_vmx_msr_check_common(vcpu, e))
12307                 return -EINVAL;
12308         return 0;
12309 }
12310
12311 /*
12312  * Load guest's/host's msr at nested entry/exit.
12313  * return 0 for success, entry index for failure.
12314  */
12315 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
12316 {
12317         u32 i;
12318         struct vmx_msr_entry e;
12319         struct msr_data msr;
12320
12321         msr.host_initiated = false;
12322         for (i = 0; i < count; i++) {
12323                 if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
12324                                         &e, sizeof(e))) {
12325                         pr_debug_ratelimited(
12326                                 "%s cannot read MSR entry (%u, 0x%08llx)\n",
12327                                 __func__, i, gpa + i * sizeof(e));
12328                         goto fail;
12329                 }
12330                 if (nested_vmx_load_msr_check(vcpu, &e)) {
12331                         pr_debug_ratelimited(
12332                                 "%s check failed (%u, 0x%x, 0x%x)\n",
12333                                 __func__, i, e.index, e.reserved);
12334                         goto fail;
12335                 }
12336                 msr.index = e.index;
12337                 msr.data = e.value;
12338                 if (kvm_set_msr(vcpu, &msr)) {
12339                         pr_debug_ratelimited(
12340                                 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
12341                                 __func__, i, e.index, e.value);
12342                         goto fail;
12343                 }
12344         }
12345         return 0;
12346 fail:
12347         return i + 1;
12348 }
12349
12350 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
12351 {
12352         u32 i;
12353         struct vmx_msr_entry e;
12354
12355         for (i = 0; i < count; i++) {
12356                 struct msr_data msr_info;
12357                 if (kvm_vcpu_read_guest(vcpu,
12358                                         gpa + i * sizeof(e),
12359                                         &e, 2 * sizeof(u32))) {
12360                         pr_debug_ratelimited(
12361                                 "%s cannot read MSR entry (%u, 0x%08llx)\n",
12362                                 __func__, i, gpa + i * sizeof(e));
12363                         return -EINVAL;
12364                 }
12365                 if (nested_vmx_store_msr_check(vcpu, &e)) {
12366                         pr_debug_ratelimited(
12367                                 "%s check failed (%u, 0x%x, 0x%x)\n",
12368                                 __func__, i, e.index, e.reserved);
12369                         return -EINVAL;
12370                 }
12371                 msr_info.host_initiated = false;
12372                 msr_info.index = e.index;
12373                 if (kvm_get_msr(vcpu, &msr_info)) {
12374                         pr_debug_ratelimited(
12375                                 "%s cannot read MSR (%u, 0x%x)\n",
12376                                 __func__, i, e.index);
12377                         return -EINVAL;
12378                 }
12379                 if (kvm_vcpu_write_guest(vcpu,
12380                                          gpa + i * sizeof(e) +
12381                                              offsetof(struct vmx_msr_entry, value),
12382                                          &msr_info.data, sizeof(msr_info.data))) {
12383                         pr_debug_ratelimited(
12384                                 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
12385                                 __func__, i, e.index, msr_info.data);
12386                         return -EINVAL;
12387                 }
12388         }
12389         return 0;
12390 }
12391
12392 static bool nested_cr3_valid(struct kvm_vcpu *vcpu, unsigned long val)
12393 {
12394         unsigned long invalid_mask;
12395
12396         invalid_mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
12397         return (val & invalid_mask) == 0;
12398 }
12399
12400 /*
12401  * Load guest's/host's cr3 at nested entry/exit. nested_ept is true if we are
12402  * emulating VM entry into a guest with EPT enabled.
12403  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
12404  * is assigned to entry_failure_code on failure.
12405  */
12406 static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool nested_ept,
12407                                u32 *entry_failure_code)
12408 {
12409         if (cr3 != kvm_read_cr3(vcpu) || (!nested_ept && pdptrs_changed(vcpu))) {
12410                 if (!nested_cr3_valid(vcpu, cr3)) {
12411                         *entry_failure_code = ENTRY_FAIL_DEFAULT;
12412                         return 1;
12413                 }
12414
12415                 /*
12416                  * If PAE paging and EPT are both on, CR3 is not used by the CPU and
12417                  * must not be dereferenced.
12418                  */
12419                 if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu) &&
12420                     !nested_ept) {
12421                         if (!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)) {
12422                                 *entry_failure_code = ENTRY_FAIL_PDPTE;
12423                                 return 1;
12424                         }
12425                 }
12426         }
12427
12428         if (!nested_ept)
12429                 kvm_mmu_new_cr3(vcpu, cr3, false);
12430
12431         vcpu->arch.cr3 = cr3;
12432         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
12433
12434         kvm_init_mmu(vcpu, false);
12435
12436         return 0;
12437 }
12438
12439 /*
12440  * Returns if KVM is able to config CPU to tag TLB entries
12441  * populated by L2 differently than TLB entries populated
12442  * by L1.
12443  *
12444  * If L1 uses EPT, then TLB entries are tagged with different EPTP.
12445  *
12446  * If L1 uses VPID and we allocated a vpid02, TLB entries are tagged
12447  * with different VPID (L1 entries are tagged with vmx->vpid
12448  * while L2 entries are tagged with vmx->nested.vpid02).
12449  */
12450 static bool nested_has_guest_tlb_tag(struct kvm_vcpu *vcpu)
12451 {
12452         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
12453
12454         return nested_cpu_has_ept(vmcs12) ||
12455                (nested_cpu_has_vpid(vmcs12) && to_vmx(vcpu)->nested.vpid02);
12456 }
12457
12458 static u64 nested_vmx_calc_efer(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
12459 {
12460         if (vmx->nested.nested_run_pending &&
12461             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
12462                 return vmcs12->guest_ia32_efer;
12463         else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
12464                 return vmx->vcpu.arch.efer | (EFER_LMA | EFER_LME);
12465         else
12466                 return vmx->vcpu.arch.efer & ~(EFER_LMA | EFER_LME);
12467 }
12468
12469 static void prepare_vmcs02_constant_state(struct vcpu_vmx *vmx)
12470 {
12471         /*
12472          * If vmcs02 hasn't been initialized, set the constant vmcs02 state
12473          * according to L0's settings (vmcs12 is irrelevant here).  Host
12474          * fields that come from L0 and are not constant, e.g. HOST_CR3,
12475          * will be set as needed prior to VMLAUNCH/VMRESUME.
12476          */
12477         if (vmx->nested.vmcs02_initialized)
12478                 return;
12479         vmx->nested.vmcs02_initialized = true;
12480
12481         /*
12482          * We don't care what the EPTP value is we just need to guarantee
12483          * it's valid so we don't get a false positive when doing early
12484          * consistency checks.
12485          */
12486         if (enable_ept && nested_early_check)
12487                 vmcs_write64(EPT_POINTER, construct_eptp(&vmx->vcpu, 0));
12488
12489         /* All VMFUNCs are currently emulated through L0 vmexits.  */
12490         if (cpu_has_vmx_vmfunc())
12491                 vmcs_write64(VM_FUNCTION_CONTROL, 0);
12492
12493         if (cpu_has_vmx_posted_intr())
12494                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
12495
12496         if (cpu_has_vmx_msr_bitmap())
12497                 vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
12498
12499         if (enable_pml)
12500                 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
12501
12502         /*
12503          * Set the MSR load/store lists to match L0's settings.  Only the
12504          * addresses are constant (for vmcs02), the counts can change based
12505          * on L2's behavior, e.g. switching to/from long mode.
12506          */
12507         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
12508         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
12509         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
12510
12511         vmx_set_constant_host_state(vmx);
12512 }
12513
12514 static void prepare_vmcs02_early_full(struct vcpu_vmx *vmx,
12515                                       struct vmcs12 *vmcs12)
12516 {
12517         prepare_vmcs02_constant_state(vmx);
12518
12519         vmcs_write64(VMCS_LINK_POINTER, -1ull);
12520
12521         if (enable_vpid) {
12522                 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02)
12523                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
12524                 else
12525                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
12526         }
12527 }
12528
12529 static void prepare_vmcs02_early(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
12530 {
12531         u32 exec_control, vmcs12_exec_ctrl;
12532         u64 guest_efer = nested_vmx_calc_efer(vmx, vmcs12);
12533
12534         if (vmx->nested.dirty_vmcs12 || vmx->nested.hv_evmcs)
12535                 prepare_vmcs02_early_full(vmx, vmcs12);
12536
12537         /*
12538          * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
12539          * entry, but only if the current (host) sp changed from the value
12540          * we wrote last (vmx->host_rsp).  This cache is no longer relevant
12541          * if we switch vmcs, and rather than hold a separate cache per vmcs,
12542          * here we just force the write to happen on entry.  host_rsp will
12543          * also be written unconditionally by nested_vmx_check_vmentry_hw()
12544          * if we are doing early consistency checks via hardware.
12545          */
12546         vmx->host_rsp = 0;
12547
12548         /*
12549          * PIN CONTROLS
12550          */
12551         exec_control = vmcs12->pin_based_vm_exec_control;
12552
12553         /* Preemption timer setting is computed directly in vmx_vcpu_run.  */
12554         exec_control |= vmcs_config.pin_based_exec_ctrl;
12555         exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
12556         vmx->loaded_vmcs->hv_timer_armed = false;
12557
12558         /* Posted interrupts setting is only taken from vmcs12.  */
12559         if (nested_cpu_has_posted_intr(vmcs12)) {
12560                 vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
12561                 vmx->nested.pi_pending = false;
12562         } else {
12563                 exec_control &= ~PIN_BASED_POSTED_INTR;
12564         }
12565         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
12566
12567         /*
12568          * EXEC CONTROLS
12569          */
12570         exec_control = vmx_exec_control(vmx); /* L0's desires */
12571         exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
12572         exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
12573         exec_control &= ~CPU_BASED_TPR_SHADOW;
12574         exec_control |= vmcs12->cpu_based_vm_exec_control;
12575
12576         /*
12577          * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR. Later, if
12578          * nested_get_vmcs12_pages can't fix it up, the illegal value
12579          * will result in a VM entry failure.
12580          */
12581         if (exec_control & CPU_BASED_TPR_SHADOW) {
12582                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
12583                 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
12584         } else {
12585 #ifdef CONFIG_X86_64
12586                 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
12587                                 CPU_BASED_CR8_STORE_EXITING;
12588 #endif
12589         }
12590
12591         /*
12592          * A vmexit (to either L1 hypervisor or L0 userspace) is always needed
12593          * for I/O port accesses.
12594          */
12595         exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
12596         exec_control |= CPU_BASED_UNCOND_IO_EXITING;
12597         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
12598
12599         /*
12600          * SECONDARY EXEC CONTROLS
12601          */
12602         if (cpu_has_secondary_exec_ctrls()) {
12603                 exec_control = vmx->secondary_exec_control;
12604
12605                 /* Take the following fields only from vmcs12 */
12606                 exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
12607                                   SECONDARY_EXEC_ENABLE_INVPCID |
12608                                   SECONDARY_EXEC_RDTSCP |
12609                                   SECONDARY_EXEC_XSAVES |
12610                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
12611                                   SECONDARY_EXEC_APIC_REGISTER_VIRT |
12612                                   SECONDARY_EXEC_ENABLE_VMFUNC);
12613                 if (nested_cpu_has(vmcs12,
12614                                    CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
12615                         vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
12616                                 ~SECONDARY_EXEC_ENABLE_PML;
12617                         exec_control |= vmcs12_exec_ctrl;
12618                 }
12619
12620                 /* VMCS shadowing for L2 is emulated for now */
12621                 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
12622
12623                 if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
12624                         vmcs_write16(GUEST_INTR_STATUS,
12625                                 vmcs12->guest_intr_status);
12626
12627                 /*
12628                  * Write an illegal value to APIC_ACCESS_ADDR. Later,
12629                  * nested_get_vmcs12_pages will either fix it up or
12630                  * remove the VM execution control.
12631                  */
12632                 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
12633                         vmcs_write64(APIC_ACCESS_ADDR, -1ull);
12634
12635                 if (exec_control & SECONDARY_EXEC_ENCLS_EXITING)
12636                         vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
12637
12638                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
12639         }
12640
12641         /*
12642          * ENTRY CONTROLS
12643          *
12644          * vmcs12's VM_{ENTRY,EXIT}_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE
12645          * are emulated by vmx_set_efer() in prepare_vmcs02(), but speculate
12646          * on the related bits (if supported by the CPU) in the hope that
12647          * we can avoid VMWrites during vmx_set_efer().
12648          */
12649         exec_control = (vmcs12->vm_entry_controls | vmcs_config.vmentry_ctrl) &
12650                         ~VM_ENTRY_IA32E_MODE & ~VM_ENTRY_LOAD_IA32_EFER;
12651         if (cpu_has_load_ia32_efer) {
12652                 if (guest_efer & EFER_LMA)
12653                         exec_control |= VM_ENTRY_IA32E_MODE;
12654                 if (guest_efer != host_efer)
12655                         exec_control |= VM_ENTRY_LOAD_IA32_EFER;
12656         }
12657         vm_entry_controls_init(vmx, exec_control);
12658
12659         /*
12660          * EXIT CONTROLS
12661          *
12662          * L2->L1 exit controls are emulated - the hardware exit is to L0 so
12663          * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
12664          * bits may be modified by vmx_set_efer() in prepare_vmcs02().
12665          */
12666         exec_control = vmcs_config.vmexit_ctrl;
12667         if (cpu_has_load_ia32_efer && guest_efer != host_efer)
12668                 exec_control |= VM_EXIT_LOAD_IA32_EFER;
12669         vm_exit_controls_init(vmx, exec_control);
12670
12671         /*
12672          * Conceptually we want to copy the PML address and index from
12673          * vmcs01 here, and then back to vmcs01 on nested vmexit. But,
12674          * since we always flush the log on each vmexit and never change
12675          * the PML address (once set), this happens to be equivalent to
12676          * simply resetting the index in vmcs02.
12677          */
12678         if (enable_pml)
12679                 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
12680
12681         /*
12682          * Interrupt/Exception Fields
12683          */
12684         if (vmx->nested.nested_run_pending) {
12685                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
12686                              vmcs12->vm_entry_intr_info_field);
12687                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
12688                              vmcs12->vm_entry_exception_error_code);
12689                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
12690                              vmcs12->vm_entry_instruction_len);
12691                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
12692                              vmcs12->guest_interruptibility_info);
12693                 vmx->loaded_vmcs->nmi_known_unmasked =
12694                         !(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
12695         } else {
12696                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
12697         }
12698 }
12699
12700 static void prepare_vmcs02_full(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
12701 {
12702         struct hv_enlightened_vmcs *hv_evmcs = vmx->nested.hv_evmcs;
12703
12704         if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
12705                            HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2)) {
12706                 vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
12707                 vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
12708                 vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
12709                 vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
12710                 vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
12711                 vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
12712                 vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
12713                 vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
12714                 vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
12715                 vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
12716                 vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
12717                 vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
12718                 vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
12719                 vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
12720                 vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
12721                 vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
12722                 vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
12723                 vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
12724                 vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
12725                 vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
12726                 vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
12727                 vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
12728                 vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
12729                 vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
12730                 vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
12731                 vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
12732                 vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
12733                 vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
12734                 vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
12735                 vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
12736                 vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
12737         }
12738
12739         if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
12740                            HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1)) {
12741                 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
12742                 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
12743                             vmcs12->guest_pending_dbg_exceptions);
12744                 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
12745                 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
12746
12747                 /*
12748                  * L1 may access the L2's PDPTR, so save them to construct
12749                  * vmcs12
12750                  */
12751                 if (enable_ept) {
12752                         vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
12753                         vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
12754                         vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
12755                         vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
12756                 }
12757         }
12758
12759         if (nested_cpu_has_xsaves(vmcs12))
12760                 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
12761
12762         /*
12763          * Whether page-faults are trapped is determined by a combination of
12764          * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
12765          * If enable_ept, L0 doesn't care about page faults and we should
12766          * set all of these to L1's desires. However, if !enable_ept, L0 does
12767          * care about (at least some) page faults, and because it is not easy
12768          * (if at all possible?) to merge L0 and L1's desires, we simply ask
12769          * to exit on each and every L2 page fault. This is done by setting
12770          * MASK=MATCH=0 and (see below) EB.PF=1.
12771          * Note that below we don't need special code to set EB.PF beyond the
12772          * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
12773          * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
12774          * !enable_ept, EB.PF is 1, so the "or" will always be 1.
12775          */
12776         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
12777                 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
12778         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
12779                 enable_ept ? vmcs12->page_fault_error_code_match : 0);
12780
12781         if (cpu_has_vmx_apicv()) {
12782                 vmcs_write64(EOI_EXIT_BITMAP0, vmcs12->eoi_exit_bitmap0);
12783                 vmcs_write64(EOI_EXIT_BITMAP1, vmcs12->eoi_exit_bitmap1);
12784                 vmcs_write64(EOI_EXIT_BITMAP2, vmcs12->eoi_exit_bitmap2);
12785                 vmcs_write64(EOI_EXIT_BITMAP3, vmcs12->eoi_exit_bitmap3);
12786         }
12787
12788         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
12789         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
12790
12791         set_cr4_guest_host_mask(vmx);
12792
12793         if (kvm_mpx_supported()) {
12794                 if (vmx->nested.nested_run_pending &&
12795                         (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
12796                         vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
12797                 else
12798                         vmcs_write64(GUEST_BNDCFGS, vmx->nested.vmcs01_guest_bndcfgs);
12799         }
12800 }
12801
12802 /*
12803  * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
12804  * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
12805  * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
12806  * guest in a way that will both be appropriate to L1's requests, and our
12807  * needs. In addition to modifying the active vmcs (which is vmcs02), this
12808  * function also has additional necessary side-effects, like setting various
12809  * vcpu->arch fields.
12810  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
12811  * is assigned to entry_failure_code on failure.
12812  */
12813 static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12814                           u32 *entry_failure_code)
12815 {
12816         struct vcpu_vmx *vmx = to_vmx(vcpu);
12817         struct hv_enlightened_vmcs *hv_evmcs = vmx->nested.hv_evmcs;
12818
12819         if (vmx->nested.dirty_vmcs12 || vmx->nested.hv_evmcs) {
12820                 prepare_vmcs02_full(vmx, vmcs12);
12821                 vmx->nested.dirty_vmcs12 = false;
12822         }
12823
12824         /*
12825          * First, the fields that are shadowed.  This must be kept in sync
12826          * with vmx_shadow_fields.h.
12827          */
12828         if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
12829                            HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2)) {
12830                 vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
12831                 vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
12832                 vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
12833                 vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
12834                 vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
12835         }
12836
12837         if (vmx->nested.nested_run_pending &&
12838             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
12839                 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
12840                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
12841         } else {
12842                 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
12843                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
12844         }
12845         vmx_set_rflags(vcpu, vmcs12->guest_rflags);
12846
12847         vmx->nested.preemption_timer_expired = false;
12848         if (nested_cpu_has_preemption_timer(vmcs12))
12849                 vmx_start_preemption_timer(vcpu);
12850
12851         /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
12852          * bitwise-or of what L1 wants to trap for L2, and what we want to
12853          * trap. Note that CR0.TS also needs updating - we do this later.
12854          */
12855         update_exception_bitmap(vcpu);
12856         vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
12857         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
12858
12859         if (vmx->nested.nested_run_pending &&
12860             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
12861                 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
12862                 vcpu->arch.pat = vmcs12->guest_ia32_pat;
12863         } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
12864                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
12865         }
12866
12867         vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
12868
12869         if (kvm_has_tsc_control)
12870                 decache_tsc_multiplier(vmx);
12871
12872         if (enable_vpid) {
12873                 /*
12874                  * There is no direct mapping between vpid02 and vpid12, the
12875                  * vpid02 is per-vCPU for L0 and reused while the value of
12876                  * vpid12 is changed w/ one invvpid during nested vmentry.
12877                  * The vpid12 is allocated by L1 for L2, so it will not
12878                  * influence global bitmap(for vpid01 and vpid02 allocation)
12879                  * even if spawn a lot of nested vCPUs.
12880                  */
12881                 if (nested_cpu_has_vpid(vmcs12) && nested_has_guest_tlb_tag(vcpu)) {
12882                         if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
12883                                 vmx->nested.last_vpid = vmcs12->virtual_processor_id;
12884                                 __vmx_flush_tlb(vcpu, nested_get_vpid02(vcpu), false);
12885                         }
12886                 } else {
12887                         /*
12888                          * If L1 use EPT, then L0 needs to execute INVEPT on
12889                          * EPTP02 instead of EPTP01. Therefore, delay TLB
12890                          * flush until vmcs02->eptp is fully updated by
12891                          * KVM_REQ_LOAD_CR3. Note that this assumes
12892                          * KVM_REQ_TLB_FLUSH is evaluated after
12893                          * KVM_REQ_LOAD_CR3 in vcpu_enter_guest().
12894                          */
12895                         kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
12896                 }
12897         }
12898
12899         if (nested_cpu_has_ept(vmcs12))
12900                 nested_ept_init_mmu_context(vcpu);
12901         else if (nested_cpu_has2(vmcs12,
12902                                  SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
12903                 vmx_flush_tlb(vcpu, true);
12904
12905         /*
12906          * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
12907          * bits which we consider mandatory enabled.
12908          * The CR0_READ_SHADOW is what L2 should have expected to read given
12909          * the specifications by L1; It's not enough to take
12910          * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
12911          * have more bits than L1 expected.
12912          */
12913         vmx_set_cr0(vcpu, vmcs12->guest_cr0);
12914         vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
12915
12916         vmx_set_cr4(vcpu, vmcs12->guest_cr4);
12917         vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
12918
12919         vcpu->arch.efer = nested_vmx_calc_efer(vmx, vmcs12);
12920         /* Note: may modify VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
12921         vmx_set_efer(vcpu, vcpu->arch.efer);
12922
12923         /*
12924          * Guest state is invalid and unrestricted guest is disabled,
12925          * which means L1 attempted VMEntry to L2 with invalid state.
12926          * Fail the VMEntry.
12927          */
12928         if (vmx->emulation_required) {
12929                 *entry_failure_code = ENTRY_FAIL_DEFAULT;
12930                 return 1;
12931         }
12932
12933         /* Shadow page tables on either EPT or shadow page tables. */
12934         if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
12935                                 entry_failure_code))
12936                 return 1;
12937
12938         if (!enable_ept)
12939                 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
12940
12941         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
12942         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
12943         return 0;
12944 }
12945
12946 static int nested_vmx_check_nmi_controls(struct vmcs12 *vmcs12)
12947 {
12948         if (!nested_cpu_has_nmi_exiting(vmcs12) &&
12949             nested_cpu_has_virtual_nmis(vmcs12))
12950                 return -EINVAL;
12951
12952         if (!nested_cpu_has_virtual_nmis(vmcs12) &&
12953             nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING))
12954                 return -EINVAL;
12955
12956         return 0;
12957 }
12958
12959 static int check_vmentry_prereqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12960 {
12961         struct vcpu_vmx *vmx = to_vmx(vcpu);
12962         bool ia32e;
12963
12964         if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
12965             vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT)
12966                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12967
12968         if (nested_cpu_has_vpid(vmcs12) && !vmcs12->virtual_processor_id)
12969                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12970
12971         if (nested_vmx_check_io_bitmap_controls(vcpu, vmcs12))
12972                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12973
12974         if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12))
12975                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12976
12977         if (nested_vmx_check_apic_access_controls(vcpu, vmcs12))
12978                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12979
12980         if (nested_vmx_check_tpr_shadow_controls(vcpu, vmcs12))
12981                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12982
12983         if (nested_vmx_check_apicv_controls(vcpu, vmcs12))
12984                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12985
12986         if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12))
12987                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12988
12989         if (nested_vmx_check_pml_controls(vcpu, vmcs12))
12990                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12991
12992         if (nested_vmx_check_shadow_vmcs_controls(vcpu, vmcs12))
12993                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12994
12995         if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
12996                                 vmx->nested.msrs.procbased_ctls_low,
12997                                 vmx->nested.msrs.procbased_ctls_high) ||
12998             (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
12999              !vmx_control_verify(vmcs12->secondary_vm_exec_control,
13000                                  vmx->nested.msrs.secondary_ctls_low,
13001                                  vmx->nested.msrs.secondary_ctls_high)) ||
13002             !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
13003                                 vmx->nested.msrs.pinbased_ctls_low,
13004                                 vmx->nested.msrs.pinbased_ctls_high) ||
13005             !vmx_control_verify(vmcs12->vm_exit_controls,
13006                                 vmx->nested.msrs.exit_ctls_low,
13007                                 vmx->nested.msrs.exit_ctls_high) ||
13008             !vmx_control_verify(vmcs12->vm_entry_controls,
13009                                 vmx->nested.msrs.entry_ctls_low,
13010                                 vmx->nested.msrs.entry_ctls_high))
13011                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13012
13013         if (nested_vmx_check_nmi_controls(vmcs12))
13014                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13015
13016         if (nested_cpu_has_vmfunc(vmcs12)) {
13017                 if (vmcs12->vm_function_control &
13018                     ~vmx->nested.msrs.vmfunc_controls)
13019                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13020
13021                 if (nested_cpu_has_eptp_switching(vmcs12)) {
13022                         if (!nested_cpu_has_ept(vmcs12) ||
13023                             !page_address_valid(vcpu, vmcs12->eptp_list_address))
13024                                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13025                 }
13026         }
13027
13028         if (vmcs12->cr3_target_count > nested_cpu_vmx_misc_cr3_count(vcpu))
13029                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13030
13031         if (!nested_host_cr0_valid(vcpu, vmcs12->host_cr0) ||
13032             !nested_host_cr4_valid(vcpu, vmcs12->host_cr4) ||
13033             !nested_cr3_valid(vcpu, vmcs12->host_cr3))
13034                 return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
13035
13036         /*
13037          * If the load IA32_EFER VM-exit control is 1, bits reserved in the
13038          * IA32_EFER MSR must be 0 in the field for that register. In addition,
13039          * the values of the LMA and LME bits in the field must each be that of
13040          * the host address-space size VM-exit control.
13041          */
13042         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
13043                 ia32e = (vmcs12->vm_exit_controls &
13044                          VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
13045                 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
13046                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
13047                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LME))
13048                         return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
13049         }
13050
13051         /*
13052          * From the Intel SDM, volume 3:
13053          * Fields relevant to VM-entry event injection must be set properly.
13054          * These fields are the VM-entry interruption-information field, the
13055          * VM-entry exception error code, and the VM-entry instruction length.
13056          */
13057         if (vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) {
13058                 u32 intr_info = vmcs12->vm_entry_intr_info_field;
13059                 u8 vector = intr_info & INTR_INFO_VECTOR_MASK;
13060                 u32 intr_type = intr_info & INTR_INFO_INTR_TYPE_MASK;
13061                 bool has_error_code = intr_info & INTR_INFO_DELIVER_CODE_MASK;
13062                 bool should_have_error_code;
13063                 bool urg = nested_cpu_has2(vmcs12,
13064                                            SECONDARY_EXEC_UNRESTRICTED_GUEST);
13065                 bool prot_mode = !urg || vmcs12->guest_cr0 & X86_CR0_PE;
13066
13067                 /* VM-entry interruption-info field: interruption type */
13068                 if (intr_type == INTR_TYPE_RESERVED ||
13069                     (intr_type == INTR_TYPE_OTHER_EVENT &&
13070                      !nested_cpu_supports_monitor_trap_flag(vcpu)))
13071                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13072
13073                 /* VM-entry interruption-info field: vector */
13074                 if ((intr_type == INTR_TYPE_NMI_INTR && vector != NMI_VECTOR) ||
13075                     (intr_type == INTR_TYPE_HARD_EXCEPTION && vector > 31) ||
13076                     (intr_type == INTR_TYPE_OTHER_EVENT && vector != 0))
13077                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13078
13079                 /* VM-entry interruption-info field: deliver error code */
13080                 should_have_error_code =
13081                         intr_type == INTR_TYPE_HARD_EXCEPTION && prot_mode &&
13082                         x86_exception_has_error_code(vector);
13083                 if (has_error_code != should_have_error_code)
13084                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13085
13086                 /* VM-entry exception error code */
13087                 if (has_error_code &&
13088                     vmcs12->vm_entry_exception_error_code & GENMASK(31, 15))
13089                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13090
13091                 /* VM-entry interruption-info field: reserved bits */
13092                 if (intr_info & INTR_INFO_RESVD_BITS_MASK)
13093                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13094
13095                 /* VM-entry instruction length */
13096                 switch (intr_type) {
13097                 case INTR_TYPE_SOFT_EXCEPTION:
13098                 case INTR_TYPE_SOFT_INTR:
13099                 case INTR_TYPE_PRIV_SW_EXCEPTION:
13100                         if ((vmcs12->vm_entry_instruction_len > 15) ||
13101                             (vmcs12->vm_entry_instruction_len == 0 &&
13102                              !nested_cpu_has_zero_length_injection(vcpu)))
13103                                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13104                 }
13105         }
13106
13107         if (nested_cpu_has_ept(vmcs12) &&
13108             !valid_ept_address(vcpu, vmcs12->ept_pointer))
13109                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13110
13111         return 0;
13112 }
13113
13114 static int nested_vmx_check_vmcs_link_ptr(struct kvm_vcpu *vcpu,
13115                                           struct vmcs12 *vmcs12)
13116 {
13117         int r;
13118         struct page *page;
13119         struct vmcs12 *shadow;
13120
13121         if (vmcs12->vmcs_link_pointer == -1ull)
13122                 return 0;
13123
13124         if (!page_address_valid(vcpu, vmcs12->vmcs_link_pointer))
13125                 return -EINVAL;
13126
13127         page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->vmcs_link_pointer);
13128         if (is_error_page(page))
13129                 return -EINVAL;
13130
13131         r = 0;
13132         shadow = kmap(page);
13133         if (shadow->hdr.revision_id != VMCS12_REVISION ||
13134             shadow->hdr.shadow_vmcs != nested_cpu_has_shadow_vmcs(vmcs12))
13135                 r = -EINVAL;
13136         kunmap(page);
13137         kvm_release_page_clean(page);
13138         return r;
13139 }
13140
13141 static int check_vmentry_postreqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
13142                                   u32 *exit_qual)
13143 {
13144         bool ia32e;
13145
13146         *exit_qual = ENTRY_FAIL_DEFAULT;
13147
13148         if (!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0) ||
13149             !nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4))
13150                 return 1;
13151
13152         if (nested_vmx_check_vmcs_link_ptr(vcpu, vmcs12)) {
13153                 *exit_qual = ENTRY_FAIL_VMCS_LINK_PTR;
13154                 return 1;
13155         }
13156
13157         /*
13158          * If the load IA32_EFER VM-entry control is 1, the following checks
13159          * are performed on the field for the IA32_EFER MSR:
13160          * - Bits reserved in the IA32_EFER MSR must be 0.
13161          * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
13162          *   the IA-32e mode guest VM-exit control. It must also be identical
13163          *   to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
13164          *   CR0.PG) is 1.
13165          */
13166         if (to_vmx(vcpu)->nested.nested_run_pending &&
13167             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {
13168                 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
13169                 if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
13170                     ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
13171                     ((vmcs12->guest_cr0 & X86_CR0_PG) &&
13172                      ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME)))
13173                         return 1;
13174         }
13175
13176         if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS) &&
13177                 (is_noncanonical_address(vmcs12->guest_bndcfgs & PAGE_MASK, vcpu) ||
13178                 (vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD)))
13179                         return 1;
13180
13181         return 0;
13182 }
13183
13184 static int __noclone nested_vmx_check_vmentry_hw(struct kvm_vcpu *vcpu)
13185 {
13186         struct vcpu_vmx *vmx = to_vmx(vcpu);
13187         unsigned long cr3, cr4;
13188
13189         if (!nested_early_check)
13190                 return 0;
13191
13192         if (vmx->msr_autoload.host.nr)
13193                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
13194         if (vmx->msr_autoload.guest.nr)
13195                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
13196
13197         preempt_disable();
13198
13199         vmx_prepare_switch_to_guest(vcpu);
13200
13201         /*
13202          * Induce a consistency check VMExit by clearing bit 1 in GUEST_RFLAGS,
13203          * which is reserved to '1' by hardware.  GUEST_RFLAGS is guaranteed to
13204          * be written (by preparve_vmcs02()) before the "real" VMEnter, i.e.
13205          * there is no need to preserve other bits or save/restore the field.
13206          */
13207         vmcs_writel(GUEST_RFLAGS, 0);
13208
13209         vmcs_writel(HOST_RIP, vmx_early_consistency_check_return);
13210
13211         cr3 = __get_current_cr3_fast();
13212         if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
13213                 vmcs_writel(HOST_CR3, cr3);
13214                 vmx->loaded_vmcs->host_state.cr3 = cr3;
13215         }
13216
13217         cr4 = cr4_read_shadow();
13218         if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
13219                 vmcs_writel(HOST_CR4, cr4);
13220                 vmx->loaded_vmcs->host_state.cr4 = cr4;
13221         }
13222
13223         vmx->__launched = vmx->loaded_vmcs->launched;
13224
13225         asm(
13226                 /* Set HOST_RSP */
13227                 __ex("vmwrite %%" _ASM_SP ", %%" _ASM_DX) "\n\t"
13228                 "mov %%" _ASM_SP ", %c[host_rsp](%0)\n\t"
13229
13230                 /* Check if vmlaunch of vmresume is needed */
13231                 "cmpl $0, %c[launched](%0)\n\t"
13232                 "je 1f\n\t"
13233                 __ex("vmresume") "\n\t"
13234                 "jmp 2f\n\t"
13235                 "1: " __ex("vmlaunch") "\n\t"
13236                 "jmp 2f\n\t"
13237                 "2: "
13238
13239                 /* Set vmx->fail accordingly */
13240                 "setbe %c[fail](%0)\n\t"
13241
13242                 ".pushsection .rodata\n\t"
13243                 ".global vmx_early_consistency_check_return\n\t"
13244                 "vmx_early_consistency_check_return: " _ASM_PTR " 2b\n\t"
13245                 ".popsection"
13246               :
13247               : "c"(vmx), "d"((unsigned long)HOST_RSP),
13248                 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
13249                 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
13250                 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp))
13251               : "rax", "cc", "memory"
13252         );
13253
13254         vmcs_writel(HOST_RIP, vmx_return);
13255
13256         preempt_enable();
13257
13258         if (vmx->msr_autoload.host.nr)
13259                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
13260         if (vmx->msr_autoload.guest.nr)
13261                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
13262
13263         if (vmx->fail) {
13264                 WARN_ON_ONCE(vmcs_read32(VM_INSTRUCTION_ERROR) !=
13265                              VMXERR_ENTRY_INVALID_CONTROL_FIELD);
13266                 vmx->fail = 0;
13267                 return 1;
13268         }
13269
13270         /*
13271          * VMExit clears RFLAGS.IF and DR7, even on a consistency check.
13272          */
13273         local_irq_enable();
13274         if (hw_breakpoint_active())
13275                 set_debugreg(__this_cpu_read(cpu_dr7), 7);
13276
13277         /*
13278          * A non-failing VMEntry means we somehow entered guest mode with
13279          * an illegal RIP, and that's just the tip of the iceberg.  There
13280          * is no telling what memory has been modified or what state has
13281          * been exposed to unknown code.  Hitting this all but guarantees
13282          * a (very critical) hardware issue.
13283          */
13284         WARN_ON(!(vmcs_read32(VM_EXIT_REASON) &
13285                 VMX_EXIT_REASONS_FAILED_VMENTRY));
13286
13287         return 0;
13288 }
13289 STACK_FRAME_NON_STANDARD(nested_vmx_check_vmentry_hw);
13290
13291 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
13292                                    struct vmcs12 *vmcs12);
13293
13294 /*
13295  * If from_vmentry is false, this is being called from state restore (either RSM
13296  * or KVM_SET_NESTED_STATE).  Otherwise it's called from vmlaunch/vmresume.
13297 + *
13298 + * Returns:
13299 + *   0 - success, i.e. proceed with actual VMEnter
13300 + *   1 - consistency check VMExit
13301 + *  -1 - consistency check VMFail
13302  */
13303 static int nested_vmx_enter_non_root_mode(struct kvm_vcpu *vcpu,
13304                                           bool from_vmentry)
13305 {
13306         struct vcpu_vmx *vmx = to_vmx(vcpu);
13307         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
13308         bool evaluate_pending_interrupts;
13309         u32 exit_reason = EXIT_REASON_INVALID_STATE;
13310         u32 exit_qual;
13311
13312         evaluate_pending_interrupts = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
13313                 (CPU_BASED_VIRTUAL_INTR_PENDING | CPU_BASED_VIRTUAL_NMI_PENDING);
13314         if (likely(!evaluate_pending_interrupts) && kvm_vcpu_apicv_active(vcpu))
13315                 evaluate_pending_interrupts |= vmx_has_apicv_interrupt(vcpu);
13316
13317         if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
13318                 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
13319         if (kvm_mpx_supported() &&
13320                 !(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
13321                 vmx->nested.vmcs01_guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
13322
13323         vmx_switch_vmcs(vcpu, &vmx->nested.vmcs02);
13324
13325         prepare_vmcs02_early(vmx, vmcs12);
13326
13327         if (from_vmentry) {
13328                 nested_get_vmcs12_pages(vcpu);
13329
13330                 if (nested_vmx_check_vmentry_hw(vcpu)) {
13331                         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
13332                         return -1;
13333                 }
13334
13335                 if (check_vmentry_postreqs(vcpu, vmcs12, &exit_qual))
13336                         goto vmentry_fail_vmexit;
13337         }
13338
13339         enter_guest_mode(vcpu);
13340         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
13341                 vcpu->arch.tsc_offset += vmcs12->tsc_offset;
13342
13343         if (prepare_vmcs02(vcpu, vmcs12, &exit_qual))
13344                 goto vmentry_fail_vmexit_guest_mode;
13345
13346         if (from_vmentry) {
13347                 exit_reason = EXIT_REASON_MSR_LOAD_FAIL;
13348                 exit_qual = nested_vmx_load_msr(vcpu,
13349                                                 vmcs12->vm_entry_msr_load_addr,
13350                                                 vmcs12->vm_entry_msr_load_count);
13351                 if (exit_qual)
13352                         goto vmentry_fail_vmexit_guest_mode;
13353         } else {
13354                 /*
13355                  * The MMU is not initialized to point at the right entities yet and
13356                  * "get pages" would need to read data from the guest (i.e. we will
13357                  * need to perform gpa to hpa translation). Request a call
13358                  * to nested_get_vmcs12_pages before the next VM-entry.  The MSRs
13359                  * have already been set at vmentry time and should not be reset.
13360                  */
13361                 kvm_make_request(KVM_REQ_GET_VMCS12_PAGES, vcpu);
13362         }
13363
13364         /*
13365          * If L1 had a pending IRQ/NMI until it executed
13366          * VMLAUNCH/VMRESUME which wasn't delivered because it was
13367          * disallowed (e.g. interrupts disabled), L0 needs to
13368          * evaluate if this pending event should cause an exit from L2
13369          * to L1 or delivered directly to L2 (e.g. In case L1 don't
13370          * intercept EXTERNAL_INTERRUPT).
13371          *
13372          * Usually this would be handled by the processor noticing an
13373          * IRQ/NMI window request, or checking RVI during evaluation of
13374          * pending virtual interrupts.  However, this setting was done
13375          * on VMCS01 and now VMCS02 is active instead. Thus, we force L0
13376          * to perform pending event evaluation by requesting a KVM_REQ_EVENT.
13377          */
13378         if (unlikely(evaluate_pending_interrupts))
13379                 kvm_make_request(KVM_REQ_EVENT, vcpu);
13380
13381         /*
13382          * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
13383          * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
13384          * returned as far as L1 is concerned. It will only return (and set
13385          * the success flag) when L2 exits (see nested_vmx_vmexit()).
13386          */
13387         return 0;
13388
13389         /*
13390          * A failed consistency check that leads to a VMExit during L1's
13391          * VMEnter to L2 is a variation of a normal VMexit, as explained in
13392          * 26.7 "VM-entry failures during or after loading guest state".
13393          */
13394 vmentry_fail_vmexit_guest_mode:
13395         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
13396                 vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
13397         leave_guest_mode(vcpu);
13398
13399 vmentry_fail_vmexit:
13400         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
13401
13402         if (!from_vmentry)
13403                 return 1;
13404
13405         load_vmcs12_host_state(vcpu, vmcs12);
13406         vmcs12->vm_exit_reason = exit_reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
13407         vmcs12->exit_qualification = exit_qual;
13408         if (enable_shadow_vmcs || vmx->nested.hv_evmcs)
13409                 vmx->nested.need_vmcs12_sync = true;
13410         return 1;
13411 }
13412
13413 /*
13414  * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
13415  * for running an L2 nested guest.
13416  */
13417 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
13418 {
13419         struct vmcs12 *vmcs12;
13420         struct vcpu_vmx *vmx = to_vmx(vcpu);
13421         u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
13422         int ret;
13423
13424         if (!nested_vmx_check_permission(vcpu))
13425                 return 1;
13426
13427         if (!nested_vmx_handle_enlightened_vmptrld(vcpu))
13428                 return 1;
13429
13430         if (!vmx->nested.hv_evmcs && vmx->nested.current_vmptr == -1ull)
13431                 return nested_vmx_failInvalid(vcpu);
13432
13433         vmcs12 = get_vmcs12(vcpu);
13434
13435         /*
13436          * Can't VMLAUNCH or VMRESUME a shadow VMCS. Despite the fact
13437          * that there *is* a valid VMCS pointer, RFLAGS.CF is set
13438          * rather than RFLAGS.ZF, and no error number is stored to the
13439          * VM-instruction error field.
13440          */
13441         if (vmcs12->hdr.shadow_vmcs)
13442                 return nested_vmx_failInvalid(vcpu);
13443
13444         if (vmx->nested.hv_evmcs) {
13445                 copy_enlightened_to_vmcs12(vmx);
13446                 /* Enlightened VMCS doesn't have launch state */
13447                 vmcs12->launch_state = !launch;
13448         } else if (enable_shadow_vmcs) {
13449                 copy_shadow_to_vmcs12(vmx);
13450         }
13451
13452         /*
13453          * The nested entry process starts with enforcing various prerequisites
13454          * on vmcs12 as required by the Intel SDM, and act appropriately when
13455          * they fail: As the SDM explains, some conditions should cause the
13456          * instruction to fail, while others will cause the instruction to seem
13457          * to succeed, but return an EXIT_REASON_INVALID_STATE.
13458          * To speed up the normal (success) code path, we should avoid checking
13459          * for misconfigurations which will anyway be caught by the processor
13460          * when using the merged vmcs02.
13461          */
13462         if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS)
13463                 return nested_vmx_failValid(vcpu,
13464                         VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
13465
13466         if (vmcs12->launch_state == launch)
13467                 return nested_vmx_failValid(vcpu,
13468                         launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
13469                                : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
13470
13471         ret = check_vmentry_prereqs(vcpu, vmcs12);
13472         if (ret)
13473                 return nested_vmx_failValid(vcpu, ret);
13474
13475         /*
13476          * We're finally done with prerequisite checking, and can start with
13477          * the nested entry.
13478          */
13479         vmx->nested.nested_run_pending = 1;
13480         ret = nested_vmx_enter_non_root_mode(vcpu, true);
13481         vmx->nested.nested_run_pending = !ret;
13482         if (ret > 0)
13483                 return 1;
13484         else if (ret)
13485                 return nested_vmx_failValid(vcpu,
13486                         VMXERR_ENTRY_INVALID_CONTROL_FIELD);
13487
13488         /* Hide L1D cache contents from the nested guest.  */
13489         vmx->vcpu.arch.l1tf_flush_l1d = true;
13490
13491         /*
13492          * Must happen outside of nested_vmx_enter_non_root_mode() as it will
13493          * also be used as part of restoring nVMX state for
13494          * snapshot restore (migration).
13495          *
13496          * In this flow, it is assumed that vmcs12 cache was
13497          * trasferred as part of captured nVMX state and should
13498          * therefore not be read from guest memory (which may not
13499          * exist on destination host yet).
13500          */
13501         nested_cache_shadow_vmcs12(vcpu, vmcs12);
13502
13503         /*
13504          * If we're entering a halted L2 vcpu and the L2 vcpu won't be woken
13505          * by event injection, halt vcpu.
13506          */
13507         if ((vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT) &&
13508             !(vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK)) {
13509                 vmx->nested.nested_run_pending = 0;
13510                 return kvm_vcpu_halt(vcpu);
13511         }
13512         return 1;
13513 }
13514
13515 /*
13516  * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
13517  * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
13518  * This function returns the new value we should put in vmcs12.guest_cr0.
13519  * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
13520  *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
13521  *     available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
13522  *     didn't trap the bit, because if L1 did, so would L0).
13523  *  2. Bits that L1 asked to trap (and therefore L0 also did) could not have
13524  *     been modified by L2, and L1 knows it. So just leave the old value of
13525  *     the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
13526  *     isn't relevant, because if L0 traps this bit it can set it to anything.
13527  *  3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
13528  *     changed these bits, and therefore they need to be updated, but L0
13529  *     didn't necessarily allow them to be changed in GUEST_CR0 - and rather
13530  *     put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
13531  */
13532 static inline unsigned long
13533 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
13534 {
13535         return
13536         /*1*/   (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
13537         /*2*/   (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
13538         /*3*/   (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
13539                         vcpu->arch.cr0_guest_owned_bits));
13540 }
13541
13542 static inline unsigned long
13543 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
13544 {
13545         return
13546         /*1*/   (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
13547         /*2*/   (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
13548         /*3*/   (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
13549                         vcpu->arch.cr4_guest_owned_bits));
13550 }
13551
13552 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
13553                                        struct vmcs12 *vmcs12)
13554 {
13555         u32 idt_vectoring;
13556         unsigned int nr;
13557
13558         if (vcpu->arch.exception.injected) {
13559                 nr = vcpu->arch.exception.nr;
13560                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
13561
13562                 if (kvm_exception_is_soft(nr)) {
13563                         vmcs12->vm_exit_instruction_len =
13564                                 vcpu->arch.event_exit_inst_len;
13565                         idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
13566                 } else
13567                         idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
13568
13569                 if (vcpu->arch.exception.has_error_code) {
13570                         idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
13571                         vmcs12->idt_vectoring_error_code =
13572                                 vcpu->arch.exception.error_code;
13573                 }
13574
13575                 vmcs12->idt_vectoring_info_field = idt_vectoring;
13576         } else if (vcpu->arch.nmi_injected) {
13577                 vmcs12->idt_vectoring_info_field =
13578                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
13579         } else if (vcpu->arch.interrupt.injected) {
13580                 nr = vcpu->arch.interrupt.nr;
13581                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
13582
13583                 if (vcpu->arch.interrupt.soft) {
13584                         idt_vectoring |= INTR_TYPE_SOFT_INTR;
13585                         vmcs12->vm_entry_instruction_len =
13586                                 vcpu->arch.event_exit_inst_len;
13587                 } else
13588                         idt_vectoring |= INTR_TYPE_EXT_INTR;
13589
13590                 vmcs12->idt_vectoring_info_field = idt_vectoring;
13591         }
13592 }
13593
13594 static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
13595 {
13596         struct vcpu_vmx *vmx = to_vmx(vcpu);
13597         unsigned long exit_qual;
13598         bool block_nested_events =
13599             vmx->nested.nested_run_pending || kvm_event_needs_reinjection(vcpu);
13600
13601         if (vcpu->arch.exception.pending &&
13602                 nested_vmx_check_exception(vcpu, &exit_qual)) {
13603                 if (block_nested_events)
13604                         return -EBUSY;
13605                 nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
13606                 return 0;
13607         }
13608
13609         if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
13610             vmx->nested.preemption_timer_expired) {
13611                 if (block_nested_events)
13612                         return -EBUSY;
13613                 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
13614                 return 0;
13615         }
13616
13617         if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
13618                 if (block_nested_events)
13619                         return -EBUSY;
13620                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
13621                                   NMI_VECTOR | INTR_TYPE_NMI_INTR |
13622                                   INTR_INFO_VALID_MASK, 0);
13623                 /*
13624                  * The NMI-triggered VM exit counts as injection:
13625                  * clear this one and block further NMIs.
13626                  */
13627                 vcpu->arch.nmi_pending = 0;
13628                 vmx_set_nmi_mask(vcpu, true);
13629                 return 0;
13630         }
13631
13632         if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
13633             nested_exit_on_intr(vcpu)) {
13634                 if (block_nested_events)
13635                         return -EBUSY;
13636                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
13637                 return 0;
13638         }
13639
13640         vmx_complete_nested_posted_interrupt(vcpu);
13641         return 0;
13642 }
13643
13644 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
13645 {
13646         to_vmx(vcpu)->req_immediate_exit = true;
13647 }
13648
13649 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
13650 {
13651         ktime_t remaining =
13652                 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
13653         u64 value;
13654
13655         if (ktime_to_ns(remaining) <= 0)
13656                 return 0;
13657
13658         value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
13659         do_div(value, 1000000);
13660         return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
13661 }
13662
13663 /*
13664  * Update the guest state fields of vmcs12 to reflect changes that
13665  * occurred while L2 was running. (The "IA-32e mode guest" bit of the
13666  * VM-entry controls is also updated, since this is really a guest
13667  * state bit.)
13668  */
13669 static void sync_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
13670 {
13671         vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
13672         vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
13673
13674         vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
13675         vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
13676         vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
13677
13678         vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
13679         vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
13680         vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
13681         vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
13682         vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
13683         vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
13684         vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
13685         vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
13686         vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
13687         vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
13688         vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
13689         vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
13690         vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
13691         vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
13692         vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
13693         vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
13694         vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
13695         vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
13696         vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
13697         vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
13698         vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
13699         vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
13700         vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
13701         vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
13702         vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
13703         vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
13704         vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
13705         vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
13706         vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
13707         vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
13708         vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
13709         vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
13710         vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
13711         vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
13712         vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
13713         vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
13714
13715         vmcs12->guest_interruptibility_info =
13716                 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
13717         vmcs12->guest_pending_dbg_exceptions =
13718                 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
13719         if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
13720                 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
13721         else
13722                 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
13723
13724         if (nested_cpu_has_preemption_timer(vmcs12)) {
13725                 if (vmcs12->vm_exit_controls &
13726                     VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
13727                         vmcs12->vmx_preemption_timer_value =
13728                                 vmx_get_preemption_timer_value(vcpu);
13729                 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
13730         }
13731
13732         /*
13733          * In some cases (usually, nested EPT), L2 is allowed to change its
13734          * own CR3 without exiting. If it has changed it, we must keep it.
13735          * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
13736          * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
13737          *
13738          * Additionally, restore L2's PDPTR to vmcs12.
13739          */
13740         if (enable_ept) {
13741                 vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
13742                 vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
13743                 vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
13744                 vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
13745                 vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
13746         }
13747
13748         vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
13749
13750         if (nested_cpu_has_vid(vmcs12))
13751                 vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
13752
13753         vmcs12->vm_entry_controls =
13754                 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
13755                 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
13756
13757         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
13758                 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
13759                 vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
13760         }
13761
13762         /* TODO: These cannot have changed unless we have MSR bitmaps and
13763          * the relevant bit asks not to trap the change */
13764         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
13765                 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
13766         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
13767                 vmcs12->guest_ia32_efer = vcpu->arch.efer;
13768         vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
13769         vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
13770         vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
13771         if (kvm_mpx_supported())
13772                 vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
13773 }
13774
13775 /*
13776  * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
13777  * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
13778  * and this function updates it to reflect the changes to the guest state while
13779  * L2 was running (and perhaps made some exits which were handled directly by L0
13780  * without going back to L1), and to reflect the exit reason.
13781  * Note that we do not have to copy here all VMCS fields, just those that
13782  * could have changed by the L2 guest or the exit - i.e., the guest-state and
13783  * exit-information fields only. Other fields are modified by L1 with VMWRITE,
13784  * which already writes to vmcs12 directly.
13785  */
13786 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
13787                            u32 exit_reason, u32 exit_intr_info,
13788                            unsigned long exit_qualification)
13789 {
13790         /* update guest state fields: */
13791         sync_vmcs12(vcpu, vmcs12);
13792
13793         /* update exit information fields: */
13794
13795         vmcs12->vm_exit_reason = exit_reason;
13796         vmcs12->exit_qualification = exit_qualification;
13797         vmcs12->vm_exit_intr_info = exit_intr_info;
13798
13799         vmcs12->idt_vectoring_info_field = 0;
13800         vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
13801         vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
13802
13803         if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
13804                 vmcs12->launch_state = 1;
13805
13806                 /* vm_entry_intr_info_field is cleared on exit. Emulate this
13807                  * instead of reading the real value. */
13808                 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
13809
13810                 /*
13811                  * Transfer the event that L0 or L1 may wanted to inject into
13812                  * L2 to IDT_VECTORING_INFO_FIELD.
13813                  */
13814                 vmcs12_save_pending_event(vcpu, vmcs12);
13815         }
13816
13817         /*
13818          * Drop what we picked up for L2 via vmx_complete_interrupts. It is
13819          * preserved above and would only end up incorrectly in L1.
13820          */
13821         vcpu->arch.nmi_injected = false;
13822         kvm_clear_exception_queue(vcpu);
13823         kvm_clear_interrupt_queue(vcpu);
13824 }
13825
13826 /*
13827  * A part of what we need to when the nested L2 guest exits and we want to
13828  * run its L1 parent, is to reset L1's guest state to the host state specified
13829  * in vmcs12.
13830  * This function is to be called not only on normal nested exit, but also on
13831  * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
13832  * Failures During or After Loading Guest State").
13833  * This function should be called when the active VMCS is L1's (vmcs01).
13834  */
13835 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
13836                                    struct vmcs12 *vmcs12)
13837 {
13838         struct kvm_segment seg;
13839         u32 entry_failure_code;
13840
13841         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
13842                 vcpu->arch.efer = vmcs12->host_ia32_efer;
13843         else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
13844                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
13845         else
13846                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
13847         vmx_set_efer(vcpu, vcpu->arch.efer);
13848
13849         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
13850         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
13851         vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
13852         vmx_set_interrupt_shadow(vcpu, 0);
13853
13854         /*
13855          * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
13856          * actually changed, because vmx_set_cr0 refers to efer set above.
13857          *
13858          * CR0_GUEST_HOST_MASK is already set in the original vmcs01
13859          * (KVM doesn't change it);
13860          */
13861         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
13862         vmx_set_cr0(vcpu, vmcs12->host_cr0);
13863
13864         /* Same as above - no reason to call set_cr4_guest_host_mask().  */
13865         vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
13866         vmx_set_cr4(vcpu, vmcs12->host_cr4);
13867
13868         nested_ept_uninit_mmu_context(vcpu);
13869
13870         /*
13871          * Only PDPTE load can fail as the value of cr3 was checked on entry and
13872          * couldn't have changed.
13873          */
13874         if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
13875                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
13876
13877         if (!enable_ept)
13878                 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
13879
13880         /*
13881          * If vmcs01 doesn't use VPID, CPU flushes TLB on every
13882          * VMEntry/VMExit. Thus, no need to flush TLB.
13883          *
13884          * If vmcs12 doesn't use VPID, L1 expects TLB to be
13885          * flushed on every VMEntry/VMExit.
13886          *
13887          * Otherwise, we can preserve TLB entries as long as we are
13888          * able to tag L1 TLB entries differently than L2 TLB entries.
13889          *
13890          * If vmcs12 uses EPT, we need to execute this flush on EPTP01
13891          * and therefore we request the TLB flush to happen only after VMCS EPTP
13892          * has been set by KVM_REQ_LOAD_CR3.
13893          */
13894         if (enable_vpid &&
13895             (!nested_cpu_has_vpid(vmcs12) || !nested_has_guest_tlb_tag(vcpu))) {
13896                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
13897         }
13898
13899         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
13900         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
13901         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
13902         vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
13903         vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
13904         vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
13905         vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
13906
13907         /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1.  */
13908         if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
13909                 vmcs_write64(GUEST_BNDCFGS, 0);
13910
13911         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
13912                 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
13913                 vcpu->arch.pat = vmcs12->host_ia32_pat;
13914         }
13915         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
13916                 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
13917                         vmcs12->host_ia32_perf_global_ctrl);
13918
13919         /* Set L1 segment info according to Intel SDM
13920             27.5.2 Loading Host Segment and Descriptor-Table Registers */
13921         seg = (struct kvm_segment) {
13922                 .base = 0,
13923                 .limit = 0xFFFFFFFF,
13924                 .selector = vmcs12->host_cs_selector,
13925                 .type = 11,
13926                 .present = 1,
13927                 .s = 1,
13928                 .g = 1
13929         };
13930         if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
13931                 seg.l = 1;
13932         else
13933                 seg.db = 1;
13934         vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
13935         seg = (struct kvm_segment) {
13936                 .base = 0,
13937                 .limit = 0xFFFFFFFF,
13938                 .type = 3,
13939                 .present = 1,
13940                 .s = 1,
13941                 .db = 1,
13942                 .g = 1
13943         };
13944         seg.selector = vmcs12->host_ds_selector;
13945         vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
13946         seg.selector = vmcs12->host_es_selector;
13947         vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
13948         seg.selector = vmcs12->host_ss_selector;
13949         vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
13950         seg.selector = vmcs12->host_fs_selector;
13951         seg.base = vmcs12->host_fs_base;
13952         vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
13953         seg.selector = vmcs12->host_gs_selector;
13954         seg.base = vmcs12->host_gs_base;
13955         vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
13956         seg = (struct kvm_segment) {
13957                 .base = vmcs12->host_tr_base,
13958                 .limit = 0x67,
13959                 .selector = vmcs12->host_tr_selector,
13960                 .type = 11,
13961                 .present = 1
13962         };
13963         vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
13964
13965         kvm_set_dr(vcpu, 7, 0x400);
13966         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
13967
13968         if (cpu_has_vmx_msr_bitmap())
13969                 vmx_update_msr_bitmap(vcpu);
13970
13971         if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
13972                                 vmcs12->vm_exit_msr_load_count))
13973                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
13974 }
13975
13976 static inline u64 nested_vmx_get_vmcs01_guest_efer(struct vcpu_vmx *vmx)
13977 {
13978         struct shared_msr_entry *efer_msr;
13979         unsigned int i;
13980
13981         if (vm_entry_controls_get(vmx) & VM_ENTRY_LOAD_IA32_EFER)
13982                 return vmcs_read64(GUEST_IA32_EFER);
13983
13984         if (cpu_has_load_ia32_efer)
13985                 return host_efer;
13986
13987         for (i = 0; i < vmx->msr_autoload.guest.nr; ++i) {
13988                 if (vmx->msr_autoload.guest.val[i].index == MSR_EFER)
13989                         return vmx->msr_autoload.guest.val[i].value;
13990         }
13991
13992         efer_msr = find_msr_entry(vmx, MSR_EFER);
13993         if (efer_msr)
13994                 return efer_msr->data;
13995
13996         return host_efer;
13997 }
13998
13999 static void nested_vmx_restore_host_state(struct kvm_vcpu *vcpu)
14000 {
14001         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
14002         struct vcpu_vmx *vmx = to_vmx(vcpu);
14003         struct vmx_msr_entry g, h;
14004         struct msr_data msr;
14005         gpa_t gpa;
14006         u32 i, j;
14007
14008         vcpu->arch.pat = vmcs_read64(GUEST_IA32_PAT);
14009
14010         if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
14011                 /*
14012                  * L1's host DR7 is lost if KVM_GUESTDBG_USE_HW_BP is set
14013                  * as vmcs01.GUEST_DR7 contains a userspace defined value
14014                  * and vcpu->arch.dr7 is not squirreled away before the
14015                  * nested VMENTER (not worth adding a variable in nested_vmx).
14016                  */
14017                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
14018                         kvm_set_dr(vcpu, 7, DR7_FIXED_1);
14019                 else
14020                         WARN_ON(kvm_set_dr(vcpu, 7, vmcs_readl(GUEST_DR7)));
14021         }
14022
14023         /*
14024          * Note that calling vmx_set_{efer,cr0,cr4} is important as they
14025          * handle a variety of side effects to KVM's software model.
14026          */
14027         vmx_set_efer(vcpu, nested_vmx_get_vmcs01_guest_efer(vmx));
14028
14029         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
14030         vmx_set_cr0(vcpu, vmcs_readl(CR0_READ_SHADOW));
14031
14032         vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
14033         vmx_set_cr4(vcpu, vmcs_readl(CR4_READ_SHADOW));
14034
14035         nested_ept_uninit_mmu_context(vcpu);
14036         vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
14037         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
14038
14039         /*
14040          * Use ept_save_pdptrs(vcpu) to load the MMU's cached PDPTRs
14041          * from vmcs01 (if necessary).  The PDPTRs are not loaded on
14042          * VMFail, like everything else we just need to ensure our
14043          * software model is up-to-date.
14044          */
14045         ept_save_pdptrs(vcpu);
14046
14047         kvm_mmu_reset_context(vcpu);
14048
14049         if (cpu_has_vmx_msr_bitmap())
14050                 vmx_update_msr_bitmap(vcpu);
14051
14052         /*
14053          * This nasty bit of open coding is a compromise between blindly
14054          * loading L1's MSRs using the exit load lists (incorrect emulation
14055          * of VMFail), leaving the nested VM's MSRs in the software model
14056          * (incorrect behavior) and snapshotting the modified MSRs (too
14057          * expensive since the lists are unbound by hardware).  For each
14058          * MSR that was (prematurely) loaded from the nested VMEntry load
14059          * list, reload it from the exit load list if it exists and differs
14060          * from the guest value.  The intent is to stuff host state as
14061          * silently as possible, not to fully process the exit load list.
14062          */
14063         msr.host_initiated = false;
14064         for (i = 0; i < vmcs12->vm_entry_msr_load_count; i++) {
14065                 gpa = vmcs12->vm_entry_msr_load_addr + (i * sizeof(g));
14066                 if (kvm_vcpu_read_guest(vcpu, gpa, &g, sizeof(g))) {
14067                         pr_debug_ratelimited(
14068                                 "%s read MSR index failed (%u, 0x%08llx)\n",
14069                                 __func__, i, gpa);
14070                         goto vmabort;
14071                 }
14072
14073                 for (j = 0; j < vmcs12->vm_exit_msr_load_count; j++) {
14074                         gpa = vmcs12->vm_exit_msr_load_addr + (j * sizeof(h));
14075                         if (kvm_vcpu_read_guest(vcpu, gpa, &h, sizeof(h))) {
14076                                 pr_debug_ratelimited(
14077                                         "%s read MSR failed (%u, 0x%08llx)\n",
14078                                         __func__, j, gpa);
14079                                 goto vmabort;
14080                         }
14081                         if (h.index != g.index)
14082                                 continue;
14083                         if (h.value == g.value)
14084                                 break;
14085
14086                         if (nested_vmx_load_msr_check(vcpu, &h)) {
14087                                 pr_debug_ratelimited(
14088                                         "%s check failed (%u, 0x%x, 0x%x)\n",
14089                                         __func__, j, h.index, h.reserved);
14090                                 goto vmabort;
14091                         }
14092
14093                         msr.index = h.index;
14094                         msr.data = h.value;
14095                         if (kvm_set_msr(vcpu, &msr)) {
14096                                 pr_debug_ratelimited(
14097                                         "%s WRMSR failed (%u, 0x%x, 0x%llx)\n",
14098                                         __func__, j, h.index, h.value);
14099                                 goto vmabort;
14100                         }
14101                 }
14102         }
14103
14104         return;
14105
14106 vmabort:
14107         nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
14108 }
14109
14110 /*
14111  * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
14112  * and modify vmcs12 to make it see what it would expect to see there if
14113  * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
14114  */
14115 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
14116                               u32 exit_intr_info,
14117                               unsigned long exit_qualification)
14118 {
14119         struct vcpu_vmx *vmx = to_vmx(vcpu);
14120         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
14121
14122         /* trying to cancel vmlaunch/vmresume is a bug */
14123         WARN_ON_ONCE(vmx->nested.nested_run_pending);
14124
14125         leave_guest_mode(vcpu);
14126
14127         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
14128                 vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
14129
14130         if (likely(!vmx->fail)) {
14131                 if (exit_reason == -1)
14132                         sync_vmcs12(vcpu, vmcs12);
14133                 else
14134                         prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
14135                                        exit_qualification);
14136
14137                 /*
14138                  * Must happen outside of sync_vmcs12() as it will
14139                  * also be used to capture vmcs12 cache as part of
14140                  * capturing nVMX state for snapshot (migration).
14141                  *
14142                  * Otherwise, this flush will dirty guest memory at a
14143                  * point it is already assumed by user-space to be
14144                  * immutable.
14145                  */
14146                 nested_flush_cached_shadow_vmcs12(vcpu, vmcs12);
14147
14148                 if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
14149                                          vmcs12->vm_exit_msr_store_count))
14150                         nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
14151         } else {
14152                 /*
14153                  * The only expected VM-instruction error is "VM entry with
14154                  * invalid control field(s)." Anything else indicates a
14155                  * problem with L0.  And we should never get here with a
14156                  * VMFail of any type if early consistency checks are enabled.
14157                  */
14158                 WARN_ON_ONCE(vmcs_read32(VM_INSTRUCTION_ERROR) !=
14159                              VMXERR_ENTRY_INVALID_CONTROL_FIELD);
14160                 WARN_ON_ONCE(nested_early_check);
14161         }
14162
14163         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
14164
14165         /* Update any VMCS fields that might have changed while L2 ran */
14166         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
14167         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
14168         vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
14169
14170         if (kvm_has_tsc_control)
14171                 decache_tsc_multiplier(vmx);
14172
14173         if (vmx->nested.change_vmcs01_virtual_apic_mode) {
14174                 vmx->nested.change_vmcs01_virtual_apic_mode = false;
14175                 vmx_set_virtual_apic_mode(vcpu);
14176         } else if (!nested_cpu_has_ept(vmcs12) &&
14177                    nested_cpu_has2(vmcs12,
14178                                    SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
14179                 vmx_flush_tlb(vcpu, true);
14180         }
14181
14182         /* This is needed for same reason as it was needed in prepare_vmcs02 */
14183         vmx->host_rsp = 0;
14184
14185         /* Unpin physical memory we referred to in vmcs02 */
14186         if (vmx->nested.apic_access_page) {
14187                 kvm_release_page_dirty(vmx->nested.apic_access_page);
14188                 vmx->nested.apic_access_page = NULL;
14189         }
14190         if (vmx->nested.virtual_apic_page) {
14191                 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
14192                 vmx->nested.virtual_apic_page = NULL;
14193         }
14194         if (vmx->nested.pi_desc_page) {
14195                 kunmap(vmx->nested.pi_desc_page);
14196                 kvm_release_page_dirty(vmx->nested.pi_desc_page);
14197                 vmx->nested.pi_desc_page = NULL;
14198                 vmx->nested.pi_desc = NULL;
14199         }
14200
14201         /*
14202          * We are now running in L2, mmu_notifier will force to reload the
14203          * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
14204          */
14205         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
14206
14207         if ((exit_reason != -1) && (enable_shadow_vmcs || vmx->nested.hv_evmcs))
14208                 vmx->nested.need_vmcs12_sync = true;
14209
14210         /* in case we halted in L2 */
14211         vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
14212
14213         if (likely(!vmx->fail)) {
14214                 /*
14215                  * TODO: SDM says that with acknowledge interrupt on
14216                  * exit, bit 31 of the VM-exit interrupt information
14217                  * (valid interrupt) is always set to 1 on
14218                  * EXIT_REASON_EXTERNAL_INTERRUPT, so we shouldn't
14219                  * need kvm_cpu_has_interrupt().  See the commit
14220                  * message for details.
14221                  */
14222                 if (nested_exit_intr_ack_set(vcpu) &&
14223                     exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT &&
14224                     kvm_cpu_has_interrupt(vcpu)) {
14225                         int irq = kvm_cpu_get_interrupt(vcpu);
14226                         WARN_ON(irq < 0);
14227                         vmcs12->vm_exit_intr_info = irq |
14228                                 INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
14229                 }
14230
14231                 if (exit_reason != -1)
14232                         trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
14233                                                        vmcs12->exit_qualification,
14234                                                        vmcs12->idt_vectoring_info_field,
14235                                                        vmcs12->vm_exit_intr_info,
14236                                                        vmcs12->vm_exit_intr_error_code,
14237                                                        KVM_ISA_VMX);
14238
14239                 load_vmcs12_host_state(vcpu, vmcs12);
14240
14241                 return;
14242         }
14243
14244         /*
14245          * After an early L2 VM-entry failure, we're now back
14246          * in L1 which thinks it just finished a VMLAUNCH or
14247          * VMRESUME instruction, so we need to set the failure
14248          * flag and the VM-instruction error field of the VMCS
14249          * accordingly, and skip the emulated instruction.
14250          */
14251         (void)nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
14252
14253         /*
14254          * Restore L1's host state to KVM's software model.  We're here
14255          * because a consistency check was caught by hardware, which
14256          * means some amount of guest state has been propagated to KVM's
14257          * model and needs to be unwound to the host's state.
14258          */
14259         nested_vmx_restore_host_state(vcpu);
14260
14261         vmx->fail = 0;
14262 }
14263
14264 /*
14265  * Forcibly leave nested mode in order to be able to reset the VCPU later on.
14266  */
14267 static void vmx_leave_nested(struct kvm_vcpu *vcpu)
14268 {
14269         if (is_guest_mode(vcpu)) {
14270                 to_vmx(vcpu)->nested.nested_run_pending = 0;
14271                 nested_vmx_vmexit(vcpu, -1, 0, 0);
14272         }
14273         free_nested(vcpu);
14274 }
14275
14276 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
14277                                struct x86_instruction_info *info,
14278                                enum x86_intercept_stage stage)
14279 {
14280         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
14281         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
14282
14283         /*
14284          * RDPID causes #UD if disabled through secondary execution controls.
14285          * Because it is marked as EmulateOnUD, we need to intercept it here.
14286          */
14287         if (info->intercept == x86_intercept_rdtscp &&
14288             !nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
14289                 ctxt->exception.vector = UD_VECTOR;
14290                 ctxt->exception.error_code_valid = false;
14291                 return X86EMUL_PROPAGATE_FAULT;
14292         }
14293
14294         /* TODO: check more intercepts... */
14295         return X86EMUL_CONTINUE;
14296 }
14297
14298 #ifdef CONFIG_X86_64
14299 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
14300 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
14301                                   u64 divisor, u64 *result)
14302 {
14303         u64 low = a << shift, high = a >> (64 - shift);
14304
14305         /* To avoid the overflow on divq */
14306         if (high >= divisor)
14307                 return 1;
14308
14309         /* Low hold the result, high hold rem which is discarded */
14310         asm("divq %2\n\t" : "=a" (low), "=d" (high) :
14311             "rm" (divisor), "0" (low), "1" (high));
14312         *result = low;
14313
14314         return 0;
14315 }
14316
14317 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
14318 {
14319         struct vcpu_vmx *vmx;
14320         u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
14321
14322         if (kvm_mwait_in_guest(vcpu->kvm))
14323                 return -EOPNOTSUPP;
14324
14325         vmx = to_vmx(vcpu);
14326         tscl = rdtsc();
14327         guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
14328         delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
14329         lapic_timer_advance_cycles = nsec_to_cycles(vcpu, lapic_timer_advance_ns);
14330
14331         if (delta_tsc > lapic_timer_advance_cycles)
14332                 delta_tsc -= lapic_timer_advance_cycles;
14333         else
14334                 delta_tsc = 0;
14335
14336         /* Convert to host delta tsc if tsc scaling is enabled */
14337         if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
14338                         u64_shl_div_u64(delta_tsc,
14339                                 kvm_tsc_scaling_ratio_frac_bits,
14340                                 vcpu->arch.tsc_scaling_ratio,
14341                                 &delta_tsc))
14342                 return -ERANGE;
14343
14344         /*
14345          * If the delta tsc can't fit in the 32 bit after the multi shift,
14346          * we can't use the preemption timer.
14347          * It's possible that it fits on later vmentries, but checking
14348          * on every vmentry is costly so we just use an hrtimer.
14349          */
14350         if (delta_tsc >> (cpu_preemption_timer_multi + 32))
14351                 return -ERANGE;
14352
14353         vmx->hv_deadline_tsc = tscl + delta_tsc;
14354         return delta_tsc == 0;
14355 }
14356
14357 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
14358 {
14359         to_vmx(vcpu)->hv_deadline_tsc = -1;
14360 }
14361 #endif
14362
14363 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
14364 {
14365         if (!kvm_pause_in_guest(vcpu->kvm))
14366                 shrink_ple_window(vcpu);
14367 }
14368
14369 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
14370                                      struct kvm_memory_slot *slot)
14371 {
14372         kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
14373         kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
14374 }
14375
14376 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
14377                                        struct kvm_memory_slot *slot)
14378 {
14379         kvm_mmu_slot_set_dirty(kvm, slot);
14380 }
14381
14382 static void vmx_flush_log_dirty(struct kvm *kvm)
14383 {
14384         kvm_flush_pml_buffers(kvm);
14385 }
14386
14387 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
14388 {
14389         struct vmcs12 *vmcs12;
14390         struct vcpu_vmx *vmx = to_vmx(vcpu);
14391         gpa_t gpa;
14392         struct page *page = NULL;
14393         u64 *pml_address;
14394
14395         if (is_guest_mode(vcpu)) {
14396                 WARN_ON_ONCE(vmx->nested.pml_full);
14397
14398                 /*
14399                  * Check if PML is enabled for the nested guest.
14400                  * Whether eptp bit 6 is set is already checked
14401                  * as part of A/D emulation.
14402                  */
14403                 vmcs12 = get_vmcs12(vcpu);
14404                 if (!nested_cpu_has_pml(vmcs12))
14405                         return 0;
14406
14407                 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
14408                         vmx->nested.pml_full = true;
14409                         return 1;
14410                 }
14411
14412                 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
14413
14414                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->pml_address);
14415                 if (is_error_page(page))
14416                         return 0;
14417
14418                 pml_address = kmap(page);
14419                 pml_address[vmcs12->guest_pml_index--] = gpa;
14420                 kunmap(page);
14421                 kvm_release_page_clean(page);
14422         }
14423
14424         return 0;
14425 }
14426
14427 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
14428                                            struct kvm_memory_slot *memslot,
14429                                            gfn_t offset, unsigned long mask)
14430 {
14431         kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
14432 }
14433
14434 static void __pi_post_block(struct kvm_vcpu *vcpu)
14435 {
14436         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
14437         struct pi_desc old, new;
14438         unsigned int dest;
14439
14440         do {
14441                 old.control = new.control = pi_desc->control;
14442                 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
14443                      "Wakeup handler not enabled while the VCPU is blocked\n");
14444
14445                 dest = cpu_physical_id(vcpu->cpu);
14446
14447                 if (x2apic_enabled())
14448                         new.ndst = dest;
14449                 else
14450                         new.ndst = (dest << 8) & 0xFF00;
14451
14452                 /* set 'NV' to 'notification vector' */
14453                 new.nv = POSTED_INTR_VECTOR;
14454         } while (cmpxchg64(&pi_desc->control, old.control,
14455                            new.control) != old.control);
14456
14457         if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
14458                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
14459                 list_del(&vcpu->blocked_vcpu_list);
14460                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
14461                 vcpu->pre_pcpu = -1;
14462         }
14463 }
14464
14465 /*
14466  * This routine does the following things for vCPU which is going
14467  * to be blocked if VT-d PI is enabled.
14468  * - Store the vCPU to the wakeup list, so when interrupts happen
14469  *   we can find the right vCPU to wake up.
14470  * - Change the Posted-interrupt descriptor as below:
14471  *      'NDST' <-- vcpu->pre_pcpu
14472  *      'NV' <-- POSTED_INTR_WAKEUP_VECTOR
14473  * - If 'ON' is set during this process, which means at least one
14474  *   interrupt is posted for this vCPU, we cannot block it, in
14475  *   this case, return 1, otherwise, return 0.
14476  *
14477  */
14478 static int pi_pre_block(struct kvm_vcpu *vcpu)
14479 {
14480         unsigned int dest;
14481         struct pi_desc old, new;
14482         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
14483
14484         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
14485                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
14486                 !kvm_vcpu_apicv_active(vcpu))
14487                 return 0;
14488
14489         WARN_ON(irqs_disabled());
14490         local_irq_disable();
14491         if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
14492                 vcpu->pre_pcpu = vcpu->cpu;
14493                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
14494                 list_add_tail(&vcpu->blocked_vcpu_list,
14495                               &per_cpu(blocked_vcpu_on_cpu,
14496                                        vcpu->pre_pcpu));
14497                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
14498         }
14499
14500         do {
14501                 old.control = new.control = pi_desc->control;
14502
14503                 WARN((pi_desc->sn == 1),
14504                      "Warning: SN field of posted-interrupts "
14505                      "is set before blocking\n");
14506
14507                 /*
14508                  * Since vCPU can be preempted during this process,
14509                  * vcpu->cpu could be different with pre_pcpu, we
14510                  * need to set pre_pcpu as the destination of wakeup
14511                  * notification event, then we can find the right vCPU
14512                  * to wakeup in wakeup handler if interrupts happen
14513                  * when the vCPU is in blocked state.
14514                  */
14515                 dest = cpu_physical_id(vcpu->pre_pcpu);
14516
14517                 if (x2apic_enabled())
14518                         new.ndst = dest;
14519                 else
14520                         new.ndst = (dest << 8) & 0xFF00;
14521
14522                 /* set 'NV' to 'wakeup vector' */
14523                 new.nv = POSTED_INTR_WAKEUP_VECTOR;
14524         } while (cmpxchg64(&pi_desc->control, old.control,
14525                            new.control) != old.control);
14526
14527         /* We should not block the vCPU if an interrupt is posted for it.  */
14528         if (pi_test_on(pi_desc) == 1)
14529                 __pi_post_block(vcpu);
14530
14531         local_irq_enable();
14532         return (vcpu->pre_pcpu == -1);
14533 }
14534
14535 static int vmx_pre_block(struct kvm_vcpu *vcpu)
14536 {
14537         if (pi_pre_block(vcpu))
14538                 return 1;
14539
14540         if (kvm_lapic_hv_timer_in_use(vcpu))
14541                 kvm_lapic_switch_to_sw_timer(vcpu);
14542
14543         return 0;
14544 }
14545
14546 static void pi_post_block(struct kvm_vcpu *vcpu)
14547 {
14548         if (vcpu->pre_pcpu == -1)
14549                 return;
14550
14551         WARN_ON(irqs_disabled());
14552         local_irq_disable();
14553         __pi_post_block(vcpu);
14554         local_irq_enable();
14555 }
14556
14557 static void vmx_post_block(struct kvm_vcpu *vcpu)
14558 {
14559         if (kvm_x86_ops->set_hv_timer)
14560                 kvm_lapic_switch_to_hv_timer(vcpu);
14561
14562         pi_post_block(vcpu);
14563 }
14564
14565 /*
14566  * vmx_update_pi_irte - set IRTE for Posted-Interrupts
14567  *
14568  * @kvm: kvm
14569  * @host_irq: host irq of the interrupt
14570  * @guest_irq: gsi of the interrupt
14571  * @set: set or unset PI
14572  * returns 0 on success, < 0 on failure
14573  */
14574 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
14575                               uint32_t guest_irq, bool set)
14576 {
14577         struct kvm_kernel_irq_routing_entry *e;
14578         struct kvm_irq_routing_table *irq_rt;
14579         struct kvm_lapic_irq irq;
14580         struct kvm_vcpu *vcpu;
14581         struct vcpu_data vcpu_info;
14582         int idx, ret = 0;
14583
14584         if (!kvm_arch_has_assigned_device(kvm) ||
14585                 !irq_remapping_cap(IRQ_POSTING_CAP) ||
14586                 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
14587                 return 0;
14588
14589         idx = srcu_read_lock(&kvm->irq_srcu);
14590         irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
14591         if (guest_irq >= irq_rt->nr_rt_entries ||
14592             hlist_empty(&irq_rt->map[guest_irq])) {
14593                 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
14594                              guest_irq, irq_rt->nr_rt_entries);
14595                 goto out;
14596         }
14597
14598         hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
14599                 if (e->type != KVM_IRQ_ROUTING_MSI)
14600                         continue;
14601                 /*
14602                  * VT-d PI cannot support posting multicast/broadcast
14603                  * interrupts to a vCPU, we still use interrupt remapping
14604                  * for these kind of interrupts.
14605                  *
14606                  * For lowest-priority interrupts, we only support
14607                  * those with single CPU as the destination, e.g. user
14608                  * configures the interrupts via /proc/irq or uses
14609                  * irqbalance to make the interrupts single-CPU.
14610                  *
14611                  * We will support full lowest-priority interrupt later.
14612                  */
14613
14614                 kvm_set_msi_irq(kvm, e, &irq);
14615                 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
14616                         /*
14617                          * Make sure the IRTE is in remapped mode if
14618                          * we don't handle it in posted mode.
14619                          */
14620                         ret = irq_set_vcpu_affinity(host_irq, NULL);
14621                         if (ret < 0) {
14622                                 printk(KERN_INFO
14623                                    "failed to back to remapped mode, irq: %u\n",
14624                                    host_irq);
14625                                 goto out;
14626                         }
14627
14628                         continue;
14629                 }
14630
14631                 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
14632                 vcpu_info.vector = irq.vector;
14633
14634                 trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
14635                                 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
14636
14637                 if (set)
14638                         ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
14639                 else
14640                         ret = irq_set_vcpu_affinity(host_irq, NULL);
14641
14642                 if (ret < 0) {
14643                         printk(KERN_INFO "%s: failed to update PI IRTE\n",
14644                                         __func__);
14645                         goto out;
14646                 }
14647         }
14648
14649         ret = 0;
14650 out:
14651         srcu_read_unlock(&kvm->irq_srcu, idx);
14652         return ret;
14653 }
14654
14655 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
14656 {
14657         if (vcpu->arch.mcg_cap & MCG_LMCE_P)
14658                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
14659                         FEATURE_CONTROL_LMCE;
14660         else
14661                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
14662                         ~FEATURE_CONTROL_LMCE;
14663 }
14664
14665 static int vmx_smi_allowed(struct kvm_vcpu *vcpu)
14666 {
14667         /* we need a nested vmexit to enter SMM, postpone if run is pending */
14668         if (to_vmx(vcpu)->nested.nested_run_pending)
14669                 return 0;
14670         return 1;
14671 }
14672
14673 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
14674 {
14675         struct vcpu_vmx *vmx = to_vmx(vcpu);
14676
14677         vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
14678         if (vmx->nested.smm.guest_mode)
14679                 nested_vmx_vmexit(vcpu, -1, 0, 0);
14680
14681         vmx->nested.smm.vmxon = vmx->nested.vmxon;
14682         vmx->nested.vmxon = false;
14683         vmx_clear_hlt(vcpu);
14684         return 0;
14685 }
14686
14687 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
14688 {
14689         struct vcpu_vmx *vmx = to_vmx(vcpu);
14690         int ret;
14691
14692         if (vmx->nested.smm.vmxon) {
14693                 vmx->nested.vmxon = true;
14694                 vmx->nested.smm.vmxon = false;
14695         }
14696
14697         if (vmx->nested.smm.guest_mode) {
14698                 vcpu->arch.hflags &= ~HF_SMM_MASK;
14699                 ret = nested_vmx_enter_non_root_mode(vcpu, false);
14700                 vcpu->arch.hflags |= HF_SMM_MASK;
14701                 if (ret)
14702                         return ret;
14703
14704                 vmx->nested.smm.guest_mode = false;
14705         }
14706         return 0;
14707 }
14708
14709 static int enable_smi_window(struct kvm_vcpu *vcpu)
14710 {
14711         return 0;
14712 }
14713
14714 static int vmx_get_nested_state(struct kvm_vcpu *vcpu,
14715                                 struct kvm_nested_state __user *user_kvm_nested_state,
14716                                 u32 user_data_size)
14717 {
14718         struct vcpu_vmx *vmx;
14719         struct vmcs12 *vmcs12;
14720         struct kvm_nested_state kvm_state = {
14721                 .flags = 0,
14722                 .format = 0,
14723                 .size = sizeof(kvm_state),
14724                 .vmx.vmxon_pa = -1ull,
14725                 .vmx.vmcs_pa = -1ull,
14726         };
14727
14728         if (!vcpu)
14729                 return kvm_state.size + 2 * VMCS12_SIZE;
14730
14731         vmx = to_vmx(vcpu);
14732         vmcs12 = get_vmcs12(vcpu);
14733
14734         /* FIXME: Enlightened VMCS is currently unsupported */
14735         if (vmx->nested.hv_evmcs)
14736                 return -ENOTSUPP;
14737
14738         if (nested_vmx_allowed(vcpu) &&
14739             (vmx->nested.vmxon || vmx->nested.smm.vmxon)) {
14740                 kvm_state.vmx.vmxon_pa = vmx->nested.vmxon_ptr;
14741                 kvm_state.vmx.vmcs_pa = vmx->nested.current_vmptr;
14742
14743                 if (vmx->nested.current_vmptr != -1ull) {
14744                         kvm_state.size += VMCS12_SIZE;
14745
14746                         if (is_guest_mode(vcpu) &&
14747                             nested_cpu_has_shadow_vmcs(vmcs12) &&
14748                             vmcs12->vmcs_link_pointer != -1ull)
14749                                 kvm_state.size += VMCS12_SIZE;
14750                 }
14751
14752                 if (vmx->nested.smm.vmxon)
14753                         kvm_state.vmx.smm.flags |= KVM_STATE_NESTED_SMM_VMXON;
14754
14755                 if (vmx->nested.smm.guest_mode)
14756                         kvm_state.vmx.smm.flags |= KVM_STATE_NESTED_SMM_GUEST_MODE;
14757
14758                 if (is_guest_mode(vcpu)) {
14759                         kvm_state.flags |= KVM_STATE_NESTED_GUEST_MODE;
14760
14761                         if (vmx->nested.nested_run_pending)
14762                                 kvm_state.flags |= KVM_STATE_NESTED_RUN_PENDING;
14763                 }
14764         }
14765
14766         if (user_data_size < kvm_state.size)
14767                 goto out;
14768
14769         if (copy_to_user(user_kvm_nested_state, &kvm_state, sizeof(kvm_state)))
14770                 return -EFAULT;
14771
14772         if (vmx->nested.current_vmptr == -1ull)
14773                 goto out;
14774
14775         /*
14776          * When running L2, the authoritative vmcs12 state is in the
14777          * vmcs02. When running L1, the authoritative vmcs12 state is
14778          * in the shadow vmcs linked to vmcs01, unless
14779          * need_vmcs12_sync is set, in which case, the authoritative
14780          * vmcs12 state is in the vmcs12 already.
14781          */
14782         if (is_guest_mode(vcpu))
14783                 sync_vmcs12(vcpu, vmcs12);
14784         else if (enable_shadow_vmcs && !vmx->nested.need_vmcs12_sync)
14785                 copy_shadow_to_vmcs12(vmx);
14786
14787         if (copy_to_user(user_kvm_nested_state->data, vmcs12, sizeof(*vmcs12)))
14788                 return -EFAULT;
14789
14790         if (nested_cpu_has_shadow_vmcs(vmcs12) &&
14791             vmcs12->vmcs_link_pointer != -1ull) {
14792                 if (copy_to_user(user_kvm_nested_state->data + VMCS12_SIZE,
14793                                  get_shadow_vmcs12(vcpu), sizeof(*vmcs12)))
14794                         return -EFAULT;
14795         }
14796
14797 out:
14798         return kvm_state.size;
14799 }
14800
14801 static int vmx_set_nested_state(struct kvm_vcpu *vcpu,
14802                                 struct kvm_nested_state __user *user_kvm_nested_state,
14803                                 struct kvm_nested_state *kvm_state)
14804 {
14805         struct vcpu_vmx *vmx = to_vmx(vcpu);
14806         struct vmcs12 *vmcs12;
14807         u32 exit_qual;
14808         int ret;
14809
14810         if (kvm_state->format != 0)
14811                 return -EINVAL;
14812
14813         if (!nested_vmx_allowed(vcpu))
14814                 return kvm_state->vmx.vmxon_pa == -1ull ? 0 : -EINVAL;
14815
14816         if (kvm_state->vmx.vmxon_pa == -1ull) {
14817                 if (kvm_state->vmx.smm.flags)
14818                         return -EINVAL;
14819
14820                 if (kvm_state->vmx.vmcs_pa != -1ull)
14821                         return -EINVAL;
14822
14823                 vmx_leave_nested(vcpu);
14824                 return 0;
14825         }
14826
14827         if (!page_address_valid(vcpu, kvm_state->vmx.vmxon_pa))
14828                 return -EINVAL;
14829
14830         if (kvm_state->size < sizeof(kvm_state) + sizeof(*vmcs12))
14831                 return -EINVAL;
14832
14833         if (kvm_state->vmx.vmcs_pa == kvm_state->vmx.vmxon_pa ||
14834             !page_address_valid(vcpu, kvm_state->vmx.vmcs_pa))
14835                 return -EINVAL;
14836
14837         if ((kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
14838             (kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
14839                 return -EINVAL;
14840
14841         if (kvm_state->vmx.smm.flags &
14842             ~(KVM_STATE_NESTED_SMM_GUEST_MODE | KVM_STATE_NESTED_SMM_VMXON))
14843                 return -EINVAL;
14844
14845         /*
14846          * SMM temporarily disables VMX, so we cannot be in guest mode,
14847          * nor can VMLAUNCH/VMRESUME be pending.  Outside SMM, SMM flags
14848          * must be zero.
14849          */
14850         if (is_smm(vcpu) ? kvm_state->flags : kvm_state->vmx.smm.flags)
14851                 return -EINVAL;
14852
14853         if ((kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
14854             !(kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON))
14855                 return -EINVAL;
14856
14857         vmx_leave_nested(vcpu);
14858         if (kvm_state->vmx.vmxon_pa == -1ull)
14859                 return 0;
14860
14861         vmx->nested.vmxon_ptr = kvm_state->vmx.vmxon_pa;
14862         ret = enter_vmx_operation(vcpu);
14863         if (ret)
14864                 return ret;
14865
14866         set_current_vmptr(vmx, kvm_state->vmx.vmcs_pa);
14867
14868         if (kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON) {
14869                 vmx->nested.smm.vmxon = true;
14870                 vmx->nested.vmxon = false;
14871
14872                 if (kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE)
14873                         vmx->nested.smm.guest_mode = true;
14874         }
14875
14876         vmcs12 = get_vmcs12(vcpu);
14877         if (copy_from_user(vmcs12, user_kvm_nested_state->data, sizeof(*vmcs12)))
14878                 return -EFAULT;
14879
14880         if (vmcs12->hdr.revision_id != VMCS12_REVISION)
14881                 return -EINVAL;
14882
14883         if (!(kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
14884                 return 0;
14885
14886         vmx->nested.nested_run_pending =
14887                 !!(kvm_state->flags & KVM_STATE_NESTED_RUN_PENDING);
14888
14889         if (nested_cpu_has_shadow_vmcs(vmcs12) &&
14890             vmcs12->vmcs_link_pointer != -1ull) {
14891                 struct vmcs12 *shadow_vmcs12 = get_shadow_vmcs12(vcpu);
14892                 if (kvm_state->size < sizeof(kvm_state) + 2 * sizeof(*vmcs12))
14893                         return -EINVAL;
14894
14895                 if (copy_from_user(shadow_vmcs12,
14896                                    user_kvm_nested_state->data + VMCS12_SIZE,
14897                                    sizeof(*vmcs12)))
14898                         return -EFAULT;
14899
14900                 if (shadow_vmcs12->hdr.revision_id != VMCS12_REVISION ||
14901                     !shadow_vmcs12->hdr.shadow_vmcs)
14902                         return -EINVAL;
14903         }
14904
14905         if (check_vmentry_prereqs(vcpu, vmcs12) ||
14906             check_vmentry_postreqs(vcpu, vmcs12, &exit_qual))
14907                 return -EINVAL;
14908
14909         vmx->nested.dirty_vmcs12 = true;
14910         ret = nested_vmx_enter_non_root_mode(vcpu, false);
14911         if (ret)
14912                 return -EINVAL;
14913
14914         return 0;
14915 }
14916
14917 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
14918         .cpu_has_kvm_support = cpu_has_kvm_support,
14919         .disabled_by_bios = vmx_disabled_by_bios,
14920         .hardware_setup = hardware_setup,
14921         .hardware_unsetup = hardware_unsetup,
14922         .check_processor_compatibility = vmx_check_processor_compat,
14923         .hardware_enable = hardware_enable,
14924         .hardware_disable = hardware_disable,
14925         .cpu_has_accelerated_tpr = report_flexpriority,
14926         .has_emulated_msr = vmx_has_emulated_msr,
14927
14928         .vm_init = vmx_vm_init,
14929         .vm_alloc = vmx_vm_alloc,
14930         .vm_free = vmx_vm_free,
14931
14932         .vcpu_create = vmx_create_vcpu,
14933         .vcpu_free = vmx_free_vcpu,
14934         .vcpu_reset = vmx_vcpu_reset,
14935
14936         .prepare_guest_switch = vmx_prepare_switch_to_guest,
14937         .vcpu_load = vmx_vcpu_load,
14938         .vcpu_put = vmx_vcpu_put,
14939
14940         .update_bp_intercept = update_exception_bitmap,
14941         .get_msr_feature = vmx_get_msr_feature,
14942         .get_msr = vmx_get_msr,
14943         .set_msr = vmx_set_msr,
14944         .get_segment_base = vmx_get_segment_base,
14945         .get_segment = vmx_get_segment,
14946         .set_segment = vmx_set_segment,
14947         .get_cpl = vmx_get_cpl,
14948         .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
14949         .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
14950         .decache_cr3 = vmx_decache_cr3,
14951         .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
14952         .set_cr0 = vmx_set_cr0,
14953         .set_cr3 = vmx_set_cr3,
14954         .set_cr4 = vmx_set_cr4,
14955         .set_efer = vmx_set_efer,
14956         .get_idt = vmx_get_idt,
14957         .set_idt = vmx_set_idt,
14958         .get_gdt = vmx_get_gdt,
14959         .set_gdt = vmx_set_gdt,
14960         .get_dr6 = vmx_get_dr6,
14961         .set_dr6 = vmx_set_dr6,
14962         .set_dr7 = vmx_set_dr7,
14963         .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
14964         .cache_reg = vmx_cache_reg,
14965         .get_rflags = vmx_get_rflags,
14966         .set_rflags = vmx_set_rflags,
14967
14968         .tlb_flush = vmx_flush_tlb,
14969         .tlb_flush_gva = vmx_flush_tlb_gva,
14970
14971         .run = vmx_vcpu_run,
14972         .handle_exit = vmx_handle_exit,
14973         .skip_emulated_instruction = skip_emulated_instruction,
14974         .set_interrupt_shadow = vmx_set_interrupt_shadow,
14975         .get_interrupt_shadow = vmx_get_interrupt_shadow,
14976         .patch_hypercall = vmx_patch_hypercall,
14977         .set_irq = vmx_inject_irq,
14978         .set_nmi = vmx_inject_nmi,
14979         .queue_exception = vmx_queue_exception,
14980         .cancel_injection = vmx_cancel_injection,
14981         .interrupt_allowed = vmx_interrupt_allowed,
14982         .nmi_allowed = vmx_nmi_allowed,
14983         .get_nmi_mask = vmx_get_nmi_mask,
14984         .set_nmi_mask = vmx_set_nmi_mask,
14985         .enable_nmi_window = enable_nmi_window,
14986         .enable_irq_window = enable_irq_window,
14987         .update_cr8_intercept = update_cr8_intercept,
14988         .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
14989         .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
14990         .get_enable_apicv = vmx_get_enable_apicv,
14991         .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
14992         .load_eoi_exitmap = vmx_load_eoi_exitmap,
14993         .apicv_post_state_restore = vmx_apicv_post_state_restore,
14994         .hwapic_irr_update = vmx_hwapic_irr_update,
14995         .hwapic_isr_update = vmx_hwapic_isr_update,
14996         .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
14997         .sync_pir_to_irr = vmx_sync_pir_to_irr,
14998         .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
14999
15000         .set_tss_addr = vmx_set_tss_addr,
15001         .set_identity_map_addr = vmx_set_identity_map_addr,
15002         .get_tdp_level = get_ept_level,
15003         .get_mt_mask = vmx_get_mt_mask,
15004
15005         .get_exit_info = vmx_get_exit_info,
15006
15007         .get_lpage_level = vmx_get_lpage_level,
15008
15009         .cpuid_update = vmx_cpuid_update,
15010
15011         .rdtscp_supported = vmx_rdtscp_supported,
15012         .invpcid_supported = vmx_invpcid_supported,
15013
15014         .set_supported_cpuid = vmx_set_supported_cpuid,
15015
15016         .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
15017
15018         .read_l1_tsc_offset = vmx_read_l1_tsc_offset,
15019         .write_tsc_offset = vmx_write_tsc_offset,
15020
15021         .set_tdp_cr3 = vmx_set_cr3,
15022
15023         .check_intercept = vmx_check_intercept,
15024         .handle_external_intr = vmx_handle_external_intr,
15025         .mpx_supported = vmx_mpx_supported,
15026         .xsaves_supported = vmx_xsaves_supported,
15027         .umip_emulated = vmx_umip_emulated,
15028
15029         .check_nested_events = vmx_check_nested_events,
15030         .request_immediate_exit = vmx_request_immediate_exit,
15031
15032         .sched_in = vmx_sched_in,
15033
15034         .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
15035         .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
15036         .flush_log_dirty = vmx_flush_log_dirty,
15037         .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
15038         .write_log_dirty = vmx_write_pml_buffer,
15039
15040         .pre_block = vmx_pre_block,
15041         .post_block = vmx_post_block,
15042
15043         .pmu_ops = &intel_pmu_ops,
15044
15045         .update_pi_irte = vmx_update_pi_irte,
15046
15047 #ifdef CONFIG_X86_64
15048         .set_hv_timer = vmx_set_hv_timer,
15049         .cancel_hv_timer = vmx_cancel_hv_timer,
15050 #endif
15051
15052         .setup_mce = vmx_setup_mce,
15053
15054         .get_nested_state = vmx_get_nested_state,
15055         .set_nested_state = vmx_set_nested_state,
15056         .get_vmcs12_pages = nested_get_vmcs12_pages,
15057
15058         .smi_allowed = vmx_smi_allowed,
15059         .pre_enter_smm = vmx_pre_enter_smm,
15060         .pre_leave_smm = vmx_pre_leave_smm,
15061         .enable_smi_window = enable_smi_window,
15062
15063         .nested_enable_evmcs = nested_enable_evmcs,
15064 };
15065
15066 static void vmx_cleanup_l1d_flush(void)
15067 {
15068         if (vmx_l1d_flush_pages) {
15069                 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
15070                 vmx_l1d_flush_pages = NULL;
15071         }
15072         /* Restore state so sysfs ignores VMX */
15073         l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
15074 }
15075
15076 static void vmx_exit(void)
15077 {
15078 #ifdef CONFIG_KEXEC_CORE
15079         RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
15080         synchronize_rcu();
15081 #endif
15082
15083         kvm_exit();
15084
15085 #if IS_ENABLED(CONFIG_HYPERV)
15086         if (static_branch_unlikely(&enable_evmcs)) {
15087                 int cpu;
15088                 struct hv_vp_assist_page *vp_ap;
15089                 /*
15090                  * Reset everything to support using non-enlightened VMCS
15091                  * access later (e.g. when we reload the module with
15092                  * enlightened_vmcs=0)
15093                  */
15094                 for_each_online_cpu(cpu) {
15095                         vp_ap = hv_get_vp_assist_page(cpu);
15096
15097                         if (!vp_ap)
15098                                 continue;
15099
15100                         vp_ap->current_nested_vmcs = 0;
15101                         vp_ap->enlighten_vmentry = 0;
15102                 }
15103
15104                 static_branch_disable(&enable_evmcs);
15105         }
15106 #endif
15107         vmx_cleanup_l1d_flush();
15108 }
15109 module_exit(vmx_exit);
15110
15111 static int __init vmx_init(void)
15112 {
15113         int r;
15114
15115 #if IS_ENABLED(CONFIG_HYPERV)
15116         /*
15117          * Enlightened VMCS usage should be recommended and the host needs
15118          * to support eVMCS v1 or above. We can also disable eVMCS support
15119          * with module parameter.
15120          */
15121         if (enlightened_vmcs &&
15122             ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
15123             (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
15124             KVM_EVMCS_VERSION) {
15125                 int cpu;
15126
15127                 /* Check that we have assist pages on all online CPUs */
15128                 for_each_online_cpu(cpu) {
15129                         if (!hv_get_vp_assist_page(cpu)) {
15130                                 enlightened_vmcs = false;
15131                                 break;
15132                         }
15133                 }
15134
15135                 if (enlightened_vmcs) {
15136                         pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
15137                         static_branch_enable(&enable_evmcs);
15138                 }
15139         } else {
15140                 enlightened_vmcs = false;
15141         }
15142 #endif
15143
15144         r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
15145                      __alignof__(struct vcpu_vmx), THIS_MODULE);
15146         if (r)
15147                 return r;
15148
15149         /*
15150          * Must be called after kvm_init() so enable_ept is properly set
15151          * up. Hand the parameter mitigation value in which was stored in
15152          * the pre module init parser. If no parameter was given, it will
15153          * contain 'auto' which will be turned into the default 'cond'
15154          * mitigation mode.
15155          */
15156         if (boot_cpu_has(X86_BUG_L1TF)) {
15157                 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
15158                 if (r) {
15159                         vmx_exit();
15160                         return r;
15161                 }
15162         }
15163
15164 #ifdef CONFIG_KEXEC_CORE
15165         rcu_assign_pointer(crash_vmclear_loaded_vmcss,
15166                            crash_vmclear_local_loaded_vmcss);
15167 #endif
15168         vmx_check_vmcs12_offsets();
15169
15170         return 0;
15171 }
15172 module_init(vmx_init);