mtd: nand: Fix memory allocation in nanddev_bbt_init()
[sfrench/cifs-2.6.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, "xor " 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 = 1;
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         /*
1581          * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs the address of the
1582          * base of EPT PML4 table, strip off EPT configuration information.
1583          */
1584         if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
1585                 kvm_for_each_vcpu(i, vcpu, kvm)
1586                         ret |= hyperv_flush_guest_mapping(
1587                                 to_vmx(kvm_get_vcpu(kvm, i))->ept_pointer & PAGE_MASK);
1588         } else {
1589                 ret = hyperv_flush_guest_mapping(
1590                                 to_vmx(kvm_get_vcpu(kvm, 0))->ept_pointer & PAGE_MASK);
1591         }
1592
1593         spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
1594         return ret;
1595 }
1596 #else /* !IS_ENABLED(CONFIG_HYPERV) */
1597 static inline void evmcs_write64(unsigned long field, u64 value) {}
1598 static inline void evmcs_write32(unsigned long field, u32 value) {}
1599 static inline void evmcs_write16(unsigned long field, u16 value) {}
1600 static inline u64 evmcs_read64(unsigned long field) { return 0; }
1601 static inline u32 evmcs_read32(unsigned long field) { return 0; }
1602 static inline u16 evmcs_read16(unsigned long field) { return 0; }
1603 static inline void evmcs_load(u64 phys_addr) {}
1604 static inline void evmcs_sanitize_exec_ctrls(struct vmcs_config *vmcs_conf) {}
1605 static inline void evmcs_touch_msr_bitmap(void) {}
1606 #endif /* IS_ENABLED(CONFIG_HYPERV) */
1607
1608 static int nested_enable_evmcs(struct kvm_vcpu *vcpu,
1609                                uint16_t *vmcs_version)
1610 {
1611         struct vcpu_vmx *vmx = to_vmx(vcpu);
1612
1613         /* We don't support disabling the feature for simplicity. */
1614         if (vmx->nested.enlightened_vmcs_enabled)
1615                 return 0;
1616
1617         vmx->nested.enlightened_vmcs_enabled = true;
1618
1619         /*
1620          * vmcs_version represents the range of supported Enlightened VMCS
1621          * versions: lower 8 bits is the minimal version, higher 8 bits is the
1622          * maximum supported version. KVM supports versions from 1 to
1623          * KVM_EVMCS_VERSION.
1624          */
1625         if (vmcs_version)
1626                 *vmcs_version = (KVM_EVMCS_VERSION << 8) | 1;
1627
1628         vmx->nested.msrs.pinbased_ctls_high &= ~EVMCS1_UNSUPPORTED_PINCTRL;
1629         vmx->nested.msrs.entry_ctls_high &= ~EVMCS1_UNSUPPORTED_VMENTRY_CTRL;
1630         vmx->nested.msrs.exit_ctls_high &= ~EVMCS1_UNSUPPORTED_VMEXIT_CTRL;
1631         vmx->nested.msrs.secondary_ctls_high &= ~EVMCS1_UNSUPPORTED_2NDEXEC;
1632         vmx->nested.msrs.vmfunc_controls &= ~EVMCS1_UNSUPPORTED_VMFUNC;
1633
1634         return 0;
1635 }
1636
1637 static inline bool is_exception_n(u32 intr_info, u8 vector)
1638 {
1639         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1640                              INTR_INFO_VALID_MASK)) ==
1641                 (INTR_TYPE_HARD_EXCEPTION | vector | INTR_INFO_VALID_MASK);
1642 }
1643
1644 static inline bool is_debug(u32 intr_info)
1645 {
1646         return is_exception_n(intr_info, DB_VECTOR);
1647 }
1648
1649 static inline bool is_breakpoint(u32 intr_info)
1650 {
1651         return is_exception_n(intr_info, BP_VECTOR);
1652 }
1653
1654 static inline bool is_page_fault(u32 intr_info)
1655 {
1656         return is_exception_n(intr_info, PF_VECTOR);
1657 }
1658
1659 static inline bool is_invalid_opcode(u32 intr_info)
1660 {
1661         return is_exception_n(intr_info, UD_VECTOR);
1662 }
1663
1664 static inline bool is_gp_fault(u32 intr_info)
1665 {
1666         return is_exception_n(intr_info, GP_VECTOR);
1667 }
1668
1669 static inline bool is_machine_check(u32 intr_info)
1670 {
1671         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1672                              INTR_INFO_VALID_MASK)) ==
1673                 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
1674 }
1675
1676 /* Undocumented: icebp/int1 */
1677 static inline bool is_icebp(u32 intr_info)
1678 {
1679         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1680                 == (INTR_TYPE_PRIV_SW_EXCEPTION | INTR_INFO_VALID_MASK);
1681 }
1682
1683 static inline bool cpu_has_vmx_msr_bitmap(void)
1684 {
1685         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
1686 }
1687
1688 static inline bool cpu_has_vmx_tpr_shadow(void)
1689 {
1690         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
1691 }
1692
1693 static inline bool cpu_need_tpr_shadow(struct kvm_vcpu *vcpu)
1694 {
1695         return cpu_has_vmx_tpr_shadow() && lapic_in_kernel(vcpu);
1696 }
1697
1698 static inline bool cpu_has_secondary_exec_ctrls(void)
1699 {
1700         return vmcs_config.cpu_based_exec_ctrl &
1701                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1702 }
1703
1704 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
1705 {
1706         return vmcs_config.cpu_based_2nd_exec_ctrl &
1707                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1708 }
1709
1710 static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
1711 {
1712         return vmcs_config.cpu_based_2nd_exec_ctrl &
1713                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
1714 }
1715
1716 static inline bool cpu_has_vmx_apic_register_virt(void)
1717 {
1718         return vmcs_config.cpu_based_2nd_exec_ctrl &
1719                 SECONDARY_EXEC_APIC_REGISTER_VIRT;
1720 }
1721
1722 static inline bool cpu_has_vmx_virtual_intr_delivery(void)
1723 {
1724         return vmcs_config.cpu_based_2nd_exec_ctrl &
1725                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1726 }
1727
1728 static inline bool cpu_has_vmx_encls_vmexit(void)
1729 {
1730         return vmcs_config.cpu_based_2nd_exec_ctrl &
1731                 SECONDARY_EXEC_ENCLS_EXITING;
1732 }
1733
1734 /*
1735  * Comment's format: document - errata name - stepping - processor name.
1736  * Refer from
1737  * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
1738  */
1739 static u32 vmx_preemption_cpu_tfms[] = {
1740 /* 323344.pdf - BA86   - D0 - Xeon 7500 Series */
1741 0x000206E6,
1742 /* 323056.pdf - AAX65  - C2 - Xeon L3406 */
1743 /* 322814.pdf - AAT59  - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
1744 /* 322911.pdf - AAU65  - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
1745 0x00020652,
1746 /* 322911.pdf - AAU65  - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
1747 0x00020655,
1748 /* 322373.pdf - AAO95  - B1 - Xeon 3400 Series */
1749 /* 322166.pdf - AAN92  - B1 - i7-800 and i5-700 Desktop */
1750 /*
1751  * 320767.pdf - AAP86  - B1 -
1752  * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
1753  */
1754 0x000106E5,
1755 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
1756 0x000106A0,
1757 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
1758 0x000106A1,
1759 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
1760 0x000106A4,
1761  /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
1762  /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
1763  /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
1764 0x000106A5,
1765 };
1766
1767 static inline bool cpu_has_broken_vmx_preemption_timer(void)
1768 {
1769         u32 eax = cpuid_eax(0x00000001), i;
1770
1771         /* Clear the reserved bits */
1772         eax &= ~(0x3U << 14 | 0xfU << 28);
1773         for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
1774                 if (eax == vmx_preemption_cpu_tfms[i])
1775                         return true;
1776
1777         return false;
1778 }
1779
1780 static inline bool cpu_has_vmx_preemption_timer(void)
1781 {
1782         return vmcs_config.pin_based_exec_ctrl &
1783                 PIN_BASED_VMX_PREEMPTION_TIMER;
1784 }
1785
1786 static inline bool cpu_has_vmx_posted_intr(void)
1787 {
1788         return IS_ENABLED(CONFIG_X86_LOCAL_APIC) &&
1789                 vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
1790 }
1791
1792 static inline bool cpu_has_vmx_apicv(void)
1793 {
1794         return cpu_has_vmx_apic_register_virt() &&
1795                 cpu_has_vmx_virtual_intr_delivery() &&
1796                 cpu_has_vmx_posted_intr();
1797 }
1798
1799 static inline bool cpu_has_vmx_flexpriority(void)
1800 {
1801         return cpu_has_vmx_tpr_shadow() &&
1802                 cpu_has_vmx_virtualize_apic_accesses();
1803 }
1804
1805 static inline bool cpu_has_vmx_ept_execute_only(void)
1806 {
1807         return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
1808 }
1809
1810 static inline bool cpu_has_vmx_ept_2m_page(void)
1811 {
1812         return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
1813 }
1814
1815 static inline bool cpu_has_vmx_ept_1g_page(void)
1816 {
1817         return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
1818 }
1819
1820 static inline bool cpu_has_vmx_ept_4levels(void)
1821 {
1822         return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
1823 }
1824
1825 static inline bool cpu_has_vmx_ept_mt_wb(void)
1826 {
1827         return vmx_capability.ept & VMX_EPTP_WB_BIT;
1828 }
1829
1830 static inline bool cpu_has_vmx_ept_5levels(void)
1831 {
1832         return vmx_capability.ept & VMX_EPT_PAGE_WALK_5_BIT;
1833 }
1834
1835 static inline bool cpu_has_vmx_ept_ad_bits(void)
1836 {
1837         return vmx_capability.ept & VMX_EPT_AD_BIT;
1838 }
1839
1840 static inline bool cpu_has_vmx_invept_context(void)
1841 {
1842         return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
1843 }
1844
1845 static inline bool cpu_has_vmx_invept_global(void)
1846 {
1847         return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
1848 }
1849
1850 static inline bool cpu_has_vmx_invvpid_individual_addr(void)
1851 {
1852         return vmx_capability.vpid & VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT;
1853 }
1854
1855 static inline bool cpu_has_vmx_invvpid_single(void)
1856 {
1857         return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
1858 }
1859
1860 static inline bool cpu_has_vmx_invvpid_global(void)
1861 {
1862         return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
1863 }
1864
1865 static inline bool cpu_has_vmx_invvpid(void)
1866 {
1867         return vmx_capability.vpid & VMX_VPID_INVVPID_BIT;
1868 }
1869
1870 static inline bool cpu_has_vmx_ept(void)
1871 {
1872         return vmcs_config.cpu_based_2nd_exec_ctrl &
1873                 SECONDARY_EXEC_ENABLE_EPT;
1874 }
1875
1876 static inline bool cpu_has_vmx_unrestricted_guest(void)
1877 {
1878         return vmcs_config.cpu_based_2nd_exec_ctrl &
1879                 SECONDARY_EXEC_UNRESTRICTED_GUEST;
1880 }
1881
1882 static inline bool cpu_has_vmx_ple(void)
1883 {
1884         return vmcs_config.cpu_based_2nd_exec_ctrl &
1885                 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1886 }
1887
1888 static inline bool cpu_has_vmx_basic_inout(void)
1889 {
1890         return  (((u64)vmcs_config.basic_cap << 32) & VMX_BASIC_INOUT);
1891 }
1892
1893 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
1894 {
1895         return flexpriority_enabled && lapic_in_kernel(vcpu);
1896 }
1897
1898 static inline bool cpu_has_vmx_vpid(void)
1899 {
1900         return vmcs_config.cpu_based_2nd_exec_ctrl &
1901                 SECONDARY_EXEC_ENABLE_VPID;
1902 }
1903
1904 static inline bool cpu_has_vmx_rdtscp(void)
1905 {
1906         return vmcs_config.cpu_based_2nd_exec_ctrl &
1907                 SECONDARY_EXEC_RDTSCP;
1908 }
1909
1910 static inline bool cpu_has_vmx_invpcid(void)
1911 {
1912         return vmcs_config.cpu_based_2nd_exec_ctrl &
1913                 SECONDARY_EXEC_ENABLE_INVPCID;
1914 }
1915
1916 static inline bool cpu_has_virtual_nmis(void)
1917 {
1918         return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1919 }
1920
1921 static inline bool cpu_has_vmx_wbinvd_exit(void)
1922 {
1923         return vmcs_config.cpu_based_2nd_exec_ctrl &
1924                 SECONDARY_EXEC_WBINVD_EXITING;
1925 }
1926
1927 static inline bool cpu_has_vmx_shadow_vmcs(void)
1928 {
1929         u64 vmx_msr;
1930         rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1931         /* check if the cpu supports writing r/o exit information fields */
1932         if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1933                 return false;
1934
1935         return vmcs_config.cpu_based_2nd_exec_ctrl &
1936                 SECONDARY_EXEC_SHADOW_VMCS;
1937 }
1938
1939 static inline bool cpu_has_vmx_pml(void)
1940 {
1941         return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_PML;
1942 }
1943
1944 static inline bool cpu_has_vmx_tsc_scaling(void)
1945 {
1946         return vmcs_config.cpu_based_2nd_exec_ctrl &
1947                 SECONDARY_EXEC_TSC_SCALING;
1948 }
1949
1950 static inline bool cpu_has_vmx_vmfunc(void)
1951 {
1952         return vmcs_config.cpu_based_2nd_exec_ctrl &
1953                 SECONDARY_EXEC_ENABLE_VMFUNC;
1954 }
1955
1956 static bool vmx_umip_emulated(void)
1957 {
1958         return vmcs_config.cpu_based_2nd_exec_ctrl &
1959                 SECONDARY_EXEC_DESC;
1960 }
1961
1962 static inline bool report_flexpriority(void)
1963 {
1964         return flexpriority_enabled;
1965 }
1966
1967 static inline unsigned nested_cpu_vmx_misc_cr3_count(struct kvm_vcpu *vcpu)
1968 {
1969         return vmx_misc_cr3_count(to_vmx(vcpu)->nested.msrs.misc_low);
1970 }
1971
1972 /*
1973  * Do the virtual VMX capability MSRs specify that L1 can use VMWRITE
1974  * to modify any valid field of the VMCS, or are the VM-exit
1975  * information fields read-only?
1976  */
1977 static inline bool nested_cpu_has_vmwrite_any_field(struct kvm_vcpu *vcpu)
1978 {
1979         return to_vmx(vcpu)->nested.msrs.misc_low &
1980                 MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS;
1981 }
1982
1983 static inline bool nested_cpu_has_zero_length_injection(struct kvm_vcpu *vcpu)
1984 {
1985         return to_vmx(vcpu)->nested.msrs.misc_low & VMX_MISC_ZERO_LEN_INS;
1986 }
1987
1988 static inline bool nested_cpu_supports_monitor_trap_flag(struct kvm_vcpu *vcpu)
1989 {
1990         return to_vmx(vcpu)->nested.msrs.procbased_ctls_high &
1991                         CPU_BASED_MONITOR_TRAP_FLAG;
1992 }
1993
1994 static inline bool nested_cpu_has_vmx_shadow_vmcs(struct kvm_vcpu *vcpu)
1995 {
1996         return to_vmx(vcpu)->nested.msrs.secondary_ctls_high &
1997                 SECONDARY_EXEC_SHADOW_VMCS;
1998 }
1999
2000 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
2001 {
2002         return vmcs12->cpu_based_vm_exec_control & bit;
2003 }
2004
2005 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
2006 {
2007         return (vmcs12->cpu_based_vm_exec_control &
2008                         CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
2009                 (vmcs12->secondary_vm_exec_control & bit);
2010 }
2011
2012 static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
2013 {
2014         return vmcs12->pin_based_vm_exec_control &
2015                 PIN_BASED_VMX_PREEMPTION_TIMER;
2016 }
2017
2018 static inline bool nested_cpu_has_nmi_exiting(struct vmcs12 *vmcs12)
2019 {
2020         return vmcs12->pin_based_vm_exec_control & PIN_BASED_NMI_EXITING;
2021 }
2022
2023 static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12)
2024 {
2025         return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
2026 }
2027
2028 static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
2029 {
2030         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
2031 }
2032
2033 static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
2034 {
2035         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
2036 }
2037
2038 static inline bool nested_cpu_has_pml(struct vmcs12 *vmcs12)
2039 {
2040         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML);
2041 }
2042
2043 static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
2044 {
2045         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
2046 }
2047
2048 static inline bool nested_cpu_has_vpid(struct vmcs12 *vmcs12)
2049 {
2050         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VPID);
2051 }
2052
2053 static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
2054 {
2055         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
2056 }
2057
2058 static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
2059 {
2060         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2061 }
2062
2063 static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
2064 {
2065         return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
2066 }
2067
2068 static inline bool nested_cpu_has_vmfunc(struct vmcs12 *vmcs12)
2069 {
2070         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VMFUNC);
2071 }
2072
2073 static inline bool nested_cpu_has_eptp_switching(struct vmcs12 *vmcs12)
2074 {
2075         return nested_cpu_has_vmfunc(vmcs12) &&
2076                 (vmcs12->vm_function_control &
2077                  VMX_VMFUNC_EPTP_SWITCHING);
2078 }
2079
2080 static inline bool nested_cpu_has_shadow_vmcs(struct vmcs12 *vmcs12)
2081 {
2082         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_SHADOW_VMCS);
2083 }
2084
2085 static inline bool is_nmi(u32 intr_info)
2086 {
2087         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
2088                 == (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK);
2089 }
2090
2091 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
2092                               u32 exit_intr_info,
2093                               unsigned long exit_qualification);
2094
2095 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
2096 {
2097         int i;
2098
2099         for (i = 0; i < vmx->nmsrs; ++i)
2100                 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
2101                         return i;
2102         return -1;
2103 }
2104
2105 static inline void __invvpid(unsigned long ext, u16 vpid, gva_t gva)
2106 {
2107     struct {
2108         u64 vpid : 16;
2109         u64 rsvd : 48;
2110         u64 gva;
2111     } operand = { vpid, 0, gva };
2112     bool error;
2113
2114     asm volatile (__ex("invvpid %2, %1") CC_SET(na)
2115                   : CC_OUT(na) (error) : "r"(ext), "m"(operand));
2116     BUG_ON(error);
2117 }
2118
2119 static inline void __invept(unsigned long ext, u64 eptp, gpa_t gpa)
2120 {
2121         struct {
2122                 u64 eptp, gpa;
2123         } operand = {eptp, gpa};
2124         bool error;
2125
2126         asm volatile (__ex("invept %2, %1") CC_SET(na)
2127                       : CC_OUT(na) (error) : "r"(ext), "m"(operand));
2128         BUG_ON(error);
2129 }
2130
2131 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
2132 {
2133         int i;
2134
2135         i = __find_msr_index(vmx, msr);
2136         if (i >= 0)
2137                 return &vmx->guest_msrs[i];
2138         return NULL;
2139 }
2140
2141 static void vmcs_clear(struct vmcs *vmcs)
2142 {
2143         u64 phys_addr = __pa(vmcs);
2144         bool error;
2145
2146         asm volatile (__ex("vmclear %1") CC_SET(na)
2147                       : CC_OUT(na) (error) : "m"(phys_addr));
2148         if (unlikely(error))
2149                 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
2150                        vmcs, phys_addr);
2151 }
2152
2153 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
2154 {
2155         vmcs_clear(loaded_vmcs->vmcs);
2156         if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
2157                 vmcs_clear(loaded_vmcs->shadow_vmcs);
2158         loaded_vmcs->cpu = -1;
2159         loaded_vmcs->launched = 0;
2160 }
2161
2162 static void vmcs_load(struct vmcs *vmcs)
2163 {
2164         u64 phys_addr = __pa(vmcs);
2165         bool error;
2166
2167         if (static_branch_unlikely(&enable_evmcs))
2168                 return evmcs_load(phys_addr);
2169
2170         asm volatile (__ex("vmptrld %1") CC_SET(na)
2171                       : CC_OUT(na) (error) : "m"(phys_addr));
2172         if (unlikely(error))
2173                 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
2174                        vmcs, phys_addr);
2175 }
2176
2177 #ifdef CONFIG_KEXEC_CORE
2178 /*
2179  * This bitmap is used to indicate whether the vmclear
2180  * operation is enabled on all cpus. All disabled by
2181  * default.
2182  */
2183 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
2184
2185 static inline void crash_enable_local_vmclear(int cpu)
2186 {
2187         cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
2188 }
2189
2190 static inline void crash_disable_local_vmclear(int cpu)
2191 {
2192         cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
2193 }
2194
2195 static inline int crash_local_vmclear_enabled(int cpu)
2196 {
2197         return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
2198 }
2199
2200 static void crash_vmclear_local_loaded_vmcss(void)
2201 {
2202         int cpu = raw_smp_processor_id();
2203         struct loaded_vmcs *v;
2204
2205         if (!crash_local_vmclear_enabled(cpu))
2206                 return;
2207
2208         list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
2209                             loaded_vmcss_on_cpu_link)
2210                 vmcs_clear(v->vmcs);
2211 }
2212 #else
2213 static inline void crash_enable_local_vmclear(int cpu) { }
2214 static inline void crash_disable_local_vmclear(int cpu) { }
2215 #endif /* CONFIG_KEXEC_CORE */
2216
2217 static void __loaded_vmcs_clear(void *arg)
2218 {
2219         struct loaded_vmcs *loaded_vmcs = arg;
2220         int cpu = raw_smp_processor_id();
2221
2222         if (loaded_vmcs->cpu != cpu)
2223                 return; /* vcpu migration can race with cpu offline */
2224         if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
2225                 per_cpu(current_vmcs, cpu) = NULL;
2226         crash_disable_local_vmclear(cpu);
2227         list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
2228
2229         /*
2230          * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
2231          * is before setting loaded_vmcs->vcpu to -1 which is done in
2232          * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
2233          * then adds the vmcs into percpu list before it is deleted.
2234          */
2235         smp_wmb();
2236
2237         loaded_vmcs_init(loaded_vmcs);
2238         crash_enable_local_vmclear(cpu);
2239 }
2240
2241 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
2242 {
2243         int cpu = loaded_vmcs->cpu;
2244
2245         if (cpu != -1)
2246                 smp_call_function_single(cpu,
2247                          __loaded_vmcs_clear, loaded_vmcs, 1);
2248 }
2249
2250 static inline bool vpid_sync_vcpu_addr(int vpid, gva_t addr)
2251 {
2252         if (vpid == 0)
2253                 return true;
2254
2255         if (cpu_has_vmx_invvpid_individual_addr()) {
2256                 __invvpid(VMX_VPID_EXTENT_INDIVIDUAL_ADDR, vpid, addr);
2257                 return true;
2258         }
2259
2260         return false;
2261 }
2262
2263 static inline void vpid_sync_vcpu_single(int vpid)
2264 {
2265         if (vpid == 0)
2266                 return;
2267
2268         if (cpu_has_vmx_invvpid_single())
2269                 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vpid, 0);
2270 }
2271
2272 static inline void vpid_sync_vcpu_global(void)
2273 {
2274         if (cpu_has_vmx_invvpid_global())
2275                 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
2276 }
2277
2278 static inline void vpid_sync_context(int vpid)
2279 {
2280         if (cpu_has_vmx_invvpid_single())
2281                 vpid_sync_vcpu_single(vpid);
2282         else
2283                 vpid_sync_vcpu_global();
2284 }
2285
2286 static inline void ept_sync_global(void)
2287 {
2288         __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
2289 }
2290
2291 static inline void ept_sync_context(u64 eptp)
2292 {
2293         if (cpu_has_vmx_invept_context())
2294                 __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
2295         else
2296                 ept_sync_global();
2297 }
2298
2299 static __always_inline void vmcs_check16(unsigned long field)
2300 {
2301         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
2302                          "16-bit accessor invalid for 64-bit field");
2303         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2304                          "16-bit accessor invalid for 64-bit high field");
2305         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2306                          "16-bit accessor invalid for 32-bit high field");
2307         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2308                          "16-bit accessor invalid for natural width field");
2309 }
2310
2311 static __always_inline void vmcs_check32(unsigned long field)
2312 {
2313         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2314                          "32-bit accessor invalid for 16-bit field");
2315         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2316                          "32-bit accessor invalid for natural width field");
2317 }
2318
2319 static __always_inline void vmcs_check64(unsigned long field)
2320 {
2321         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2322                          "64-bit accessor invalid for 16-bit field");
2323         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2324                          "64-bit accessor invalid for 64-bit high field");
2325         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2326                          "64-bit accessor invalid for 32-bit field");
2327         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2328                          "64-bit accessor invalid for natural width field");
2329 }
2330
2331 static __always_inline void vmcs_checkl(unsigned long field)
2332 {
2333         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2334                          "Natural width accessor invalid for 16-bit field");
2335         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
2336                          "Natural width accessor invalid for 64-bit field");
2337         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2338                          "Natural width accessor invalid for 64-bit high field");
2339         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2340                          "Natural width accessor invalid for 32-bit field");
2341 }
2342
2343 static __always_inline unsigned long __vmcs_readl(unsigned long field)
2344 {
2345         unsigned long value;
2346
2347         asm volatile (__ex_clear("vmread %1, %0", "%k0")
2348                       : "=r"(value) : "r"(field));
2349         return value;
2350 }
2351
2352 static __always_inline u16 vmcs_read16(unsigned long field)
2353 {
2354         vmcs_check16(field);
2355         if (static_branch_unlikely(&enable_evmcs))
2356                 return evmcs_read16(field);
2357         return __vmcs_readl(field);
2358 }
2359
2360 static __always_inline u32 vmcs_read32(unsigned long field)
2361 {
2362         vmcs_check32(field);
2363         if (static_branch_unlikely(&enable_evmcs))
2364                 return evmcs_read32(field);
2365         return __vmcs_readl(field);
2366 }
2367
2368 static __always_inline u64 vmcs_read64(unsigned long field)
2369 {
2370         vmcs_check64(field);
2371         if (static_branch_unlikely(&enable_evmcs))
2372                 return evmcs_read64(field);
2373 #ifdef CONFIG_X86_64
2374         return __vmcs_readl(field);
2375 #else
2376         return __vmcs_readl(field) | ((u64)__vmcs_readl(field+1) << 32);
2377 #endif
2378 }
2379
2380 static __always_inline unsigned long vmcs_readl(unsigned long field)
2381 {
2382         vmcs_checkl(field);
2383         if (static_branch_unlikely(&enable_evmcs))
2384                 return evmcs_read64(field);
2385         return __vmcs_readl(field);
2386 }
2387
2388 static noinline void vmwrite_error(unsigned long field, unsigned long value)
2389 {
2390         printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
2391                field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
2392         dump_stack();
2393 }
2394
2395 static __always_inline void __vmcs_writel(unsigned long field, unsigned long value)
2396 {
2397         bool error;
2398
2399         asm volatile (__ex("vmwrite %2, %1") CC_SET(na)
2400                       : CC_OUT(na) (error) : "r"(field), "rm"(value));
2401         if (unlikely(error))
2402                 vmwrite_error(field, value);
2403 }
2404
2405 static __always_inline void vmcs_write16(unsigned long field, u16 value)
2406 {
2407         vmcs_check16(field);
2408         if (static_branch_unlikely(&enable_evmcs))
2409                 return evmcs_write16(field, value);
2410
2411         __vmcs_writel(field, value);
2412 }
2413
2414 static __always_inline void vmcs_write32(unsigned long field, u32 value)
2415 {
2416         vmcs_check32(field);
2417         if (static_branch_unlikely(&enable_evmcs))
2418                 return evmcs_write32(field, value);
2419
2420         __vmcs_writel(field, value);
2421 }
2422
2423 static __always_inline void vmcs_write64(unsigned long field, u64 value)
2424 {
2425         vmcs_check64(field);
2426         if (static_branch_unlikely(&enable_evmcs))
2427                 return evmcs_write64(field, value);
2428
2429         __vmcs_writel(field, value);
2430 #ifndef CONFIG_X86_64
2431         asm volatile ("");
2432         __vmcs_writel(field+1, value >> 32);
2433 #endif
2434 }
2435
2436 static __always_inline void vmcs_writel(unsigned long field, unsigned long value)
2437 {
2438         vmcs_checkl(field);
2439         if (static_branch_unlikely(&enable_evmcs))
2440                 return evmcs_write64(field, value);
2441
2442         __vmcs_writel(field, value);
2443 }
2444
2445 static __always_inline void vmcs_clear_bits(unsigned long field, u32 mask)
2446 {
2447         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
2448                          "vmcs_clear_bits does not support 64-bit fields");
2449         if (static_branch_unlikely(&enable_evmcs))
2450                 return evmcs_write32(field, evmcs_read32(field) & ~mask);
2451
2452         __vmcs_writel(field, __vmcs_readl(field) & ~mask);
2453 }
2454
2455 static __always_inline void vmcs_set_bits(unsigned long field, u32 mask)
2456 {
2457         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
2458                          "vmcs_set_bits does not support 64-bit fields");
2459         if (static_branch_unlikely(&enable_evmcs))
2460                 return evmcs_write32(field, evmcs_read32(field) | mask);
2461
2462         __vmcs_writel(field, __vmcs_readl(field) | mask);
2463 }
2464
2465 static inline void vm_entry_controls_reset_shadow(struct vcpu_vmx *vmx)
2466 {
2467         vmx->vm_entry_controls_shadow = vmcs_read32(VM_ENTRY_CONTROLS);
2468 }
2469
2470 static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
2471 {
2472         vmcs_write32(VM_ENTRY_CONTROLS, val);
2473         vmx->vm_entry_controls_shadow = val;
2474 }
2475
2476 static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
2477 {
2478         if (vmx->vm_entry_controls_shadow != val)
2479                 vm_entry_controls_init(vmx, val);
2480 }
2481
2482 static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
2483 {
2484         return vmx->vm_entry_controls_shadow;
2485 }
2486
2487
2488 static inline void vm_entry_controls_setbit(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_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
2494 {
2495         vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
2496 }
2497
2498 static inline void vm_exit_controls_reset_shadow(struct vcpu_vmx *vmx)
2499 {
2500         vmx->vm_exit_controls_shadow = vmcs_read32(VM_EXIT_CONTROLS);
2501 }
2502
2503 static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
2504 {
2505         vmcs_write32(VM_EXIT_CONTROLS, val);
2506         vmx->vm_exit_controls_shadow = val;
2507 }
2508
2509 static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
2510 {
2511         if (vmx->vm_exit_controls_shadow != val)
2512                 vm_exit_controls_init(vmx, val);
2513 }
2514
2515 static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
2516 {
2517         return vmx->vm_exit_controls_shadow;
2518 }
2519
2520
2521 static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
2522 {
2523         vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
2524 }
2525
2526 static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
2527 {
2528         vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
2529 }
2530
2531 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
2532 {
2533         vmx->segment_cache.bitmask = 0;
2534 }
2535
2536 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
2537                                        unsigned field)
2538 {
2539         bool ret;
2540         u32 mask = 1 << (seg * SEG_FIELD_NR + field);
2541
2542         if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
2543                 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
2544                 vmx->segment_cache.bitmask = 0;
2545         }
2546         ret = vmx->segment_cache.bitmask & mask;
2547         vmx->segment_cache.bitmask |= mask;
2548         return ret;
2549 }
2550
2551 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
2552 {
2553         u16 *p = &vmx->segment_cache.seg[seg].selector;
2554
2555         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
2556                 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
2557         return *p;
2558 }
2559
2560 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
2561 {
2562         ulong *p = &vmx->segment_cache.seg[seg].base;
2563
2564         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
2565                 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
2566         return *p;
2567 }
2568
2569 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
2570 {
2571         u32 *p = &vmx->segment_cache.seg[seg].limit;
2572
2573         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
2574                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
2575         return *p;
2576 }
2577
2578 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
2579 {
2580         u32 *p = &vmx->segment_cache.seg[seg].ar;
2581
2582         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
2583                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
2584         return *p;
2585 }
2586
2587 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
2588 {
2589         u32 eb;
2590
2591         eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
2592              (1u << DB_VECTOR) | (1u << AC_VECTOR);
2593         /*
2594          * Guest access to VMware backdoor ports could legitimately
2595          * trigger #GP because of TSS I/O permission bitmap.
2596          * We intercept those #GP and allow access to them anyway
2597          * as VMware does.
2598          */
2599         if (enable_vmware_backdoor)
2600                 eb |= (1u << GP_VECTOR);
2601         if ((vcpu->guest_debug &
2602              (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
2603             (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
2604                 eb |= 1u << BP_VECTOR;
2605         if (to_vmx(vcpu)->rmode.vm86_active)
2606                 eb = ~0;
2607         if (enable_ept)
2608                 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
2609
2610         /* When we are running a nested L2 guest and L1 specified for it a
2611          * certain exception bitmap, we must trap the same exceptions and pass
2612          * them to L1. When running L2, we will only handle the exceptions
2613          * specified above if L1 did not want them.
2614          */
2615         if (is_guest_mode(vcpu))
2616                 eb |= get_vmcs12(vcpu)->exception_bitmap;
2617
2618         vmcs_write32(EXCEPTION_BITMAP, eb);
2619 }
2620
2621 /*
2622  * Check if MSR is intercepted for currently loaded MSR bitmap.
2623  */
2624 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
2625 {
2626         unsigned long *msr_bitmap;
2627         int f = sizeof(unsigned long);
2628
2629         if (!cpu_has_vmx_msr_bitmap())
2630                 return true;
2631
2632         msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
2633
2634         if (msr <= 0x1fff) {
2635                 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2636         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2637                 msr &= 0x1fff;
2638                 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2639         }
2640
2641         return true;
2642 }
2643
2644 /*
2645  * Check if MSR is intercepted for L01 MSR bitmap.
2646  */
2647 static bool msr_write_intercepted_l01(struct kvm_vcpu *vcpu, u32 msr)
2648 {
2649         unsigned long *msr_bitmap;
2650         int f = sizeof(unsigned long);
2651
2652         if (!cpu_has_vmx_msr_bitmap())
2653                 return true;
2654
2655         msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
2656
2657         if (msr <= 0x1fff) {
2658                 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2659         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2660                 msr &= 0x1fff;
2661                 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2662         }
2663
2664         return true;
2665 }
2666
2667 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2668                 unsigned long entry, unsigned long exit)
2669 {
2670         vm_entry_controls_clearbit(vmx, entry);
2671         vm_exit_controls_clearbit(vmx, exit);
2672 }
2673
2674 static int find_msr(struct vmx_msrs *m, unsigned int msr)
2675 {
2676         unsigned int i;
2677
2678         for (i = 0; i < m->nr; ++i) {
2679                 if (m->val[i].index == msr)
2680                         return i;
2681         }
2682         return -ENOENT;
2683 }
2684
2685 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
2686 {
2687         int i;
2688         struct msr_autoload *m = &vmx->msr_autoload;
2689
2690         switch (msr) {
2691         case MSR_EFER:
2692                 if (cpu_has_load_ia32_efer) {
2693                         clear_atomic_switch_msr_special(vmx,
2694                                         VM_ENTRY_LOAD_IA32_EFER,
2695                                         VM_EXIT_LOAD_IA32_EFER);
2696                         return;
2697                 }
2698                 break;
2699         case MSR_CORE_PERF_GLOBAL_CTRL:
2700                 if (cpu_has_load_perf_global_ctrl) {
2701                         clear_atomic_switch_msr_special(vmx,
2702                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2703                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
2704                         return;
2705                 }
2706                 break;
2707         }
2708         i = find_msr(&m->guest, msr);
2709         if (i < 0)
2710                 goto skip_guest;
2711         --m->guest.nr;
2712         m->guest.val[i] = m->guest.val[m->guest.nr];
2713         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2714
2715 skip_guest:
2716         i = find_msr(&m->host, msr);
2717         if (i < 0)
2718                 return;
2719
2720         --m->host.nr;
2721         m->host.val[i] = m->host.val[m->host.nr];
2722         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2723 }
2724
2725 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2726                 unsigned long entry, unsigned long exit,
2727                 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
2728                 u64 guest_val, u64 host_val)
2729 {
2730         vmcs_write64(guest_val_vmcs, guest_val);
2731         if (host_val_vmcs != HOST_IA32_EFER)
2732                 vmcs_write64(host_val_vmcs, host_val);
2733         vm_entry_controls_setbit(vmx, entry);
2734         vm_exit_controls_setbit(vmx, exit);
2735 }
2736
2737 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
2738                                   u64 guest_val, u64 host_val, bool entry_only)
2739 {
2740         int i, j = 0;
2741         struct msr_autoload *m = &vmx->msr_autoload;
2742
2743         switch (msr) {
2744         case MSR_EFER:
2745                 if (cpu_has_load_ia32_efer) {
2746                         add_atomic_switch_msr_special(vmx,
2747                                         VM_ENTRY_LOAD_IA32_EFER,
2748                                         VM_EXIT_LOAD_IA32_EFER,
2749                                         GUEST_IA32_EFER,
2750                                         HOST_IA32_EFER,
2751                                         guest_val, host_val);
2752                         return;
2753                 }
2754                 break;
2755         case MSR_CORE_PERF_GLOBAL_CTRL:
2756                 if (cpu_has_load_perf_global_ctrl) {
2757                         add_atomic_switch_msr_special(vmx,
2758                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2759                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
2760                                         GUEST_IA32_PERF_GLOBAL_CTRL,
2761                                         HOST_IA32_PERF_GLOBAL_CTRL,
2762                                         guest_val, host_val);
2763                         return;
2764                 }
2765                 break;
2766         case MSR_IA32_PEBS_ENABLE:
2767                 /* PEBS needs a quiescent period after being disabled (to write
2768                  * a record).  Disabling PEBS through VMX MSR swapping doesn't
2769                  * provide that period, so a CPU could write host's record into
2770                  * guest's memory.
2771                  */
2772                 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
2773         }
2774
2775         i = find_msr(&m->guest, msr);
2776         if (!entry_only)
2777                 j = find_msr(&m->host, msr);
2778
2779         if (i == NR_AUTOLOAD_MSRS || j == NR_AUTOLOAD_MSRS) {
2780                 printk_once(KERN_WARNING "Not enough msr switch entries. "
2781                                 "Can't add msr %x\n", msr);
2782                 return;
2783         }
2784         if (i < 0) {
2785                 i = m->guest.nr++;
2786                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2787         }
2788         m->guest.val[i].index = msr;
2789         m->guest.val[i].value = guest_val;
2790
2791         if (entry_only)
2792                 return;
2793
2794         if (j < 0) {
2795                 j = m->host.nr++;
2796                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2797         }
2798         m->host.val[j].index = msr;
2799         m->host.val[j].value = host_val;
2800 }
2801
2802 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
2803 {
2804         u64 guest_efer = vmx->vcpu.arch.efer;
2805         u64 ignore_bits = 0;
2806
2807         if (!enable_ept) {
2808                 /*
2809                  * NX is needed to handle CR0.WP=1, CR4.SMEP=1.  Testing
2810                  * host CPUID is more efficient than testing guest CPUID
2811                  * or CR4.  Host SMEP is anyway a requirement for guest SMEP.
2812                  */
2813                 if (boot_cpu_has(X86_FEATURE_SMEP))
2814                         guest_efer |= EFER_NX;
2815                 else if (!(guest_efer & EFER_NX))
2816                         ignore_bits |= EFER_NX;
2817         }
2818
2819         /*
2820          * LMA and LME handled by hardware; SCE meaningless outside long mode.
2821          */
2822         ignore_bits |= EFER_SCE;
2823 #ifdef CONFIG_X86_64
2824         ignore_bits |= EFER_LMA | EFER_LME;
2825         /* SCE is meaningful only in long mode on Intel */
2826         if (guest_efer & EFER_LMA)
2827                 ignore_bits &= ~(u64)EFER_SCE;
2828 #endif
2829
2830         /*
2831          * On EPT, we can't emulate NX, so we must switch EFER atomically.
2832          * On CPUs that support "load IA32_EFER", always switch EFER
2833          * atomically, since it's faster than switching it manually.
2834          */
2835         if (cpu_has_load_ia32_efer ||
2836             (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
2837                 if (!(guest_efer & EFER_LMA))
2838                         guest_efer &= ~EFER_LME;
2839                 if (guest_efer != host_efer)
2840                         add_atomic_switch_msr(vmx, MSR_EFER,
2841                                               guest_efer, host_efer, false);
2842                 else
2843                         clear_atomic_switch_msr(vmx, MSR_EFER);
2844                 return false;
2845         } else {
2846                 clear_atomic_switch_msr(vmx, MSR_EFER);
2847
2848                 guest_efer &= ~ignore_bits;
2849                 guest_efer |= host_efer & ignore_bits;
2850
2851                 vmx->guest_msrs[efer_offset].data = guest_efer;
2852                 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
2853
2854                 return true;
2855         }
2856 }
2857
2858 #ifdef CONFIG_X86_32
2859 /*
2860  * On 32-bit kernels, VM exits still load the FS and GS bases from the
2861  * VMCS rather than the segment table.  KVM uses this helper to figure
2862  * out the current bases to poke them into the VMCS before entry.
2863  */
2864 static unsigned long segment_base(u16 selector)
2865 {
2866         struct desc_struct *table;
2867         unsigned long v;
2868
2869         if (!(selector & ~SEGMENT_RPL_MASK))
2870                 return 0;
2871
2872         table = get_current_gdt_ro();
2873
2874         if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
2875                 u16 ldt_selector = kvm_read_ldt();
2876
2877                 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
2878                         return 0;
2879
2880                 table = (struct desc_struct *)segment_base(ldt_selector);
2881         }
2882         v = get_desc_base(&table[selector >> 3]);
2883         return v;
2884 }
2885 #endif
2886
2887 static void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
2888 {
2889         struct vcpu_vmx *vmx = to_vmx(vcpu);
2890         struct vmcs_host_state *host_state;
2891 #ifdef CONFIG_X86_64
2892         int cpu = raw_smp_processor_id();
2893 #endif
2894         unsigned long fs_base, gs_base;
2895         u16 fs_sel, gs_sel;
2896         int i;
2897
2898         vmx->req_immediate_exit = false;
2899
2900         if (vmx->loaded_cpu_state)
2901                 return;
2902
2903         vmx->loaded_cpu_state = vmx->loaded_vmcs;
2904         host_state = &vmx->loaded_cpu_state->host_state;
2905
2906         /*
2907          * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
2908          * allow segment selectors with cpl > 0 or ti == 1.
2909          */
2910         host_state->ldt_sel = kvm_read_ldt();
2911
2912 #ifdef CONFIG_X86_64
2913         savesegment(ds, host_state->ds_sel);
2914         savesegment(es, host_state->es_sel);
2915
2916         gs_base = cpu_kernelmode_gs_base(cpu);
2917         if (likely(is_64bit_mm(current->mm))) {
2918                 save_fsgs_for_kvm();
2919                 fs_sel = current->thread.fsindex;
2920                 gs_sel = current->thread.gsindex;
2921                 fs_base = current->thread.fsbase;
2922                 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
2923         } else {
2924                 savesegment(fs, fs_sel);
2925                 savesegment(gs, gs_sel);
2926                 fs_base = read_msr(MSR_FS_BASE);
2927                 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
2928         }
2929
2930         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2931 #else
2932         savesegment(fs, fs_sel);
2933         savesegment(gs, gs_sel);
2934         fs_base = segment_base(fs_sel);
2935         gs_base = segment_base(gs_sel);
2936 #endif
2937
2938         if (unlikely(fs_sel != host_state->fs_sel)) {
2939                 if (!(fs_sel & 7))
2940                         vmcs_write16(HOST_FS_SELECTOR, fs_sel);
2941                 else
2942                         vmcs_write16(HOST_FS_SELECTOR, 0);
2943                 host_state->fs_sel = fs_sel;
2944         }
2945         if (unlikely(gs_sel != host_state->gs_sel)) {
2946                 if (!(gs_sel & 7))
2947                         vmcs_write16(HOST_GS_SELECTOR, gs_sel);
2948                 else
2949                         vmcs_write16(HOST_GS_SELECTOR, 0);
2950                 host_state->gs_sel = gs_sel;
2951         }
2952         if (unlikely(fs_base != host_state->fs_base)) {
2953                 vmcs_writel(HOST_FS_BASE, fs_base);
2954                 host_state->fs_base = fs_base;
2955         }
2956         if (unlikely(gs_base != host_state->gs_base)) {
2957                 vmcs_writel(HOST_GS_BASE, gs_base);
2958                 host_state->gs_base = gs_base;
2959         }
2960
2961         for (i = 0; i < vmx->save_nmsrs; ++i)
2962                 kvm_set_shared_msr(vmx->guest_msrs[i].index,
2963                                    vmx->guest_msrs[i].data,
2964                                    vmx->guest_msrs[i].mask);
2965 }
2966
2967 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
2968 {
2969         struct vmcs_host_state *host_state;
2970
2971         if (!vmx->loaded_cpu_state)
2972                 return;
2973
2974         WARN_ON_ONCE(vmx->loaded_cpu_state != vmx->loaded_vmcs);
2975         host_state = &vmx->loaded_cpu_state->host_state;
2976
2977         ++vmx->vcpu.stat.host_state_reload;
2978         vmx->loaded_cpu_state = NULL;
2979
2980 #ifdef CONFIG_X86_64
2981         rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2982 #endif
2983         if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
2984                 kvm_load_ldt(host_state->ldt_sel);
2985 #ifdef CONFIG_X86_64
2986                 load_gs_index(host_state->gs_sel);
2987 #else
2988                 loadsegment(gs, host_state->gs_sel);
2989 #endif
2990         }
2991         if (host_state->fs_sel & 7)
2992                 loadsegment(fs, host_state->fs_sel);
2993 #ifdef CONFIG_X86_64
2994         if (unlikely(host_state->ds_sel | host_state->es_sel)) {
2995                 loadsegment(ds, host_state->ds_sel);
2996                 loadsegment(es, host_state->es_sel);
2997         }
2998 #endif
2999         invalidate_tss_limit();
3000 #ifdef CONFIG_X86_64
3001         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
3002 #endif
3003         load_fixmap_gdt(raw_smp_processor_id());
3004 }
3005
3006 #ifdef CONFIG_X86_64
3007 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
3008 {
3009         preempt_disable();
3010         if (vmx->loaded_cpu_state)
3011                 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
3012         preempt_enable();
3013         return vmx->msr_guest_kernel_gs_base;
3014 }
3015
3016 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
3017 {
3018         preempt_disable();
3019         if (vmx->loaded_cpu_state)
3020                 wrmsrl(MSR_KERNEL_GS_BASE, data);
3021         preempt_enable();
3022         vmx->msr_guest_kernel_gs_base = data;
3023 }
3024 #endif
3025
3026 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
3027 {
3028         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
3029         struct pi_desc old, new;
3030         unsigned int dest;
3031
3032         /*
3033          * In case of hot-plug or hot-unplug, we may have to undo
3034          * vmx_vcpu_pi_put even if there is no assigned device.  And we
3035          * always keep PI.NDST up to date for simplicity: it makes the
3036          * code easier, and CPU migration is not a fast path.
3037          */
3038         if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
3039                 return;
3040
3041         /*
3042          * First handle the simple case where no cmpxchg is necessary; just
3043          * allow posting non-urgent interrupts.
3044          *
3045          * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
3046          * PI.NDST: pi_post_block will do it for us and the wakeup_handler
3047          * expects the VCPU to be on the blocked_vcpu_list that matches
3048          * PI.NDST.
3049          */
3050         if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR ||
3051             vcpu->cpu == cpu) {
3052                 pi_clear_sn(pi_desc);
3053                 return;
3054         }
3055
3056         /* The full case.  */
3057         do {
3058                 old.control = new.control = pi_desc->control;
3059
3060                 dest = cpu_physical_id(cpu);
3061
3062                 if (x2apic_enabled())
3063                         new.ndst = dest;
3064                 else
3065                         new.ndst = (dest << 8) & 0xFF00;
3066
3067                 new.sn = 0;
3068         } while (cmpxchg64(&pi_desc->control, old.control,
3069                            new.control) != old.control);
3070 }
3071
3072 static void decache_tsc_multiplier(struct vcpu_vmx *vmx)
3073 {
3074         vmx->current_tsc_ratio = vmx->vcpu.arch.tsc_scaling_ratio;
3075         vmcs_write64(TSC_MULTIPLIER, vmx->current_tsc_ratio);
3076 }
3077
3078 /*
3079  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
3080  * vcpu mutex is already taken.
3081  */
3082 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3083 {
3084         struct vcpu_vmx *vmx = to_vmx(vcpu);
3085         bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
3086
3087         if (!already_loaded) {
3088                 loaded_vmcs_clear(vmx->loaded_vmcs);
3089                 local_irq_disable();
3090                 crash_disable_local_vmclear(cpu);
3091
3092                 /*
3093                  * Read loaded_vmcs->cpu should be before fetching
3094                  * loaded_vmcs->loaded_vmcss_on_cpu_link.
3095                  * See the comments in __loaded_vmcs_clear().
3096                  */
3097                 smp_rmb();
3098
3099                 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
3100                          &per_cpu(loaded_vmcss_on_cpu, cpu));
3101                 crash_enable_local_vmclear(cpu);
3102                 local_irq_enable();
3103         }
3104
3105         if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
3106                 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
3107                 vmcs_load(vmx->loaded_vmcs->vmcs);
3108                 indirect_branch_prediction_barrier();
3109         }
3110
3111         if (!already_loaded) {
3112                 void *gdt = get_current_gdt_ro();
3113                 unsigned long sysenter_esp;
3114
3115                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3116
3117                 /*
3118                  * Linux uses per-cpu TSS and GDT, so set these when switching
3119                  * processors.  See 22.2.4.
3120                  */
3121                 vmcs_writel(HOST_TR_BASE,
3122                             (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
3123                 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt);   /* 22.2.4 */
3124
3125                 /*
3126                  * VM exits change the host TR limit to 0x67 after a VM
3127                  * exit.  This is okay, since 0x67 covers everything except
3128                  * the IO bitmap and have have code to handle the IO bitmap
3129                  * being lost after a VM exit.
3130                  */
3131                 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
3132
3133                 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
3134                 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
3135
3136                 vmx->loaded_vmcs->cpu = cpu;
3137         }
3138
3139         /* Setup TSC multiplier */
3140         if (kvm_has_tsc_control &&
3141             vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
3142                 decache_tsc_multiplier(vmx);
3143
3144         vmx_vcpu_pi_load(vcpu, cpu);
3145         vmx->host_pkru = read_pkru();
3146         vmx->host_debugctlmsr = get_debugctlmsr();
3147 }
3148
3149 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
3150 {
3151         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
3152
3153         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
3154                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
3155                 !kvm_vcpu_apicv_active(vcpu))
3156                 return;
3157
3158         /* Set SN when the vCPU is preempted */
3159         if (vcpu->preempted)
3160                 pi_set_sn(pi_desc);
3161 }
3162
3163 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
3164 {
3165         vmx_vcpu_pi_put(vcpu);
3166
3167         vmx_prepare_switch_to_host(to_vmx(vcpu));
3168 }
3169
3170 static bool emulation_required(struct kvm_vcpu *vcpu)
3171 {
3172         return emulate_invalid_guest_state && !guest_state_valid(vcpu);
3173 }
3174
3175 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
3176
3177 /*
3178  * Return the cr0 value that a nested guest would read. This is a combination
3179  * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
3180  * its hypervisor (cr0_read_shadow).
3181  */
3182 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
3183 {
3184         return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
3185                 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
3186 }
3187 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
3188 {
3189         return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
3190                 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
3191 }
3192
3193 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
3194 {
3195         unsigned long rflags, save_rflags;
3196
3197         if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
3198                 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
3199                 rflags = vmcs_readl(GUEST_RFLAGS);
3200                 if (to_vmx(vcpu)->rmode.vm86_active) {
3201                         rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
3202                         save_rflags = to_vmx(vcpu)->rmode.save_rflags;
3203                         rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
3204                 }
3205                 to_vmx(vcpu)->rflags = rflags;
3206         }
3207         return to_vmx(vcpu)->rflags;
3208 }
3209
3210 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
3211 {
3212         unsigned long old_rflags = vmx_get_rflags(vcpu);
3213
3214         __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
3215         to_vmx(vcpu)->rflags = rflags;
3216         if (to_vmx(vcpu)->rmode.vm86_active) {
3217                 to_vmx(vcpu)->rmode.save_rflags = rflags;
3218                 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
3219         }
3220         vmcs_writel(GUEST_RFLAGS, rflags);
3221
3222         if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
3223                 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
3224 }
3225
3226 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
3227 {
3228         u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
3229         int ret = 0;
3230
3231         if (interruptibility & GUEST_INTR_STATE_STI)
3232                 ret |= KVM_X86_SHADOW_INT_STI;
3233         if (interruptibility & GUEST_INTR_STATE_MOV_SS)
3234                 ret |= KVM_X86_SHADOW_INT_MOV_SS;
3235
3236         return ret;
3237 }
3238
3239 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
3240 {
3241         u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
3242         u32 interruptibility = interruptibility_old;
3243
3244         interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
3245
3246         if (mask & KVM_X86_SHADOW_INT_MOV_SS)
3247                 interruptibility |= GUEST_INTR_STATE_MOV_SS;
3248         else if (mask & KVM_X86_SHADOW_INT_STI)
3249                 interruptibility |= GUEST_INTR_STATE_STI;
3250
3251         if ((interruptibility != interruptibility_old))
3252                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
3253 }
3254
3255 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
3256 {
3257         unsigned long rip;
3258
3259         rip = kvm_rip_read(vcpu);
3260         rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
3261         kvm_rip_write(vcpu, rip);
3262
3263         /* skipping an emulated instruction also counts */
3264         vmx_set_interrupt_shadow(vcpu, 0);
3265 }
3266
3267 static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
3268                                                unsigned long exit_qual)
3269 {
3270         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3271         unsigned int nr = vcpu->arch.exception.nr;
3272         u32 intr_info = nr | INTR_INFO_VALID_MASK;
3273
3274         if (vcpu->arch.exception.has_error_code) {
3275                 vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code;
3276                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
3277         }
3278
3279         if (kvm_exception_is_soft(nr))
3280                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
3281         else
3282                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
3283
3284         if (!(vmcs12->idt_vectoring_info_field & VECTORING_INFO_VALID_MASK) &&
3285             vmx_get_nmi_mask(vcpu))
3286                 intr_info |= INTR_INFO_UNBLOCK_NMI;
3287
3288         nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI, intr_info, exit_qual);
3289 }
3290
3291 /*
3292  * KVM wants to inject page-faults which it got to the guest. This function
3293  * checks whether in a nested guest, we need to inject them to L1 or L2.
3294  */
3295 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned long *exit_qual)
3296 {
3297         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3298         unsigned int nr = vcpu->arch.exception.nr;
3299         bool has_payload = vcpu->arch.exception.has_payload;
3300         unsigned long payload = vcpu->arch.exception.payload;
3301
3302         if (nr == PF_VECTOR) {
3303                 if (vcpu->arch.exception.nested_apf) {
3304                         *exit_qual = vcpu->arch.apf.nested_apf_token;
3305                         return 1;
3306                 }
3307                 if (nested_vmx_is_page_fault_vmexit(vmcs12,
3308                                                     vcpu->arch.exception.error_code)) {
3309                         *exit_qual = has_payload ? payload : vcpu->arch.cr2;
3310                         return 1;
3311                 }
3312         } else if (vmcs12->exception_bitmap & (1u << nr)) {
3313                 if (nr == DB_VECTOR) {
3314                         if (!has_payload) {
3315                                 payload = vcpu->arch.dr6;
3316                                 payload &= ~(DR6_FIXED_1 | DR6_BT);
3317                                 payload ^= DR6_RTM;
3318                         }
3319                         *exit_qual = payload;
3320                 } else
3321                         *exit_qual = 0;
3322                 return 1;
3323         }
3324
3325         return 0;
3326 }
3327
3328 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
3329 {
3330         /*
3331          * Ensure that we clear the HLT state in the VMCS.  We don't need to
3332          * explicitly skip the instruction because if the HLT state is set,
3333          * then the instruction is already executing and RIP has already been
3334          * advanced.
3335          */
3336         if (kvm_hlt_in_guest(vcpu->kvm) &&
3337                         vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
3338                 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
3339 }
3340
3341 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
3342 {
3343         struct vcpu_vmx *vmx = to_vmx(vcpu);
3344         unsigned nr = vcpu->arch.exception.nr;
3345         bool has_error_code = vcpu->arch.exception.has_error_code;
3346         u32 error_code = vcpu->arch.exception.error_code;
3347         u32 intr_info = nr | INTR_INFO_VALID_MASK;
3348
3349         kvm_deliver_exception_payload(vcpu);
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                                                  bool from_launch)
9343 {
9344         struct vcpu_vmx *vmx = to_vmx(vcpu);
9345         struct hv_vp_assist_page assist_page;
9346
9347         if (likely(!vmx->nested.enlightened_vmcs_enabled))
9348                 return 1;
9349
9350         if (unlikely(!kvm_hv_get_assist_page(vcpu, &assist_page)))
9351                 return 1;
9352
9353         if (unlikely(!assist_page.enlighten_vmentry))
9354                 return 1;
9355
9356         if (unlikely(assist_page.current_nested_vmcs !=
9357                      vmx->nested.hv_evmcs_vmptr)) {
9358
9359                 if (!vmx->nested.hv_evmcs)
9360                         vmx->nested.current_vmptr = -1ull;
9361
9362                 nested_release_evmcs(vcpu);
9363
9364                 vmx->nested.hv_evmcs_page = kvm_vcpu_gpa_to_page(
9365                         vcpu, assist_page.current_nested_vmcs);
9366
9367                 if (unlikely(is_error_page(vmx->nested.hv_evmcs_page)))
9368                         return 0;
9369
9370                 vmx->nested.hv_evmcs = kmap(vmx->nested.hv_evmcs_page);
9371
9372                 if (vmx->nested.hv_evmcs->revision_id != VMCS12_REVISION) {
9373                         nested_release_evmcs(vcpu);
9374                         return 0;
9375                 }
9376
9377                 vmx->nested.dirty_vmcs12 = true;
9378                 /*
9379                  * As we keep L2 state for one guest only 'hv_clean_fields' mask
9380                  * can't be used when we switch between them. Reset it here for
9381                  * simplicity.
9382                  */
9383                 vmx->nested.hv_evmcs->hv_clean_fields &=
9384                         ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
9385                 vmx->nested.hv_evmcs_vmptr = assist_page.current_nested_vmcs;
9386
9387                 /*
9388                  * Unlike normal vmcs12, enlightened vmcs12 is not fully
9389                  * reloaded from guest's memory (read only fields, fields not
9390                  * present in struct hv_enlightened_vmcs, ...). Make sure there
9391                  * are no leftovers.
9392                  */
9393                 if (from_launch)
9394                         memset(vmx->nested.cached_vmcs12, 0,
9395                                sizeof(*vmx->nested.cached_vmcs12));
9396
9397         }
9398         return 1;
9399 }
9400
9401 /* Emulate the VMPTRST instruction */
9402 static int handle_vmptrst(struct kvm_vcpu *vcpu)
9403 {
9404         unsigned long exit_qual = vmcs_readl(EXIT_QUALIFICATION);
9405         u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9406         gpa_t current_vmptr = to_vmx(vcpu)->nested.current_vmptr;
9407         struct x86_exception e;
9408         gva_t gva;
9409
9410         if (!nested_vmx_check_permission(vcpu))
9411                 return 1;
9412
9413         if (unlikely(to_vmx(vcpu)->nested.hv_evmcs))
9414                 return 1;
9415
9416         if (get_vmx_mem_address(vcpu, exit_qual, instr_info, true, &gva))
9417                 return 1;
9418         /* *_system ok, nested_vmx_check_permission has verified cpl=0 */
9419         if (kvm_write_guest_virt_system(vcpu, gva, (void *)&current_vmptr,
9420                                         sizeof(gpa_t), &e)) {
9421                 kvm_inject_page_fault(vcpu, &e);
9422                 return 1;
9423         }
9424         return nested_vmx_succeed(vcpu);
9425 }
9426
9427 /* Emulate the INVEPT instruction */
9428 static int handle_invept(struct kvm_vcpu *vcpu)
9429 {
9430         struct vcpu_vmx *vmx = to_vmx(vcpu);
9431         u32 vmx_instruction_info, types;
9432         unsigned long type;
9433         gva_t gva;
9434         struct x86_exception e;
9435         struct {
9436                 u64 eptp, gpa;
9437         } operand;
9438
9439         if (!(vmx->nested.msrs.secondary_ctls_high &
9440               SECONDARY_EXEC_ENABLE_EPT) ||
9441             !(vmx->nested.msrs.ept_caps & VMX_EPT_INVEPT_BIT)) {
9442                 kvm_queue_exception(vcpu, UD_VECTOR);
9443                 return 1;
9444         }
9445
9446         if (!nested_vmx_check_permission(vcpu))
9447                 return 1;
9448
9449         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9450         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9451
9452         types = (vmx->nested.msrs.ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
9453
9454         if (type >= 32 || !(types & (1 << type)))
9455                 return nested_vmx_failValid(vcpu,
9456                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9457
9458         /* According to the Intel VMX instruction reference, the memory
9459          * operand is read even if it isn't needed (e.g., for type==global)
9460          */
9461         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9462                         vmx_instruction_info, false, &gva))
9463                 return 1;
9464         if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9465                 kvm_inject_page_fault(vcpu, &e);
9466                 return 1;
9467         }
9468
9469         switch (type) {
9470         case VMX_EPT_EXTENT_GLOBAL:
9471         /*
9472          * TODO: track mappings and invalidate
9473          * single context requests appropriately
9474          */
9475         case VMX_EPT_EXTENT_CONTEXT:
9476                 kvm_mmu_sync_roots(vcpu);
9477                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
9478                 break;
9479         default:
9480                 BUG_ON(1);
9481                 break;
9482         }
9483
9484         return nested_vmx_succeed(vcpu);
9485 }
9486
9487 static u16 nested_get_vpid02(struct kvm_vcpu *vcpu)
9488 {
9489         struct vcpu_vmx *vmx = to_vmx(vcpu);
9490
9491         return vmx->nested.vpid02 ? vmx->nested.vpid02 : vmx->vpid;
9492 }
9493
9494 static int handle_invvpid(struct kvm_vcpu *vcpu)
9495 {
9496         struct vcpu_vmx *vmx = to_vmx(vcpu);
9497         u32 vmx_instruction_info;
9498         unsigned long type, types;
9499         gva_t gva;
9500         struct x86_exception e;
9501         struct {
9502                 u64 vpid;
9503                 u64 gla;
9504         } operand;
9505         u16 vpid02;
9506
9507         if (!(vmx->nested.msrs.secondary_ctls_high &
9508               SECONDARY_EXEC_ENABLE_VPID) ||
9509                         !(vmx->nested.msrs.vpid_caps & VMX_VPID_INVVPID_BIT)) {
9510                 kvm_queue_exception(vcpu, UD_VECTOR);
9511                 return 1;
9512         }
9513
9514         if (!nested_vmx_check_permission(vcpu))
9515                 return 1;
9516
9517         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9518         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9519
9520         types = (vmx->nested.msrs.vpid_caps &
9521                         VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
9522
9523         if (type >= 32 || !(types & (1 << type)))
9524                 return nested_vmx_failValid(vcpu,
9525                         VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9526
9527         /* according to the intel vmx instruction reference, the memory
9528          * operand is read even if it isn't needed (e.g., for type==global)
9529          */
9530         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9531                         vmx_instruction_info, false, &gva))
9532                 return 1;
9533         if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9534                 kvm_inject_page_fault(vcpu, &e);
9535                 return 1;
9536         }
9537         if (operand.vpid >> 16)
9538                 return nested_vmx_failValid(vcpu,
9539                         VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9540
9541         vpid02 = nested_get_vpid02(vcpu);
9542         switch (type) {
9543         case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
9544                 if (!operand.vpid ||
9545                     is_noncanonical_address(operand.gla, vcpu))
9546                         return nested_vmx_failValid(vcpu,
9547                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9548                 if (cpu_has_vmx_invvpid_individual_addr()) {
9549                         __invvpid(VMX_VPID_EXTENT_INDIVIDUAL_ADDR,
9550                                 vpid02, operand.gla);
9551                 } else
9552                         __vmx_flush_tlb(vcpu, vpid02, false);
9553                 break;
9554         case VMX_VPID_EXTENT_SINGLE_CONTEXT:
9555         case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
9556                 if (!operand.vpid)
9557                         return nested_vmx_failValid(vcpu,
9558                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9559                 __vmx_flush_tlb(vcpu, vpid02, false);
9560                 break;
9561         case VMX_VPID_EXTENT_ALL_CONTEXT:
9562                 __vmx_flush_tlb(vcpu, vpid02, false);
9563                 break;
9564         default:
9565                 WARN_ON_ONCE(1);
9566                 return kvm_skip_emulated_instruction(vcpu);
9567         }
9568
9569         return nested_vmx_succeed(vcpu);
9570 }
9571
9572 static int handle_invpcid(struct kvm_vcpu *vcpu)
9573 {
9574         u32 vmx_instruction_info;
9575         unsigned long type;
9576         bool pcid_enabled;
9577         gva_t gva;
9578         struct x86_exception e;
9579         unsigned i;
9580         unsigned long roots_to_free = 0;
9581         struct {
9582                 u64 pcid;
9583                 u64 gla;
9584         } operand;
9585
9586         if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
9587                 kvm_queue_exception(vcpu, UD_VECTOR);
9588                 return 1;
9589         }
9590
9591         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9592         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9593
9594         if (type > 3) {
9595                 kvm_inject_gp(vcpu, 0);
9596                 return 1;
9597         }
9598
9599         /* According to the Intel instruction reference, the memory operand
9600          * is read even if it isn't needed (e.g., for type==all)
9601          */
9602         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9603                                 vmx_instruction_info, false, &gva))
9604                 return 1;
9605
9606         if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9607                 kvm_inject_page_fault(vcpu, &e);
9608                 return 1;
9609         }
9610
9611         if (operand.pcid >> 12 != 0) {
9612                 kvm_inject_gp(vcpu, 0);
9613                 return 1;
9614         }
9615
9616         pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
9617
9618         switch (type) {
9619         case INVPCID_TYPE_INDIV_ADDR:
9620                 if ((!pcid_enabled && (operand.pcid != 0)) ||
9621                     is_noncanonical_address(operand.gla, vcpu)) {
9622                         kvm_inject_gp(vcpu, 0);
9623                         return 1;
9624                 }
9625                 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
9626                 return kvm_skip_emulated_instruction(vcpu);
9627
9628         case INVPCID_TYPE_SINGLE_CTXT:
9629                 if (!pcid_enabled && (operand.pcid != 0)) {
9630                         kvm_inject_gp(vcpu, 0);
9631                         return 1;
9632                 }
9633
9634                 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
9635                         kvm_mmu_sync_roots(vcpu);
9636                         kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
9637                 }
9638
9639                 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
9640                         if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].cr3)
9641                             == operand.pcid)
9642                                 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
9643
9644                 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
9645                 /*
9646                  * If neither the current cr3 nor any of the prev_roots use the
9647                  * given PCID, then nothing needs to be done here because a
9648                  * resync will happen anyway before switching to any other CR3.
9649                  */
9650
9651                 return kvm_skip_emulated_instruction(vcpu);
9652
9653         case INVPCID_TYPE_ALL_NON_GLOBAL:
9654                 /*
9655                  * Currently, KVM doesn't mark global entries in the shadow
9656                  * page tables, so a non-global flush just degenerates to a
9657                  * global flush. If needed, we could optimize this later by
9658                  * keeping track of global entries in shadow page tables.
9659                  */
9660
9661                 /* fall-through */
9662         case INVPCID_TYPE_ALL_INCL_GLOBAL:
9663                 kvm_mmu_unload(vcpu);
9664                 return kvm_skip_emulated_instruction(vcpu);
9665
9666         default:
9667                 BUG(); /* We have already checked above that type <= 3 */
9668         }
9669 }
9670
9671 static int handle_pml_full(struct kvm_vcpu *vcpu)
9672 {
9673         unsigned long exit_qualification;
9674
9675         trace_kvm_pml_full(vcpu->vcpu_id);
9676
9677         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9678
9679         /*
9680          * PML buffer FULL happened while executing iret from NMI,
9681          * "blocked by NMI" bit has to be set before next VM entry.
9682          */
9683         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
9684                         enable_vnmi &&
9685                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
9686                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
9687                                 GUEST_INTR_STATE_NMI);
9688
9689         /*
9690          * PML buffer already flushed at beginning of VMEXIT. Nothing to do
9691          * here.., and there's no userspace involvement needed for PML.
9692          */
9693         return 1;
9694 }
9695
9696 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
9697 {
9698         if (!to_vmx(vcpu)->req_immediate_exit)
9699                 kvm_lapic_expired_hv_timer(vcpu);
9700         return 1;
9701 }
9702
9703 static bool valid_ept_address(struct kvm_vcpu *vcpu, u64 address)
9704 {
9705         struct vcpu_vmx *vmx = to_vmx(vcpu);
9706         int maxphyaddr = cpuid_maxphyaddr(vcpu);
9707
9708         /* Check for memory type validity */
9709         switch (address & VMX_EPTP_MT_MASK) {
9710         case VMX_EPTP_MT_UC:
9711                 if (!(vmx->nested.msrs.ept_caps & VMX_EPTP_UC_BIT))
9712                         return false;
9713                 break;
9714         case VMX_EPTP_MT_WB:
9715                 if (!(vmx->nested.msrs.ept_caps & VMX_EPTP_WB_BIT))
9716                         return false;
9717                 break;
9718         default:
9719                 return false;
9720         }
9721
9722         /* only 4 levels page-walk length are valid */
9723         if ((address & VMX_EPTP_PWL_MASK) != VMX_EPTP_PWL_4)
9724                 return false;
9725
9726         /* Reserved bits should not be set */
9727         if (address >> maxphyaddr || ((address >> 7) & 0x1f))
9728                 return false;
9729
9730         /* AD, if set, should be supported */
9731         if (address & VMX_EPTP_AD_ENABLE_BIT) {
9732                 if (!(vmx->nested.msrs.ept_caps & VMX_EPT_AD_BIT))
9733                         return false;
9734         }
9735
9736         return true;
9737 }
9738
9739 static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
9740                                      struct vmcs12 *vmcs12)
9741 {
9742         u32 index = vcpu->arch.regs[VCPU_REGS_RCX];
9743         u64 address;
9744         bool accessed_dirty;
9745         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
9746
9747         if (!nested_cpu_has_eptp_switching(vmcs12) ||
9748             !nested_cpu_has_ept(vmcs12))
9749                 return 1;
9750
9751         if (index >= VMFUNC_EPTP_ENTRIES)
9752                 return 1;
9753
9754
9755         if (kvm_vcpu_read_guest_page(vcpu, vmcs12->eptp_list_address >> PAGE_SHIFT,
9756                                      &address, index * 8, 8))
9757                 return 1;
9758
9759         accessed_dirty = !!(address & VMX_EPTP_AD_ENABLE_BIT);
9760
9761         /*
9762          * If the (L2) guest does a vmfunc to the currently
9763          * active ept pointer, we don't have to do anything else
9764          */
9765         if (vmcs12->ept_pointer != address) {
9766                 if (!valid_ept_address(vcpu, address))
9767                         return 1;
9768
9769                 kvm_mmu_unload(vcpu);
9770                 mmu->ept_ad = accessed_dirty;
9771                 mmu->mmu_role.base.ad_disabled = !accessed_dirty;
9772                 vmcs12->ept_pointer = address;
9773                 /*
9774                  * TODO: Check what's the correct approach in case
9775                  * mmu reload fails. Currently, we just let the next
9776                  * reload potentially fail
9777                  */
9778                 kvm_mmu_reload(vcpu);
9779         }
9780
9781         return 0;
9782 }
9783
9784 static int handle_vmfunc(struct kvm_vcpu *vcpu)
9785 {
9786         struct vcpu_vmx *vmx = to_vmx(vcpu);
9787         struct vmcs12 *vmcs12;
9788         u32 function = vcpu->arch.regs[VCPU_REGS_RAX];
9789
9790         /*
9791          * VMFUNC is only supported for nested guests, but we always enable the
9792          * secondary control for simplicity; for non-nested mode, fake that we
9793          * didn't by injecting #UD.
9794          */
9795         if (!is_guest_mode(vcpu)) {
9796                 kvm_queue_exception(vcpu, UD_VECTOR);
9797                 return 1;
9798         }
9799
9800         vmcs12 = get_vmcs12(vcpu);
9801         if ((vmcs12->vm_function_control & (1 << function)) == 0)
9802                 goto fail;
9803
9804         switch (function) {
9805         case 0:
9806                 if (nested_vmx_eptp_switching(vcpu, vmcs12))
9807                         goto fail;
9808                 break;
9809         default:
9810                 goto fail;
9811         }
9812         return kvm_skip_emulated_instruction(vcpu);
9813
9814 fail:
9815         nested_vmx_vmexit(vcpu, vmx->exit_reason,
9816                           vmcs_read32(VM_EXIT_INTR_INFO),
9817                           vmcs_readl(EXIT_QUALIFICATION));
9818         return 1;
9819 }
9820
9821 static int handle_encls(struct kvm_vcpu *vcpu)
9822 {
9823         /*
9824          * SGX virtualization is not yet supported.  There is no software
9825          * enable bit for SGX, so we have to trap ENCLS and inject a #UD
9826          * to prevent the guest from executing ENCLS.
9827          */
9828         kvm_queue_exception(vcpu, UD_VECTOR);
9829         return 1;
9830 }
9831
9832 /*
9833  * The exit handlers return 1 if the exit was handled fully and guest execution
9834  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
9835  * to be done to userspace and return 0.
9836  */
9837 static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
9838         [EXIT_REASON_EXCEPTION_NMI]           = handle_exception,
9839         [EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
9840         [EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
9841         [EXIT_REASON_NMI_WINDOW]              = handle_nmi_window,
9842         [EXIT_REASON_IO_INSTRUCTION]          = handle_io,
9843         [EXIT_REASON_CR_ACCESS]               = handle_cr,
9844         [EXIT_REASON_DR_ACCESS]               = handle_dr,
9845         [EXIT_REASON_CPUID]                   = handle_cpuid,
9846         [EXIT_REASON_MSR_READ]                = handle_rdmsr,
9847         [EXIT_REASON_MSR_WRITE]               = handle_wrmsr,
9848         [EXIT_REASON_PENDING_INTERRUPT]       = handle_interrupt_window,
9849         [EXIT_REASON_HLT]                     = handle_halt,
9850         [EXIT_REASON_INVD]                    = handle_invd,
9851         [EXIT_REASON_INVLPG]                  = handle_invlpg,
9852         [EXIT_REASON_RDPMC]                   = handle_rdpmc,
9853         [EXIT_REASON_VMCALL]                  = handle_vmcall,
9854         [EXIT_REASON_VMCLEAR]                 = handle_vmclear,
9855         [EXIT_REASON_VMLAUNCH]                = handle_vmlaunch,
9856         [EXIT_REASON_VMPTRLD]                 = handle_vmptrld,
9857         [EXIT_REASON_VMPTRST]                 = handle_vmptrst,
9858         [EXIT_REASON_VMREAD]                  = handle_vmread,
9859         [EXIT_REASON_VMRESUME]                = handle_vmresume,
9860         [EXIT_REASON_VMWRITE]                 = handle_vmwrite,
9861         [EXIT_REASON_VMOFF]                   = handle_vmoff,
9862         [EXIT_REASON_VMON]                    = handle_vmon,
9863         [EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
9864         [EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
9865         [EXIT_REASON_APIC_WRITE]              = handle_apic_write,
9866         [EXIT_REASON_EOI_INDUCED]             = handle_apic_eoi_induced,
9867         [EXIT_REASON_WBINVD]                  = handle_wbinvd,
9868         [EXIT_REASON_XSETBV]                  = handle_xsetbv,
9869         [EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
9870         [EXIT_REASON_MCE_DURING_VMENTRY]      = handle_machine_check,
9871         [EXIT_REASON_GDTR_IDTR]               = handle_desc,
9872         [EXIT_REASON_LDTR_TR]                 = handle_desc,
9873         [EXIT_REASON_EPT_VIOLATION]           = handle_ept_violation,
9874         [EXIT_REASON_EPT_MISCONFIG]           = handle_ept_misconfig,
9875         [EXIT_REASON_PAUSE_INSTRUCTION]       = handle_pause,
9876         [EXIT_REASON_MWAIT_INSTRUCTION]       = handle_mwait,
9877         [EXIT_REASON_MONITOR_TRAP_FLAG]       = handle_monitor_trap,
9878         [EXIT_REASON_MONITOR_INSTRUCTION]     = handle_monitor,
9879         [EXIT_REASON_INVEPT]                  = handle_invept,
9880         [EXIT_REASON_INVVPID]                 = handle_invvpid,
9881         [EXIT_REASON_RDRAND]                  = handle_invalid_op,
9882         [EXIT_REASON_RDSEED]                  = handle_invalid_op,
9883         [EXIT_REASON_XSAVES]                  = handle_xsaves,
9884         [EXIT_REASON_XRSTORS]                 = handle_xrstors,
9885         [EXIT_REASON_PML_FULL]                = handle_pml_full,
9886         [EXIT_REASON_INVPCID]                 = handle_invpcid,
9887         [EXIT_REASON_VMFUNC]                  = handle_vmfunc,
9888         [EXIT_REASON_PREEMPTION_TIMER]        = handle_preemption_timer,
9889         [EXIT_REASON_ENCLS]                   = handle_encls,
9890 };
9891
9892 static const int kvm_vmx_max_exit_handlers =
9893         ARRAY_SIZE(kvm_vmx_exit_handlers);
9894
9895 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
9896                                        struct vmcs12 *vmcs12)
9897 {
9898         unsigned long exit_qualification;
9899         gpa_t bitmap, last_bitmap;
9900         unsigned int port;
9901         int size;
9902         u8 b;
9903
9904         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
9905                 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
9906
9907         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9908
9909         port = exit_qualification >> 16;
9910         size = (exit_qualification & 7) + 1;
9911
9912         last_bitmap = (gpa_t)-1;
9913         b = -1;
9914
9915         while (size > 0) {
9916                 if (port < 0x8000)
9917                         bitmap = vmcs12->io_bitmap_a;
9918                 else if (port < 0x10000)
9919                         bitmap = vmcs12->io_bitmap_b;
9920                 else
9921                         return true;
9922                 bitmap += (port & 0x7fff) / 8;
9923
9924                 if (last_bitmap != bitmap)
9925                         if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
9926                                 return true;
9927                 if (b & (1 << (port & 7)))
9928                         return true;
9929
9930                 port++;
9931                 size--;
9932                 last_bitmap = bitmap;
9933         }
9934
9935         return false;
9936 }
9937
9938 /*
9939  * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
9940  * rather than handle it ourselves in L0. I.e., check whether L1 expressed
9941  * disinterest in the current event (read or write a specific MSR) by using an
9942  * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
9943  */
9944 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
9945         struct vmcs12 *vmcs12, u32 exit_reason)
9946 {
9947         u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
9948         gpa_t bitmap;
9949
9950         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
9951                 return true;
9952
9953         /*
9954          * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
9955          * for the four combinations of read/write and low/high MSR numbers.
9956          * First we need to figure out which of the four to use:
9957          */
9958         bitmap = vmcs12->msr_bitmap;
9959         if (exit_reason == EXIT_REASON_MSR_WRITE)
9960                 bitmap += 2048;
9961         if (msr_index >= 0xc0000000) {
9962                 msr_index -= 0xc0000000;
9963                 bitmap += 1024;
9964         }
9965
9966         /* Then read the msr_index'th bit from this bitmap: */
9967         if (msr_index < 1024*8) {
9968                 unsigned char b;
9969                 if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
9970                         return true;
9971                 return 1 & (b >> (msr_index & 7));
9972         } else
9973                 return true; /* let L1 handle the wrong parameter */
9974 }
9975
9976 /*
9977  * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
9978  * rather than handle it ourselves in L0. I.e., check if L1 wanted to
9979  * intercept (via guest_host_mask etc.) the current event.
9980  */
9981 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
9982         struct vmcs12 *vmcs12)
9983 {
9984         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9985         int cr = exit_qualification & 15;
9986         int reg;
9987         unsigned long val;
9988
9989         switch ((exit_qualification >> 4) & 3) {
9990         case 0: /* mov to cr */
9991                 reg = (exit_qualification >> 8) & 15;
9992                 val = kvm_register_readl(vcpu, reg);
9993                 switch (cr) {
9994                 case 0:
9995                         if (vmcs12->cr0_guest_host_mask &
9996                             (val ^ vmcs12->cr0_read_shadow))
9997                                 return true;
9998                         break;
9999                 case 3:
10000                         if ((vmcs12->cr3_target_count >= 1 &&
10001                                         vmcs12->cr3_target_value0 == val) ||
10002                                 (vmcs12->cr3_target_count >= 2 &&
10003                                         vmcs12->cr3_target_value1 == val) ||
10004                                 (vmcs12->cr3_target_count >= 3 &&
10005                                         vmcs12->cr3_target_value2 == val) ||
10006                                 (vmcs12->cr3_target_count >= 4 &&
10007                                         vmcs12->cr3_target_value3 == val))
10008                                 return false;
10009                         if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
10010                                 return true;
10011                         break;
10012                 case 4:
10013                         if (vmcs12->cr4_guest_host_mask &
10014                             (vmcs12->cr4_read_shadow ^ val))
10015                                 return true;
10016                         break;
10017                 case 8:
10018                         if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
10019                                 return true;
10020                         break;
10021                 }
10022                 break;
10023         case 2: /* clts */
10024                 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
10025                     (vmcs12->cr0_read_shadow & X86_CR0_TS))
10026                         return true;
10027                 break;
10028         case 1: /* mov from cr */
10029                 switch (cr) {
10030                 case 3:
10031                         if (vmcs12->cpu_based_vm_exec_control &
10032                             CPU_BASED_CR3_STORE_EXITING)
10033                                 return true;
10034                         break;
10035                 case 8:
10036                         if (vmcs12->cpu_based_vm_exec_control &
10037                             CPU_BASED_CR8_STORE_EXITING)
10038                                 return true;
10039                         break;
10040                 }
10041                 break;
10042         case 3: /* lmsw */
10043                 /*
10044                  * lmsw can change bits 1..3 of cr0, and only set bit 0 of
10045                  * cr0. Other attempted changes are ignored, with no exit.
10046                  */
10047                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
10048                 if (vmcs12->cr0_guest_host_mask & 0xe &
10049                     (val ^ vmcs12->cr0_read_shadow))
10050                         return true;
10051                 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
10052                     !(vmcs12->cr0_read_shadow & 0x1) &&
10053                     (val & 0x1))
10054                         return true;
10055                 break;
10056         }
10057         return false;
10058 }
10059
10060 static bool nested_vmx_exit_handled_vmcs_access(struct kvm_vcpu *vcpu,
10061         struct vmcs12 *vmcs12, gpa_t bitmap)
10062 {
10063         u32 vmx_instruction_info;
10064         unsigned long field;
10065         u8 b;
10066
10067         if (!nested_cpu_has_shadow_vmcs(vmcs12))
10068                 return true;
10069
10070         /* Decode instruction info and find the field to access */
10071         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
10072         field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
10073
10074         /* Out-of-range fields always cause a VM exit from L2 to L1 */
10075         if (field >> 15)
10076                 return true;
10077
10078         if (kvm_vcpu_read_guest(vcpu, bitmap + field/8, &b, 1))
10079                 return true;
10080
10081         return 1 & (b >> (field & 7));
10082 }
10083
10084 /*
10085  * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
10086  * should handle it ourselves in L0 (and then continue L2). Only call this
10087  * when in is_guest_mode (L2).
10088  */
10089 static bool nested_vmx_exit_reflected(struct kvm_vcpu *vcpu, u32 exit_reason)
10090 {
10091         u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10092         struct vcpu_vmx *vmx = to_vmx(vcpu);
10093         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10094
10095         if (vmx->nested.nested_run_pending)
10096                 return false;
10097
10098         if (unlikely(vmx->fail)) {
10099                 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
10100                                     vmcs_read32(VM_INSTRUCTION_ERROR));
10101                 return true;
10102         }
10103
10104         /*
10105          * The host physical addresses of some pages of guest memory
10106          * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
10107          * Page). The CPU may write to these pages via their host
10108          * physical address while L2 is running, bypassing any
10109          * address-translation-based dirty tracking (e.g. EPT write
10110          * protection).
10111          *
10112          * Mark them dirty on every exit from L2 to prevent them from
10113          * getting out of sync with dirty tracking.
10114          */
10115         nested_mark_vmcs12_pages_dirty(vcpu);
10116
10117         trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
10118                                 vmcs_readl(EXIT_QUALIFICATION),
10119                                 vmx->idt_vectoring_info,
10120                                 intr_info,
10121                                 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
10122                                 KVM_ISA_VMX);
10123
10124         switch (exit_reason) {
10125         case EXIT_REASON_EXCEPTION_NMI:
10126                 if (is_nmi(intr_info))
10127                         return false;
10128                 else if (is_page_fault(intr_info))
10129                         return !vmx->vcpu.arch.apf.host_apf_reason && enable_ept;
10130                 else if (is_debug(intr_info) &&
10131                          vcpu->guest_debug &
10132                          (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
10133                         return false;
10134                 else if (is_breakpoint(intr_info) &&
10135                          vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
10136                         return false;
10137                 return vmcs12->exception_bitmap &
10138                                 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
10139         case EXIT_REASON_EXTERNAL_INTERRUPT:
10140                 return false;
10141         case EXIT_REASON_TRIPLE_FAULT:
10142                 return true;
10143         case EXIT_REASON_PENDING_INTERRUPT:
10144                 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
10145         case EXIT_REASON_NMI_WINDOW:
10146                 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
10147         case EXIT_REASON_TASK_SWITCH:
10148                 return true;
10149         case EXIT_REASON_CPUID:
10150                 return true;
10151         case EXIT_REASON_HLT:
10152                 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
10153         case EXIT_REASON_INVD:
10154                 return true;
10155         case EXIT_REASON_INVLPG:
10156                 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
10157         case EXIT_REASON_RDPMC:
10158                 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
10159         case EXIT_REASON_RDRAND:
10160                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDRAND_EXITING);
10161         case EXIT_REASON_RDSEED:
10162                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDSEED_EXITING);
10163         case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
10164                 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
10165         case EXIT_REASON_VMREAD:
10166                 return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
10167                         vmcs12->vmread_bitmap);
10168         case EXIT_REASON_VMWRITE:
10169                 return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
10170                         vmcs12->vmwrite_bitmap);
10171         case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
10172         case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
10173         case EXIT_REASON_VMPTRST: case EXIT_REASON_VMRESUME:
10174         case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
10175         case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
10176                 /*
10177                  * VMX instructions trap unconditionally. This allows L1 to
10178                  * emulate them for its L2 guest, i.e., allows 3-level nesting!
10179                  */
10180                 return true;
10181         case EXIT_REASON_CR_ACCESS:
10182                 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
10183         case EXIT_REASON_DR_ACCESS:
10184                 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
10185         case EXIT_REASON_IO_INSTRUCTION:
10186                 return nested_vmx_exit_handled_io(vcpu, vmcs12);
10187         case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
10188                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
10189         case EXIT_REASON_MSR_READ:
10190         case EXIT_REASON_MSR_WRITE:
10191                 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
10192         case EXIT_REASON_INVALID_STATE:
10193                 return true;
10194         case EXIT_REASON_MWAIT_INSTRUCTION:
10195                 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
10196         case EXIT_REASON_MONITOR_TRAP_FLAG:
10197                 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG);
10198         case EXIT_REASON_MONITOR_INSTRUCTION:
10199                 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
10200         case EXIT_REASON_PAUSE_INSTRUCTION:
10201                 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
10202                         nested_cpu_has2(vmcs12,
10203                                 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
10204         case EXIT_REASON_MCE_DURING_VMENTRY:
10205                 return false;
10206         case EXIT_REASON_TPR_BELOW_THRESHOLD:
10207                 return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
10208         case EXIT_REASON_APIC_ACCESS:
10209         case EXIT_REASON_APIC_WRITE:
10210         case EXIT_REASON_EOI_INDUCED:
10211                 /*
10212                  * The controls for "virtualize APIC accesses," "APIC-
10213                  * register virtualization," and "virtual-interrupt
10214                  * delivery" only come from vmcs12.
10215                  */
10216                 return true;
10217         case EXIT_REASON_EPT_VIOLATION:
10218                 /*
10219                  * L0 always deals with the EPT violation. If nested EPT is
10220                  * used, and the nested mmu code discovers that the address is
10221                  * missing in the guest EPT table (EPT12), the EPT violation
10222                  * will be injected with nested_ept_inject_page_fault()
10223                  */
10224                 return false;
10225         case EXIT_REASON_EPT_MISCONFIG:
10226                 /*
10227                  * L2 never uses directly L1's EPT, but rather L0's own EPT
10228                  * table (shadow on EPT) or a merged EPT table that L0 built
10229                  * (EPT on EPT). So any problems with the structure of the
10230                  * table is L0's fault.
10231                  */
10232                 return false;
10233         case EXIT_REASON_INVPCID:
10234                 return
10235                         nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_INVPCID) &&
10236                         nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
10237         case EXIT_REASON_WBINVD:
10238                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
10239         case EXIT_REASON_XSETBV:
10240                 return true;
10241         case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
10242                 /*
10243                  * This should never happen, since it is not possible to
10244                  * set XSS to a non-zero value---neither in L1 nor in L2.
10245                  * If if it were, XSS would have to be checked against
10246                  * the XSS exit bitmap in vmcs12.
10247                  */
10248                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
10249         case EXIT_REASON_PREEMPTION_TIMER:
10250                 return false;
10251         case EXIT_REASON_PML_FULL:
10252                 /* We emulate PML support to L1. */
10253                 return false;
10254         case EXIT_REASON_VMFUNC:
10255                 /* VM functions are emulated through L2->L0 vmexits. */
10256                 return false;
10257         case EXIT_REASON_ENCLS:
10258                 /* SGX is never exposed to L1 */
10259                 return false;
10260         default:
10261                 return true;
10262         }
10263 }
10264
10265 static int nested_vmx_reflect_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason)
10266 {
10267         u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10268
10269         /*
10270          * At this point, the exit interruption info in exit_intr_info
10271          * is only valid for EXCEPTION_NMI exits.  For EXTERNAL_INTERRUPT
10272          * we need to query the in-kernel LAPIC.
10273          */
10274         WARN_ON(exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT);
10275         if ((exit_intr_info &
10276              (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
10277             (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) {
10278                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10279                 vmcs12->vm_exit_intr_error_code =
10280                         vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
10281         }
10282
10283         nested_vmx_vmexit(vcpu, exit_reason, exit_intr_info,
10284                           vmcs_readl(EXIT_QUALIFICATION));
10285         return 1;
10286 }
10287
10288 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
10289 {
10290         *info1 = vmcs_readl(EXIT_QUALIFICATION);
10291         *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
10292 }
10293
10294 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
10295 {
10296         if (vmx->pml_pg) {
10297                 __free_page(vmx->pml_pg);
10298                 vmx->pml_pg = NULL;
10299         }
10300 }
10301
10302 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
10303 {
10304         struct vcpu_vmx *vmx = to_vmx(vcpu);
10305         u64 *pml_buf;
10306         u16 pml_idx;
10307
10308         pml_idx = vmcs_read16(GUEST_PML_INDEX);
10309
10310         /* Do nothing if PML buffer is empty */
10311         if (pml_idx == (PML_ENTITY_NUM - 1))
10312                 return;
10313
10314         /* PML index always points to next available PML buffer entity */
10315         if (pml_idx >= PML_ENTITY_NUM)
10316                 pml_idx = 0;
10317         else
10318                 pml_idx++;
10319
10320         pml_buf = page_address(vmx->pml_pg);
10321         for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
10322                 u64 gpa;
10323
10324                 gpa = pml_buf[pml_idx];
10325                 WARN_ON(gpa & (PAGE_SIZE - 1));
10326                 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
10327         }
10328
10329         /* reset PML index */
10330         vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
10331 }
10332
10333 /*
10334  * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
10335  * Called before reporting dirty_bitmap to userspace.
10336  */
10337 static void kvm_flush_pml_buffers(struct kvm *kvm)
10338 {
10339         int i;
10340         struct kvm_vcpu *vcpu;
10341         /*
10342          * We only need to kick vcpu out of guest mode here, as PML buffer
10343          * is flushed at beginning of all VMEXITs, and it's obvious that only
10344          * vcpus running in guest are possible to have unflushed GPAs in PML
10345          * buffer.
10346          */
10347         kvm_for_each_vcpu(i, vcpu, kvm)
10348                 kvm_vcpu_kick(vcpu);
10349 }
10350
10351 static void vmx_dump_sel(char *name, uint32_t sel)
10352 {
10353         pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
10354                name, vmcs_read16(sel),
10355                vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
10356                vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
10357                vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
10358 }
10359
10360 static void vmx_dump_dtsel(char *name, uint32_t limit)
10361 {
10362         pr_err("%s                           limit=0x%08x, base=0x%016lx\n",
10363                name, vmcs_read32(limit),
10364                vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
10365 }
10366
10367 static void dump_vmcs(void)
10368 {
10369         u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
10370         u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
10371         u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
10372         u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
10373         u32 secondary_exec_control = 0;
10374         unsigned long cr4 = vmcs_readl(GUEST_CR4);
10375         u64 efer = vmcs_read64(GUEST_IA32_EFER);
10376         int i, n;
10377
10378         if (cpu_has_secondary_exec_ctrls())
10379                 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
10380
10381         pr_err("*** Guest State ***\n");
10382         pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
10383                vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
10384                vmcs_readl(CR0_GUEST_HOST_MASK));
10385         pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
10386                cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
10387         pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
10388         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
10389             (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
10390         {
10391                 pr_err("PDPTR0 = 0x%016llx  PDPTR1 = 0x%016llx\n",
10392                        vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
10393                 pr_err("PDPTR2 = 0x%016llx  PDPTR3 = 0x%016llx\n",
10394                        vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
10395         }
10396         pr_err("RSP = 0x%016lx  RIP = 0x%016lx\n",
10397                vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
10398         pr_err("RFLAGS=0x%08lx         DR7 = 0x%016lx\n",
10399                vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
10400         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
10401                vmcs_readl(GUEST_SYSENTER_ESP),
10402                vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
10403         vmx_dump_sel("CS:  ", GUEST_CS_SELECTOR);
10404         vmx_dump_sel("DS:  ", GUEST_DS_SELECTOR);
10405         vmx_dump_sel("SS:  ", GUEST_SS_SELECTOR);
10406         vmx_dump_sel("ES:  ", GUEST_ES_SELECTOR);
10407         vmx_dump_sel("FS:  ", GUEST_FS_SELECTOR);
10408         vmx_dump_sel("GS:  ", GUEST_GS_SELECTOR);
10409         vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
10410         vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
10411         vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
10412         vmx_dump_sel("TR:  ", GUEST_TR_SELECTOR);
10413         if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
10414             (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
10415                 pr_err("EFER =     0x%016llx  PAT = 0x%016llx\n",
10416                        efer, vmcs_read64(GUEST_IA32_PAT));
10417         pr_err("DebugCtl = 0x%016llx  DebugExceptions = 0x%016lx\n",
10418                vmcs_read64(GUEST_IA32_DEBUGCTL),
10419                vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
10420         if (cpu_has_load_perf_global_ctrl &&
10421             vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
10422                 pr_err("PerfGlobCtl = 0x%016llx\n",
10423                        vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
10424         if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
10425                 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
10426         pr_err("Interruptibility = %08x  ActivityState = %08x\n",
10427                vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
10428                vmcs_read32(GUEST_ACTIVITY_STATE));
10429         if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
10430                 pr_err("InterruptStatus = %04x\n",
10431                        vmcs_read16(GUEST_INTR_STATUS));
10432
10433         pr_err("*** Host State ***\n");
10434         pr_err("RIP = 0x%016lx  RSP = 0x%016lx\n",
10435                vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
10436         pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
10437                vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
10438                vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
10439                vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
10440                vmcs_read16(HOST_TR_SELECTOR));
10441         pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
10442                vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
10443                vmcs_readl(HOST_TR_BASE));
10444         pr_err("GDTBase=%016lx IDTBase=%016lx\n",
10445                vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
10446         pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
10447                vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
10448                vmcs_readl(HOST_CR4));
10449         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
10450                vmcs_readl(HOST_IA32_SYSENTER_ESP),
10451                vmcs_read32(HOST_IA32_SYSENTER_CS),
10452                vmcs_readl(HOST_IA32_SYSENTER_EIP));
10453         if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
10454                 pr_err("EFER = 0x%016llx  PAT = 0x%016llx\n",
10455                        vmcs_read64(HOST_IA32_EFER),
10456                        vmcs_read64(HOST_IA32_PAT));
10457         if (cpu_has_load_perf_global_ctrl &&
10458             vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
10459                 pr_err("PerfGlobCtl = 0x%016llx\n",
10460                        vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
10461
10462         pr_err("*** Control State ***\n");
10463         pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
10464                pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
10465         pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
10466         pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
10467                vmcs_read32(EXCEPTION_BITMAP),
10468                vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
10469                vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
10470         pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
10471                vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
10472                vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
10473                vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
10474         pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
10475                vmcs_read32(VM_EXIT_INTR_INFO),
10476                vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
10477                vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
10478         pr_err("        reason=%08x qualification=%016lx\n",
10479                vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
10480         pr_err("IDTVectoring: info=%08x errcode=%08x\n",
10481                vmcs_read32(IDT_VECTORING_INFO_FIELD),
10482                vmcs_read32(IDT_VECTORING_ERROR_CODE));
10483         pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
10484         if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
10485                 pr_err("TSC Multiplier = 0x%016llx\n",
10486                        vmcs_read64(TSC_MULTIPLIER));
10487         if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
10488                 pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
10489         if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
10490                 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
10491         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
10492                 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
10493         n = vmcs_read32(CR3_TARGET_COUNT);
10494         for (i = 0; i + 1 < n; i += 4)
10495                 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
10496                        i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
10497                        i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
10498         if (i < n)
10499                 pr_err("CR3 target%u=%016lx\n",
10500                        i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
10501         if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
10502                 pr_err("PLE Gap=%08x Window=%08x\n",
10503                        vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
10504         if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
10505                 pr_err("Virtual processor ID = 0x%04x\n",
10506                        vmcs_read16(VIRTUAL_PROCESSOR_ID));
10507 }
10508
10509 /*
10510  * The guest has exited.  See if we can fix it or if we need userspace
10511  * assistance.
10512  */
10513 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
10514 {
10515         struct vcpu_vmx *vmx = to_vmx(vcpu);
10516         u32 exit_reason = vmx->exit_reason;
10517         u32 vectoring_info = vmx->idt_vectoring_info;
10518
10519         trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
10520
10521         /*
10522          * Flush logged GPAs PML buffer, this will make dirty_bitmap more
10523          * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
10524          * querying dirty_bitmap, we only need to kick all vcpus out of guest
10525          * mode as if vcpus is in root mode, the PML buffer must has been
10526          * flushed already.
10527          */
10528         if (enable_pml)
10529                 vmx_flush_pml_buffer(vcpu);
10530
10531         /* If guest state is invalid, start emulating */
10532         if (vmx->emulation_required)
10533                 return handle_invalid_guest_state(vcpu);
10534
10535         if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
10536                 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
10537
10538         if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
10539                 dump_vmcs();
10540                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
10541                 vcpu->run->fail_entry.hardware_entry_failure_reason
10542                         = exit_reason;
10543                 return 0;
10544         }
10545
10546         if (unlikely(vmx->fail)) {
10547                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
10548                 vcpu->run->fail_entry.hardware_entry_failure_reason
10549                         = vmcs_read32(VM_INSTRUCTION_ERROR);
10550                 return 0;
10551         }
10552
10553         /*
10554          * Note:
10555          * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
10556          * delivery event since it indicates guest is accessing MMIO.
10557          * The vm-exit can be triggered again after return to guest that
10558          * will cause infinite loop.
10559          */
10560         if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
10561                         (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
10562                         exit_reason != EXIT_REASON_EPT_VIOLATION &&
10563                         exit_reason != EXIT_REASON_PML_FULL &&
10564                         exit_reason != EXIT_REASON_TASK_SWITCH)) {
10565                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
10566                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
10567                 vcpu->run->internal.ndata = 3;
10568                 vcpu->run->internal.data[0] = vectoring_info;
10569                 vcpu->run->internal.data[1] = exit_reason;
10570                 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
10571                 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
10572                         vcpu->run->internal.ndata++;
10573                         vcpu->run->internal.data[3] =
10574                                 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
10575                 }
10576                 return 0;
10577         }
10578
10579         if (unlikely(!enable_vnmi &&
10580                      vmx->loaded_vmcs->soft_vnmi_blocked)) {
10581                 if (vmx_interrupt_allowed(vcpu)) {
10582                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
10583                 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
10584                            vcpu->arch.nmi_pending) {
10585                         /*
10586                          * This CPU don't support us in finding the end of an
10587                          * NMI-blocked window if the guest runs with IRQs
10588                          * disabled. So we pull the trigger after 1 s of
10589                          * futile waiting, but inform the user about this.
10590                          */
10591                         printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
10592                                "state on VCPU %d after 1 s timeout\n",
10593                                __func__, vcpu->vcpu_id);
10594                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
10595                 }
10596         }
10597
10598         if (exit_reason < kvm_vmx_max_exit_handlers
10599             && kvm_vmx_exit_handlers[exit_reason])
10600                 return kvm_vmx_exit_handlers[exit_reason](vcpu);
10601         else {
10602                 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
10603                                 exit_reason);
10604                 kvm_queue_exception(vcpu, UD_VECTOR);
10605                 return 1;
10606         }
10607 }
10608
10609 /*
10610  * Software based L1D cache flush which is used when microcode providing
10611  * the cache control MSR is not loaded.
10612  *
10613  * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
10614  * flush it is required to read in 64 KiB because the replacement algorithm
10615  * is not exactly LRU. This could be sized at runtime via topology
10616  * information but as all relevant affected CPUs have 32KiB L1D cache size
10617  * there is no point in doing so.
10618  */
10619 static void vmx_l1d_flush(struct kvm_vcpu *vcpu)
10620 {
10621         int size = PAGE_SIZE << L1D_CACHE_ORDER;
10622
10623         /*
10624          * This code is only executed when the the flush mode is 'cond' or
10625          * 'always'
10626          */
10627         if (static_branch_likely(&vmx_l1d_flush_cond)) {
10628                 bool flush_l1d;
10629
10630                 /*
10631                  * Clear the per-vcpu flush bit, it gets set again
10632                  * either from vcpu_run() or from one of the unsafe
10633                  * VMEXIT handlers.
10634                  */
10635                 flush_l1d = vcpu->arch.l1tf_flush_l1d;
10636                 vcpu->arch.l1tf_flush_l1d = false;
10637
10638                 /*
10639                  * Clear the per-cpu flush bit, it gets set again from
10640                  * the interrupt handlers.
10641                  */
10642                 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
10643                 kvm_clear_cpu_l1tf_flush_l1d();
10644
10645                 if (!flush_l1d)
10646                         return;
10647         }
10648
10649         vcpu->stat.l1d_flush++;
10650
10651         if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
10652                 wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
10653                 return;
10654         }
10655
10656         asm volatile(
10657                 /* First ensure the pages are in the TLB */
10658                 "xorl   %%eax, %%eax\n"
10659                 ".Lpopulate_tlb:\n\t"
10660                 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
10661                 "addl   $4096, %%eax\n\t"
10662                 "cmpl   %%eax, %[size]\n\t"
10663                 "jne    .Lpopulate_tlb\n\t"
10664                 "xorl   %%eax, %%eax\n\t"
10665                 "cpuid\n\t"
10666                 /* Now fill the cache */
10667                 "xorl   %%eax, %%eax\n"
10668                 ".Lfill_cache:\n"
10669                 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
10670                 "addl   $64, %%eax\n\t"
10671                 "cmpl   %%eax, %[size]\n\t"
10672                 "jne    .Lfill_cache\n\t"
10673                 "lfence\n"
10674                 :: [flush_pages] "r" (vmx_l1d_flush_pages),
10675                     [size] "r" (size)
10676                 : "eax", "ebx", "ecx", "edx");
10677 }
10678
10679 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
10680 {
10681         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10682
10683         if (is_guest_mode(vcpu) &&
10684                 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10685                 return;
10686
10687         if (irr == -1 || tpr < irr) {
10688                 vmcs_write32(TPR_THRESHOLD, 0);
10689                 return;
10690         }
10691
10692         vmcs_write32(TPR_THRESHOLD, irr);
10693 }
10694
10695 static void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
10696 {
10697         u32 sec_exec_control;
10698
10699         if (!lapic_in_kernel(vcpu))
10700                 return;
10701
10702         if (!flexpriority_enabled &&
10703             !cpu_has_vmx_virtualize_x2apic_mode())
10704                 return;
10705
10706         /* Postpone execution until vmcs01 is the current VMCS. */
10707         if (is_guest_mode(vcpu)) {
10708                 to_vmx(vcpu)->nested.change_vmcs01_virtual_apic_mode = true;
10709                 return;
10710         }
10711
10712         sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
10713         sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
10714                               SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
10715
10716         switch (kvm_get_apic_mode(vcpu)) {
10717         case LAPIC_MODE_INVALID:
10718                 WARN_ONCE(true, "Invalid local APIC state");
10719         case LAPIC_MODE_DISABLED:
10720                 break;
10721         case LAPIC_MODE_XAPIC:
10722                 if (flexpriority_enabled) {
10723                         sec_exec_control |=
10724                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
10725                         vmx_flush_tlb(vcpu, true);
10726                 }
10727                 break;
10728         case LAPIC_MODE_X2APIC:
10729                 if (cpu_has_vmx_virtualize_x2apic_mode())
10730                         sec_exec_control |=
10731                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
10732                 break;
10733         }
10734         vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
10735
10736         vmx_update_msr_bitmap(vcpu);
10737 }
10738
10739 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
10740 {
10741         if (!is_guest_mode(vcpu)) {
10742                 vmcs_write64(APIC_ACCESS_ADDR, hpa);
10743                 vmx_flush_tlb(vcpu, true);
10744         }
10745 }
10746
10747 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
10748 {
10749         u16 status;
10750         u8 old;
10751
10752         if (max_isr == -1)
10753                 max_isr = 0;
10754
10755         status = vmcs_read16(GUEST_INTR_STATUS);
10756         old = status >> 8;
10757         if (max_isr != old) {
10758                 status &= 0xff;
10759                 status |= max_isr << 8;
10760                 vmcs_write16(GUEST_INTR_STATUS, status);
10761         }
10762 }
10763
10764 static void vmx_set_rvi(int vector)
10765 {
10766         u16 status;
10767         u8 old;
10768
10769         if (vector == -1)
10770                 vector = 0;
10771
10772         status = vmcs_read16(GUEST_INTR_STATUS);
10773         old = (u8)status & 0xff;
10774         if ((u8)vector != old) {
10775                 status &= ~0xff;
10776                 status |= (u8)vector;
10777                 vmcs_write16(GUEST_INTR_STATUS, status);
10778         }
10779 }
10780
10781 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
10782 {
10783         /*
10784          * When running L2, updating RVI is only relevant when
10785          * vmcs12 virtual-interrupt-delivery enabled.
10786          * However, it can be enabled only when L1 also
10787          * intercepts external-interrupts and in that case
10788          * we should not update vmcs02 RVI but instead intercept
10789          * interrupt. Therefore, do nothing when running L2.
10790          */
10791         if (!is_guest_mode(vcpu))
10792                 vmx_set_rvi(max_irr);
10793 }
10794
10795 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
10796 {
10797         struct vcpu_vmx *vmx = to_vmx(vcpu);
10798         int max_irr;
10799         bool max_irr_updated;
10800
10801         WARN_ON(!vcpu->arch.apicv_active);
10802         if (pi_test_on(&vmx->pi_desc)) {
10803                 pi_clear_on(&vmx->pi_desc);
10804                 /*
10805                  * IOMMU can write to PIR.ON, so the barrier matters even on UP.
10806                  * But on x86 this is just a compiler barrier anyway.
10807                  */
10808                 smp_mb__after_atomic();
10809                 max_irr_updated =
10810                         kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
10811
10812                 /*
10813                  * If we are running L2 and L1 has a new pending interrupt
10814                  * which can be injected, we should re-evaluate
10815                  * what should be done with this new L1 interrupt.
10816                  * If L1 intercepts external-interrupts, we should
10817                  * exit from L2 to L1. Otherwise, interrupt should be
10818                  * delivered directly to L2.
10819                  */
10820                 if (is_guest_mode(vcpu) && max_irr_updated) {
10821                         if (nested_exit_on_intr(vcpu))
10822                                 kvm_vcpu_exiting_guest_mode(vcpu);
10823                         else
10824                                 kvm_make_request(KVM_REQ_EVENT, vcpu);
10825                 }
10826         } else {
10827                 max_irr = kvm_lapic_find_highest_irr(vcpu);
10828         }
10829         vmx_hwapic_irr_update(vcpu, max_irr);
10830         return max_irr;
10831 }
10832
10833 static u8 vmx_has_apicv_interrupt(struct kvm_vcpu *vcpu)
10834 {
10835         u8 rvi = vmx_get_rvi();
10836         u8 vppr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_PROCPRI);
10837
10838         return ((rvi & 0xf0) > (vppr & 0xf0));
10839 }
10840
10841 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
10842 {
10843         if (!kvm_vcpu_apicv_active(vcpu))
10844                 return;
10845
10846         vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
10847         vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
10848         vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
10849         vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
10850 }
10851
10852 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
10853 {
10854         struct vcpu_vmx *vmx = to_vmx(vcpu);
10855
10856         pi_clear_on(&vmx->pi_desc);
10857         memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
10858 }
10859
10860 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
10861 {
10862         u32 exit_intr_info = 0;
10863         u16 basic_exit_reason = (u16)vmx->exit_reason;
10864
10865         if (!(basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
10866               || basic_exit_reason == EXIT_REASON_EXCEPTION_NMI))
10867                 return;
10868
10869         if (!(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
10870                 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10871         vmx->exit_intr_info = exit_intr_info;
10872
10873         /* if exit due to PF check for async PF */
10874         if (is_page_fault(exit_intr_info))
10875                 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
10876
10877         /* Handle machine checks before interrupts are enabled */
10878         if (basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY ||
10879             is_machine_check(exit_intr_info))
10880                 kvm_machine_check();
10881
10882         /* We need to handle NMIs before interrupts are enabled */
10883         if (is_nmi(exit_intr_info)) {
10884                 kvm_before_interrupt(&vmx->vcpu);
10885                 asm("int $2");
10886                 kvm_after_interrupt(&vmx->vcpu);
10887         }
10888 }
10889
10890 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
10891 {
10892         u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10893
10894         if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
10895                         == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
10896                 unsigned int vector;
10897                 unsigned long entry;
10898                 gate_desc *desc;
10899                 struct vcpu_vmx *vmx = to_vmx(vcpu);
10900 #ifdef CONFIG_X86_64
10901                 unsigned long tmp;
10902 #endif
10903
10904                 vector =  exit_intr_info & INTR_INFO_VECTOR_MASK;
10905                 desc = (gate_desc *)vmx->host_idt_base + vector;
10906                 entry = gate_offset(desc);
10907                 asm volatile(
10908 #ifdef CONFIG_X86_64
10909                         "mov %%" _ASM_SP ", %[sp]\n\t"
10910                         "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
10911                         "push $%c[ss]\n\t"
10912                         "push %[sp]\n\t"
10913 #endif
10914                         "pushf\n\t"
10915                         __ASM_SIZE(push) " $%c[cs]\n\t"
10916                         CALL_NOSPEC
10917                         :
10918 #ifdef CONFIG_X86_64
10919                         [sp]"=&r"(tmp),
10920 #endif
10921                         ASM_CALL_CONSTRAINT
10922                         :
10923                         THUNK_TARGET(entry),
10924                         [ss]"i"(__KERNEL_DS),
10925                         [cs]"i"(__KERNEL_CS)
10926                         );
10927         }
10928 }
10929 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
10930
10931 static bool vmx_has_emulated_msr(int index)
10932 {
10933         switch (index) {
10934         case MSR_IA32_SMBASE:
10935                 /*
10936                  * We cannot do SMM unless we can run the guest in big
10937                  * real mode.
10938                  */
10939                 return enable_unrestricted_guest || emulate_invalid_guest_state;
10940         case MSR_AMD64_VIRT_SPEC_CTRL:
10941                 /* This is AMD only.  */
10942                 return false;
10943         default:
10944                 return true;
10945         }
10946 }
10947
10948 static bool vmx_mpx_supported(void)
10949 {
10950         return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
10951                 (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
10952 }
10953
10954 static bool vmx_xsaves_supported(void)
10955 {
10956         return vmcs_config.cpu_based_2nd_exec_ctrl &
10957                 SECONDARY_EXEC_XSAVES;
10958 }
10959
10960 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
10961 {
10962         u32 exit_intr_info;
10963         bool unblock_nmi;
10964         u8 vector;
10965         bool idtv_info_valid;
10966
10967         idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
10968
10969         if (enable_vnmi) {
10970                 if (vmx->loaded_vmcs->nmi_known_unmasked)
10971                         return;
10972                 /*
10973                  * Can't use vmx->exit_intr_info since we're not sure what
10974                  * the exit reason is.
10975                  */
10976                 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10977                 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
10978                 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
10979                 /*
10980                  * SDM 3: 27.7.1.2 (September 2008)
10981                  * Re-set bit "block by NMI" before VM entry if vmexit caused by
10982                  * a guest IRET fault.
10983                  * SDM 3: 23.2.2 (September 2008)
10984                  * Bit 12 is undefined in any of the following cases:
10985                  *  If the VM exit sets the valid bit in the IDT-vectoring
10986                  *   information field.
10987                  *  If the VM exit is due to a double fault.
10988                  */
10989                 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
10990                     vector != DF_VECTOR && !idtv_info_valid)
10991                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
10992                                       GUEST_INTR_STATE_NMI);
10993                 else
10994                         vmx->loaded_vmcs->nmi_known_unmasked =
10995                                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
10996                                   & GUEST_INTR_STATE_NMI);
10997         } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
10998                 vmx->loaded_vmcs->vnmi_blocked_time +=
10999                         ktime_to_ns(ktime_sub(ktime_get(),
11000                                               vmx->loaded_vmcs->entry_time));
11001 }
11002
11003 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
11004                                       u32 idt_vectoring_info,
11005                                       int instr_len_field,
11006                                       int error_code_field)
11007 {
11008         u8 vector;
11009         int type;
11010         bool idtv_info_valid;
11011
11012         idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
11013
11014         vcpu->arch.nmi_injected = false;
11015         kvm_clear_exception_queue(vcpu);
11016         kvm_clear_interrupt_queue(vcpu);
11017
11018         if (!idtv_info_valid)
11019                 return;
11020
11021         kvm_make_request(KVM_REQ_EVENT, vcpu);
11022
11023         vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
11024         type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
11025
11026         switch (type) {
11027         case INTR_TYPE_NMI_INTR:
11028                 vcpu->arch.nmi_injected = true;
11029                 /*
11030                  * SDM 3: 27.7.1.2 (September 2008)
11031                  * Clear bit "block by NMI" before VM entry if a NMI
11032                  * delivery faulted.
11033                  */
11034                 vmx_set_nmi_mask(vcpu, false);
11035                 break;
11036         case INTR_TYPE_SOFT_EXCEPTION:
11037                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
11038                 /* fall through */
11039         case INTR_TYPE_HARD_EXCEPTION:
11040                 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
11041                         u32 err = vmcs_read32(error_code_field);
11042                         kvm_requeue_exception_e(vcpu, vector, err);
11043                 } else
11044                         kvm_requeue_exception(vcpu, vector);
11045                 break;
11046         case INTR_TYPE_SOFT_INTR:
11047                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
11048                 /* fall through */
11049         case INTR_TYPE_EXT_INTR:
11050                 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
11051                 break;
11052         default:
11053                 break;
11054         }
11055 }
11056
11057 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
11058 {
11059         __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
11060                                   VM_EXIT_INSTRUCTION_LEN,
11061                                   IDT_VECTORING_ERROR_CODE);
11062 }
11063
11064 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
11065 {
11066         __vmx_complete_interrupts(vcpu,
11067                                   vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
11068                                   VM_ENTRY_INSTRUCTION_LEN,
11069                                   VM_ENTRY_EXCEPTION_ERROR_CODE);
11070
11071         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
11072 }
11073
11074 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
11075 {
11076         int i, nr_msrs;
11077         struct perf_guest_switch_msr *msrs;
11078
11079         msrs = perf_guest_get_msrs(&nr_msrs);
11080
11081         if (!msrs)
11082                 return;
11083
11084         for (i = 0; i < nr_msrs; i++)
11085                 if (msrs[i].host == msrs[i].guest)
11086                         clear_atomic_switch_msr(vmx, msrs[i].msr);
11087                 else
11088                         add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
11089                                         msrs[i].host, false);
11090 }
11091
11092 static void vmx_arm_hv_timer(struct vcpu_vmx *vmx, u32 val)
11093 {
11094         vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, val);
11095         if (!vmx->loaded_vmcs->hv_timer_armed)
11096                 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
11097                               PIN_BASED_VMX_PREEMPTION_TIMER);
11098         vmx->loaded_vmcs->hv_timer_armed = true;
11099 }
11100
11101 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
11102 {
11103         struct vcpu_vmx *vmx = to_vmx(vcpu);
11104         u64 tscl;
11105         u32 delta_tsc;
11106
11107         if (vmx->req_immediate_exit) {
11108                 vmx_arm_hv_timer(vmx, 0);
11109                 return;
11110         }
11111
11112         if (vmx->hv_deadline_tsc != -1) {
11113                 tscl = rdtsc();
11114                 if (vmx->hv_deadline_tsc > tscl)
11115                         /* set_hv_timer ensures the delta fits in 32-bits */
11116                         delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
11117                                 cpu_preemption_timer_multi);
11118                 else
11119                         delta_tsc = 0;
11120
11121                 vmx_arm_hv_timer(vmx, delta_tsc);
11122                 return;
11123         }
11124
11125         if (vmx->loaded_vmcs->hv_timer_armed)
11126                 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
11127                                 PIN_BASED_VMX_PREEMPTION_TIMER);
11128         vmx->loaded_vmcs->hv_timer_armed = false;
11129 }
11130
11131 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
11132 {
11133         struct vcpu_vmx *vmx = to_vmx(vcpu);
11134         unsigned long cr3, cr4, evmcs_rsp;
11135
11136         /* Record the guest's net vcpu time for enforced NMI injections. */
11137         if (unlikely(!enable_vnmi &&
11138                      vmx->loaded_vmcs->soft_vnmi_blocked))
11139                 vmx->loaded_vmcs->entry_time = ktime_get();
11140
11141         /* Don't enter VMX if guest state is invalid, let the exit handler
11142            start emulation until we arrive back to a valid state */
11143         if (vmx->emulation_required)
11144                 return;
11145
11146         if (vmx->ple_window_dirty) {
11147                 vmx->ple_window_dirty = false;
11148                 vmcs_write32(PLE_WINDOW, vmx->ple_window);
11149         }
11150
11151         if (vmx->nested.need_vmcs12_sync) {
11152                 /*
11153                  * hv_evmcs may end up being not mapped after migration (when
11154                  * L2 was running), map it here to make sure vmcs12 changes are
11155                  * properly reflected.
11156                  */
11157                 if (vmx->nested.enlightened_vmcs_enabled &&
11158                     !vmx->nested.hv_evmcs)
11159                         nested_vmx_handle_enlightened_vmptrld(vcpu, false);
11160
11161                 if (vmx->nested.hv_evmcs) {
11162                         copy_vmcs12_to_enlightened(vmx);
11163                         /* All fields are clean */
11164                         vmx->nested.hv_evmcs->hv_clean_fields |=
11165                                 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
11166                 } else {
11167                         copy_vmcs12_to_shadow(vmx);
11168                 }
11169                 vmx->nested.need_vmcs12_sync = false;
11170         }
11171
11172         if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
11173                 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
11174         if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
11175                 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
11176
11177         cr3 = __get_current_cr3_fast();
11178         if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
11179                 vmcs_writel(HOST_CR3, cr3);
11180                 vmx->loaded_vmcs->host_state.cr3 = cr3;
11181         }
11182
11183         cr4 = cr4_read_shadow();
11184         if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
11185                 vmcs_writel(HOST_CR4, cr4);
11186                 vmx->loaded_vmcs->host_state.cr4 = cr4;
11187         }
11188
11189         /* When single-stepping over STI and MOV SS, we must clear the
11190          * corresponding interruptibility bits in the guest state. Otherwise
11191          * vmentry fails as it then expects bit 14 (BS) in pending debug
11192          * exceptions being set, but that's not correct for the guest debugging
11193          * case. */
11194         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
11195                 vmx_set_interrupt_shadow(vcpu, 0);
11196
11197         if (static_cpu_has(X86_FEATURE_PKU) &&
11198             kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
11199             vcpu->arch.pkru != vmx->host_pkru)
11200                 __write_pkru(vcpu->arch.pkru);
11201
11202         atomic_switch_perf_msrs(vmx);
11203
11204         vmx_update_hv_timer(vcpu);
11205
11206         /*
11207          * If this vCPU has touched SPEC_CTRL, restore the guest's value if
11208          * it's non-zero. Since vmentry is serialising on affected CPUs, there
11209          * is no need to worry about the conditional branch over the wrmsr
11210          * being speculatively taken.
11211          */
11212         x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
11213
11214         vmx->__launched = vmx->loaded_vmcs->launched;
11215
11216         evmcs_rsp = static_branch_unlikely(&enable_evmcs) ?
11217                 (unsigned long)&current_evmcs->host_rsp : 0;
11218
11219         if (static_branch_unlikely(&vmx_l1d_should_flush))
11220                 vmx_l1d_flush(vcpu);
11221
11222         asm(
11223                 /* Store host registers */
11224                 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
11225                 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
11226                 "push %%" _ASM_CX " \n\t"
11227                 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
11228                 "je 1f \n\t"
11229                 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
11230                 /* Avoid VMWRITE when Enlightened VMCS is in use */
11231                 "test %%" _ASM_SI ", %%" _ASM_SI " \n\t"
11232                 "jz 2f \n\t"
11233                 "mov %%" _ASM_SP ", (%%" _ASM_SI ") \n\t"
11234                 "jmp 1f \n\t"
11235                 "2: \n\t"
11236                 __ex("vmwrite %%" _ASM_SP ", %%" _ASM_DX) "\n\t"
11237                 "1: \n\t"
11238                 /* Reload cr2 if changed */
11239                 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
11240                 "mov %%cr2, %%" _ASM_DX " \n\t"
11241                 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
11242                 "je 3f \n\t"
11243                 "mov %%" _ASM_AX", %%cr2 \n\t"
11244                 "3: \n\t"
11245                 /* Check if vmlaunch of vmresume is needed */
11246                 "cmpl $0, %c[launched](%0) \n\t"
11247                 /* Load guest registers.  Don't clobber flags. */
11248                 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
11249                 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
11250                 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
11251                 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
11252                 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
11253                 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
11254 #ifdef CONFIG_X86_64
11255                 "mov %c[r8](%0),  %%r8  \n\t"
11256                 "mov %c[r9](%0),  %%r9  \n\t"
11257                 "mov %c[r10](%0), %%r10 \n\t"
11258                 "mov %c[r11](%0), %%r11 \n\t"
11259                 "mov %c[r12](%0), %%r12 \n\t"
11260                 "mov %c[r13](%0), %%r13 \n\t"
11261                 "mov %c[r14](%0), %%r14 \n\t"
11262                 "mov %c[r15](%0), %%r15 \n\t"
11263 #endif
11264                 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
11265
11266                 /* Enter guest mode */
11267                 "jne 1f \n\t"
11268                 __ex("vmlaunch") "\n\t"
11269                 "jmp 2f \n\t"
11270                 "1: " __ex("vmresume") "\n\t"
11271                 "2: "
11272                 /* Save guest registers, load host registers, keep flags */
11273                 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
11274                 "pop %0 \n\t"
11275                 "setbe %c[fail](%0)\n\t"
11276                 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
11277                 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
11278                 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
11279                 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
11280                 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
11281                 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
11282                 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
11283 #ifdef CONFIG_X86_64
11284                 "mov %%r8,  %c[r8](%0) \n\t"
11285                 "mov %%r9,  %c[r9](%0) \n\t"
11286                 "mov %%r10, %c[r10](%0) \n\t"
11287                 "mov %%r11, %c[r11](%0) \n\t"
11288                 "mov %%r12, %c[r12](%0) \n\t"
11289                 "mov %%r13, %c[r13](%0) \n\t"
11290                 "mov %%r14, %c[r14](%0) \n\t"
11291                 "mov %%r15, %c[r15](%0) \n\t"
11292                 /*
11293                 * Clear host registers marked as clobbered to prevent
11294                 * speculative use.
11295                 */
11296                 "xor %%r8d,  %%r8d \n\t"
11297                 "xor %%r9d,  %%r9d \n\t"
11298                 "xor %%r10d, %%r10d \n\t"
11299                 "xor %%r11d, %%r11d \n\t"
11300                 "xor %%r12d, %%r12d \n\t"
11301                 "xor %%r13d, %%r13d \n\t"
11302                 "xor %%r14d, %%r14d \n\t"
11303                 "xor %%r15d, %%r15d \n\t"
11304 #endif
11305                 "mov %%cr2, %%" _ASM_AX "   \n\t"
11306                 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
11307
11308                 "xor %%eax, %%eax \n\t"
11309                 "xor %%ebx, %%ebx \n\t"
11310                 "xor %%esi, %%esi \n\t"
11311                 "xor %%edi, %%edi \n\t"
11312                 "pop  %%" _ASM_BP "; pop  %%" _ASM_DX " \n\t"
11313                 ".pushsection .rodata \n\t"
11314                 ".global vmx_return \n\t"
11315                 "vmx_return: " _ASM_PTR " 2b \n\t"
11316                 ".popsection"
11317               : : "c"(vmx), "d"((unsigned long)HOST_RSP), "S"(evmcs_rsp),
11318                 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
11319                 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
11320                 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
11321                 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
11322                 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
11323                 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
11324                 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
11325                 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
11326                 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
11327                 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
11328 #ifdef CONFIG_X86_64
11329                 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
11330                 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
11331                 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
11332                 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
11333                 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
11334                 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
11335                 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
11336                 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
11337 #endif
11338                 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
11339                 [wordsize]"i"(sizeof(ulong))
11340               : "cc", "memory"
11341 #ifdef CONFIG_X86_64
11342                 , "rax", "rbx", "rdi"
11343                 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
11344 #else
11345                 , "eax", "ebx", "edi"
11346 #endif
11347               );
11348
11349         /*
11350          * We do not use IBRS in the kernel. If this vCPU has used the
11351          * SPEC_CTRL MSR it may have left it on; save the value and
11352          * turn it off. This is much more efficient than blindly adding
11353          * it to the atomic save/restore list. Especially as the former
11354          * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
11355          *
11356          * For non-nested case:
11357          * If the L01 MSR bitmap does not intercept the MSR, then we need to
11358          * save it.
11359          *
11360          * For nested case:
11361          * If the L02 MSR bitmap does not intercept the MSR, then we need to
11362          * save it.
11363          */
11364         if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
11365                 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
11366
11367         x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
11368
11369         /* Eliminate branch target predictions from guest mode */
11370         vmexit_fill_RSB();
11371
11372         /* All fields are clean at this point */
11373         if (static_branch_unlikely(&enable_evmcs))
11374                 current_evmcs->hv_clean_fields |=
11375                         HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
11376
11377         /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
11378         if (vmx->host_debugctlmsr)
11379                 update_debugctlmsr(vmx->host_debugctlmsr);
11380
11381 #ifndef CONFIG_X86_64
11382         /*
11383          * The sysexit path does not restore ds/es, so we must set them to
11384          * a reasonable value ourselves.
11385          *
11386          * We can't defer this to vmx_prepare_switch_to_host() since that
11387          * function may be executed in interrupt context, which saves and
11388          * restore segments around it, nullifying its effect.
11389          */
11390         loadsegment(ds, __USER_DS);
11391         loadsegment(es, __USER_DS);
11392 #endif
11393
11394         vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
11395                                   | (1 << VCPU_EXREG_RFLAGS)
11396                                   | (1 << VCPU_EXREG_PDPTR)
11397                                   | (1 << VCPU_EXREG_SEGMENTS)
11398                                   | (1 << VCPU_EXREG_CR3));
11399         vcpu->arch.regs_dirty = 0;
11400
11401         /*
11402          * eager fpu is enabled if PKEY is supported and CR4 is switched
11403          * back on host, so it is safe to read guest PKRU from current
11404          * XSAVE.
11405          */
11406         if (static_cpu_has(X86_FEATURE_PKU) &&
11407             kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
11408                 vcpu->arch.pkru = __read_pkru();
11409                 if (vcpu->arch.pkru != vmx->host_pkru)
11410                         __write_pkru(vmx->host_pkru);
11411         }
11412
11413         vmx->nested.nested_run_pending = 0;
11414         vmx->idt_vectoring_info = 0;
11415
11416         vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
11417         if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
11418                 return;
11419
11420         vmx->loaded_vmcs->launched = 1;
11421         vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
11422
11423         vmx_complete_atomic_exit(vmx);
11424         vmx_recover_nmi_blocking(vmx);
11425         vmx_complete_interrupts(vmx);
11426 }
11427 STACK_FRAME_NON_STANDARD(vmx_vcpu_run);
11428
11429 static struct kvm *vmx_vm_alloc(void)
11430 {
11431         struct kvm_vmx *kvm_vmx = vzalloc(sizeof(struct kvm_vmx));
11432         return &kvm_vmx->kvm;
11433 }
11434
11435 static void vmx_vm_free(struct kvm *kvm)
11436 {
11437         vfree(to_kvm_vmx(kvm));
11438 }
11439
11440 static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
11441 {
11442         struct vcpu_vmx *vmx = to_vmx(vcpu);
11443         int cpu;
11444
11445         if (vmx->loaded_vmcs == vmcs)
11446                 return;
11447
11448         cpu = get_cpu();
11449         vmx_vcpu_put(vcpu);
11450         vmx->loaded_vmcs = vmcs;
11451         vmx_vcpu_load(vcpu, cpu);
11452         put_cpu();
11453
11454         vm_entry_controls_reset_shadow(vmx);
11455         vm_exit_controls_reset_shadow(vmx);
11456         vmx_segment_cache_clear(vmx);
11457 }
11458
11459 /*
11460  * Ensure that the current vmcs of the logical processor is the
11461  * vmcs01 of the vcpu before calling free_nested().
11462  */
11463 static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu)
11464 {
11465         vcpu_load(vcpu);
11466         vmx_switch_vmcs(vcpu, &to_vmx(vcpu)->vmcs01);
11467         free_nested(vcpu);
11468         vcpu_put(vcpu);
11469 }
11470
11471 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
11472 {
11473         struct vcpu_vmx *vmx = to_vmx(vcpu);
11474
11475         if (enable_pml)
11476                 vmx_destroy_pml_buffer(vmx);
11477         free_vpid(vmx->vpid);
11478         leave_guest_mode(vcpu);
11479         vmx_free_vcpu_nested(vcpu);
11480         free_loaded_vmcs(vmx->loaded_vmcs);
11481         kfree(vmx->guest_msrs);
11482         kvm_vcpu_uninit(vcpu);
11483         kmem_cache_free(kvm_vcpu_cache, vmx);
11484 }
11485
11486 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
11487 {
11488         int err;
11489         struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
11490         unsigned long *msr_bitmap;
11491         int cpu;
11492
11493         if (!vmx)
11494                 return ERR_PTR(-ENOMEM);
11495
11496         vmx->vpid = allocate_vpid();
11497
11498         err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
11499         if (err)
11500                 goto free_vcpu;
11501
11502         err = -ENOMEM;
11503
11504         /*
11505          * If PML is turned on, failure on enabling PML just results in failure
11506          * of creating the vcpu, therefore we can simplify PML logic (by
11507          * avoiding dealing with cases, such as enabling PML partially on vcpus
11508          * for the guest, etc.
11509          */
11510         if (enable_pml) {
11511                 vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
11512                 if (!vmx->pml_pg)
11513                         goto uninit_vcpu;
11514         }
11515
11516         vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
11517         BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
11518                      > PAGE_SIZE);
11519
11520         if (!vmx->guest_msrs)
11521                 goto free_pml;
11522
11523         err = alloc_loaded_vmcs(&vmx->vmcs01);
11524         if (err < 0)
11525                 goto free_msrs;
11526
11527         msr_bitmap = vmx->vmcs01.msr_bitmap;
11528         vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
11529         vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
11530         vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
11531         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
11532         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
11533         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
11534         vmx->msr_bitmap_mode = 0;
11535
11536         vmx->loaded_vmcs = &vmx->vmcs01;
11537         cpu = get_cpu();
11538         vmx_vcpu_load(&vmx->vcpu, cpu);
11539         vmx->vcpu.cpu = cpu;
11540         vmx_vcpu_setup(vmx);
11541         vmx_vcpu_put(&vmx->vcpu);
11542         put_cpu();
11543         if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
11544                 err = alloc_apic_access_page(kvm);
11545                 if (err)
11546                         goto free_vmcs;
11547         }
11548
11549         if (enable_ept && !enable_unrestricted_guest) {
11550                 err = init_rmode_identity_map(kvm);
11551                 if (err)
11552                         goto free_vmcs;
11553         }
11554
11555         if (nested)
11556                 nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
11557                                            kvm_vcpu_apicv_active(&vmx->vcpu));
11558
11559         vmx->nested.posted_intr_nv = -1;
11560         vmx->nested.current_vmptr = -1ull;
11561
11562         vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
11563
11564         /*
11565          * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
11566          * or POSTED_INTR_WAKEUP_VECTOR.
11567          */
11568         vmx->pi_desc.nv = POSTED_INTR_VECTOR;
11569         vmx->pi_desc.sn = 1;
11570
11571         return &vmx->vcpu;
11572
11573 free_vmcs:
11574         free_loaded_vmcs(vmx->loaded_vmcs);
11575 free_msrs:
11576         kfree(vmx->guest_msrs);
11577 free_pml:
11578         vmx_destroy_pml_buffer(vmx);
11579 uninit_vcpu:
11580         kvm_vcpu_uninit(&vmx->vcpu);
11581 free_vcpu:
11582         free_vpid(vmx->vpid);
11583         kmem_cache_free(kvm_vcpu_cache, vmx);
11584         return ERR_PTR(err);
11585 }
11586
11587 #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"
11588 #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"
11589
11590 static int vmx_vm_init(struct kvm *kvm)
11591 {
11592         spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
11593
11594         if (!ple_gap)
11595                 kvm->arch.pause_in_guest = true;
11596
11597         if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
11598                 switch (l1tf_mitigation) {
11599                 case L1TF_MITIGATION_OFF:
11600                 case L1TF_MITIGATION_FLUSH_NOWARN:
11601                         /* 'I explicitly don't care' is set */
11602                         break;
11603                 case L1TF_MITIGATION_FLUSH:
11604                 case L1TF_MITIGATION_FLUSH_NOSMT:
11605                 case L1TF_MITIGATION_FULL:
11606                         /*
11607                          * Warn upon starting the first VM in a potentially
11608                          * insecure environment.
11609                          */
11610                         if (cpu_smt_control == CPU_SMT_ENABLED)
11611                                 pr_warn_once(L1TF_MSG_SMT);
11612                         if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
11613                                 pr_warn_once(L1TF_MSG_L1D);
11614                         break;
11615                 case L1TF_MITIGATION_FULL_FORCE:
11616                         /* Flush is enforced */
11617                         break;
11618                 }
11619         }
11620         return 0;
11621 }
11622
11623 static void __init vmx_check_processor_compat(void *rtn)
11624 {
11625         struct vmcs_config vmcs_conf;
11626
11627         *(int *)rtn = 0;
11628         if (setup_vmcs_config(&vmcs_conf) < 0)
11629                 *(int *)rtn = -EIO;
11630         nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, enable_apicv);
11631         if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
11632                 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
11633                                 smp_processor_id());
11634                 *(int *)rtn = -EIO;
11635         }
11636 }
11637
11638 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
11639 {
11640         u8 cache;
11641         u64 ipat = 0;
11642
11643         /* For VT-d and EPT combination
11644          * 1. MMIO: always map as UC
11645          * 2. EPT with VT-d:
11646          *   a. VT-d without snooping control feature: can't guarantee the
11647          *      result, try to trust guest.
11648          *   b. VT-d with snooping control feature: snooping control feature of
11649          *      VT-d engine can guarantee the cache correctness. Just set it
11650          *      to WB to keep consistent with host. So the same as item 3.
11651          * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
11652          *    consistent with host MTRR
11653          */
11654         if (is_mmio) {
11655                 cache = MTRR_TYPE_UNCACHABLE;
11656                 goto exit;
11657         }
11658
11659         if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
11660                 ipat = VMX_EPT_IPAT_BIT;
11661                 cache = MTRR_TYPE_WRBACK;
11662                 goto exit;
11663         }
11664
11665         if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
11666                 ipat = VMX_EPT_IPAT_BIT;
11667                 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
11668                         cache = MTRR_TYPE_WRBACK;
11669                 else
11670                         cache = MTRR_TYPE_UNCACHABLE;
11671                 goto exit;
11672         }
11673
11674         cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
11675
11676 exit:
11677         return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
11678 }
11679
11680 static int vmx_get_lpage_level(void)
11681 {
11682         if (enable_ept && !cpu_has_vmx_ept_1g_page())
11683                 return PT_DIRECTORY_LEVEL;
11684         else
11685                 /* For shadow and EPT supported 1GB page */
11686                 return PT_PDPE_LEVEL;
11687 }
11688
11689 static void vmcs_set_secondary_exec_control(u32 new_ctl)
11690 {
11691         /*
11692          * These bits in the secondary execution controls field
11693          * are dynamic, the others are mostly based on the hypervisor
11694          * architecture and the guest's CPUID.  Do not touch the
11695          * dynamic bits.
11696          */
11697         u32 mask =
11698                 SECONDARY_EXEC_SHADOW_VMCS |
11699                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
11700                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
11701                 SECONDARY_EXEC_DESC;
11702
11703         u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
11704
11705         vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
11706                      (new_ctl & ~mask) | (cur_ctl & mask));
11707 }
11708
11709 /*
11710  * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
11711  * (indicating "allowed-1") if they are supported in the guest's CPUID.
11712  */
11713 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
11714 {
11715         struct vcpu_vmx *vmx = to_vmx(vcpu);
11716         struct kvm_cpuid_entry2 *entry;
11717
11718         vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
11719         vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
11720
11721 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do {            \
11722         if (entry && (entry->_reg & (_cpuid_mask)))                     \
11723                 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask);     \
11724 } while (0)
11725
11726         entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
11727         cr4_fixed1_update(X86_CR4_VME,        edx, bit(X86_FEATURE_VME));
11728         cr4_fixed1_update(X86_CR4_PVI,        edx, bit(X86_FEATURE_VME));
11729         cr4_fixed1_update(X86_CR4_TSD,        edx, bit(X86_FEATURE_TSC));
11730         cr4_fixed1_update(X86_CR4_DE,         edx, bit(X86_FEATURE_DE));
11731         cr4_fixed1_update(X86_CR4_PSE,        edx, bit(X86_FEATURE_PSE));
11732         cr4_fixed1_update(X86_CR4_PAE,        edx, bit(X86_FEATURE_PAE));
11733         cr4_fixed1_update(X86_CR4_MCE,        edx, bit(X86_FEATURE_MCE));
11734         cr4_fixed1_update(X86_CR4_PGE,        edx, bit(X86_FEATURE_PGE));
11735         cr4_fixed1_update(X86_CR4_OSFXSR,     edx, bit(X86_FEATURE_FXSR));
11736         cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
11737         cr4_fixed1_update(X86_CR4_VMXE,       ecx, bit(X86_FEATURE_VMX));
11738         cr4_fixed1_update(X86_CR4_SMXE,       ecx, bit(X86_FEATURE_SMX));
11739         cr4_fixed1_update(X86_CR4_PCIDE,      ecx, bit(X86_FEATURE_PCID));
11740         cr4_fixed1_update(X86_CR4_OSXSAVE,    ecx, bit(X86_FEATURE_XSAVE));
11741
11742         entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
11743         cr4_fixed1_update(X86_CR4_FSGSBASE,   ebx, bit(X86_FEATURE_FSGSBASE));
11744         cr4_fixed1_update(X86_CR4_SMEP,       ebx, bit(X86_FEATURE_SMEP));
11745         cr4_fixed1_update(X86_CR4_SMAP,       ebx, bit(X86_FEATURE_SMAP));
11746         cr4_fixed1_update(X86_CR4_PKE,        ecx, bit(X86_FEATURE_PKU));
11747         cr4_fixed1_update(X86_CR4_UMIP,       ecx, bit(X86_FEATURE_UMIP));
11748
11749 #undef cr4_fixed1_update
11750 }
11751
11752 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
11753 {
11754         struct vcpu_vmx *vmx = to_vmx(vcpu);
11755
11756         if (kvm_mpx_supported()) {
11757                 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
11758
11759                 if (mpx_enabled) {
11760                         vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
11761                         vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
11762                 } else {
11763                         vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
11764                         vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
11765                 }
11766         }
11767 }
11768
11769 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
11770 {
11771         struct vcpu_vmx *vmx = to_vmx(vcpu);
11772
11773         if (cpu_has_secondary_exec_ctrls()) {
11774                 vmx_compute_secondary_exec_control(vmx);
11775                 vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
11776         }
11777
11778         if (nested_vmx_allowed(vcpu))
11779                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
11780                         FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
11781         else
11782                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
11783                         ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
11784
11785         if (nested_vmx_allowed(vcpu)) {
11786                 nested_vmx_cr_fixed1_bits_update(vcpu);
11787                 nested_vmx_entry_exit_ctls_update(vcpu);
11788         }
11789 }
11790
11791 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
11792 {
11793         if (func == 1 && nested)
11794                 entry->ecx |= bit(X86_FEATURE_VMX);
11795 }
11796
11797 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
11798                 struct x86_exception *fault)
11799 {
11800         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11801         struct vcpu_vmx *vmx = to_vmx(vcpu);
11802         u32 exit_reason;
11803         unsigned long exit_qualification = vcpu->arch.exit_qualification;
11804
11805         if (vmx->nested.pml_full) {
11806                 exit_reason = EXIT_REASON_PML_FULL;
11807                 vmx->nested.pml_full = false;
11808                 exit_qualification &= INTR_INFO_UNBLOCK_NMI;
11809         } else if (fault->error_code & PFERR_RSVD_MASK)
11810                 exit_reason = EXIT_REASON_EPT_MISCONFIG;
11811         else
11812                 exit_reason = EXIT_REASON_EPT_VIOLATION;
11813
11814         nested_vmx_vmexit(vcpu, exit_reason, 0, exit_qualification);
11815         vmcs12->guest_physical_address = fault->address;
11816 }
11817
11818 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu)
11819 {
11820         return nested_ept_get_cr3(vcpu) & VMX_EPTP_AD_ENABLE_BIT;
11821 }
11822
11823 /* Callbacks for nested_ept_init_mmu_context: */
11824
11825 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
11826 {
11827         /* return the page table to be shadowed - in our case, EPT12 */
11828         return get_vmcs12(vcpu)->ept_pointer;
11829 }
11830
11831 static void nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
11832 {
11833         WARN_ON(mmu_is_nested(vcpu));
11834
11835         vcpu->arch.mmu = &vcpu->arch.guest_mmu;
11836         kvm_init_shadow_ept_mmu(vcpu,
11837                         to_vmx(vcpu)->nested.msrs.ept_caps &
11838                         VMX_EPT_EXECUTE_ONLY_BIT,
11839                         nested_ept_ad_enabled(vcpu),
11840                         nested_ept_get_cr3(vcpu));
11841         vcpu->arch.mmu->set_cr3           = vmx_set_cr3;
11842         vcpu->arch.mmu->get_cr3           = nested_ept_get_cr3;
11843         vcpu->arch.mmu->inject_page_fault = nested_ept_inject_page_fault;
11844         vcpu->arch.mmu->get_pdptr         = kvm_pdptr_read;
11845
11846         vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
11847 }
11848
11849 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
11850 {
11851         vcpu->arch.mmu = &vcpu->arch.root_mmu;
11852         vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
11853 }
11854
11855 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
11856                                             u16 error_code)
11857 {
11858         bool inequality, bit;
11859
11860         bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
11861         inequality =
11862                 (error_code & vmcs12->page_fault_error_code_mask) !=
11863                  vmcs12->page_fault_error_code_match;
11864         return inequality ^ bit;
11865 }
11866
11867 static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
11868                 struct x86_exception *fault)
11869 {
11870         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11871
11872         WARN_ON(!is_guest_mode(vcpu));
11873
11874         if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code) &&
11875                 !to_vmx(vcpu)->nested.nested_run_pending) {
11876                 vmcs12->vm_exit_intr_error_code = fault->error_code;
11877                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
11878                                   PF_VECTOR | INTR_TYPE_HARD_EXCEPTION |
11879                                   INTR_INFO_DELIVER_CODE_MASK | INTR_INFO_VALID_MASK,
11880                                   fault->address);
11881         } else {
11882                 kvm_inject_page_fault(vcpu, fault);
11883         }
11884 }
11885
11886 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
11887                                                  struct vmcs12 *vmcs12);
11888
11889 static void nested_get_vmcs12_pages(struct kvm_vcpu *vcpu)
11890 {
11891         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11892         struct vcpu_vmx *vmx = to_vmx(vcpu);
11893         struct page *page;
11894         u64 hpa;
11895
11896         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
11897                 /*
11898                  * Translate L1 physical address to host physical
11899                  * address for vmcs02. Keep the page pinned, so this
11900                  * physical address remains valid. We keep a reference
11901                  * to it so we can release it later.
11902                  */
11903                 if (vmx->nested.apic_access_page) { /* shouldn't happen */
11904                         kvm_release_page_dirty(vmx->nested.apic_access_page);
11905                         vmx->nested.apic_access_page = NULL;
11906                 }
11907                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->apic_access_addr);
11908                 /*
11909                  * If translation failed, no matter: This feature asks
11910                  * to exit when accessing the given address, and if it
11911                  * can never be accessed, this feature won't do
11912                  * anything anyway.
11913                  */
11914                 if (!is_error_page(page)) {
11915                         vmx->nested.apic_access_page = page;
11916                         hpa = page_to_phys(vmx->nested.apic_access_page);
11917                         vmcs_write64(APIC_ACCESS_ADDR, hpa);
11918                 } else {
11919                         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
11920                                         SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
11921                 }
11922         }
11923
11924         if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
11925                 if (vmx->nested.virtual_apic_page) { /* shouldn't happen */
11926                         kvm_release_page_dirty(vmx->nested.virtual_apic_page);
11927                         vmx->nested.virtual_apic_page = NULL;
11928                 }
11929                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->virtual_apic_page_addr);
11930
11931                 /*
11932                  * If translation failed, VM entry will fail because
11933                  * prepare_vmcs02 set VIRTUAL_APIC_PAGE_ADDR to -1ull.
11934                  * Failing the vm entry is _not_ what the processor
11935                  * does but it's basically the only possibility we
11936                  * have.  We could still enter the guest if CR8 load
11937                  * exits are enabled, CR8 store exits are enabled, and
11938                  * virtualize APIC access is disabled; in this case
11939                  * the processor would never use the TPR shadow and we
11940                  * could simply clear the bit from the execution
11941                  * control.  But such a configuration is useless, so
11942                  * let's keep the code simple.
11943                  */
11944                 if (!is_error_page(page)) {
11945                         vmx->nested.virtual_apic_page = page;
11946                         hpa = page_to_phys(vmx->nested.virtual_apic_page);
11947                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, hpa);
11948                 }
11949         }
11950
11951         if (nested_cpu_has_posted_intr(vmcs12)) {
11952                 if (vmx->nested.pi_desc_page) { /* shouldn't happen */
11953                         kunmap(vmx->nested.pi_desc_page);
11954                         kvm_release_page_dirty(vmx->nested.pi_desc_page);
11955                         vmx->nested.pi_desc_page = NULL;
11956                 }
11957                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->posted_intr_desc_addr);
11958                 if (is_error_page(page))
11959                         return;
11960                 vmx->nested.pi_desc_page = page;
11961                 vmx->nested.pi_desc = kmap(vmx->nested.pi_desc_page);
11962                 vmx->nested.pi_desc =
11963                         (struct pi_desc *)((void *)vmx->nested.pi_desc +
11964                         (unsigned long)(vmcs12->posted_intr_desc_addr &
11965                         (PAGE_SIZE - 1)));
11966                 vmcs_write64(POSTED_INTR_DESC_ADDR,
11967                         page_to_phys(vmx->nested.pi_desc_page) +
11968                         (unsigned long)(vmcs12->posted_intr_desc_addr &
11969                         (PAGE_SIZE - 1)));
11970         }
11971         if (nested_vmx_prepare_msr_bitmap(vcpu, vmcs12))
11972                 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
11973                               CPU_BASED_USE_MSR_BITMAPS);
11974         else
11975                 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
11976                                 CPU_BASED_USE_MSR_BITMAPS);
11977 }
11978
11979 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
11980 {
11981         u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
11982         struct vcpu_vmx *vmx = to_vmx(vcpu);
11983
11984         /*
11985          * A timer value of zero is architecturally guaranteed to cause
11986          * a VMExit prior to executing any instructions in the guest.
11987          */
11988         if (preemption_timeout == 0) {
11989                 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
11990                 return;
11991         }
11992
11993         if (vcpu->arch.virtual_tsc_khz == 0)
11994                 return;
11995
11996         preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
11997         preemption_timeout *= 1000000;
11998         do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
11999         hrtimer_start(&vmx->nested.preemption_timer,
12000                       ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
12001 }
12002
12003 static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,
12004                                                struct vmcs12 *vmcs12)
12005 {
12006         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
12007                 return 0;
12008
12009         if (!page_address_valid(vcpu, vmcs12->io_bitmap_a) ||
12010             !page_address_valid(vcpu, vmcs12->io_bitmap_b))
12011                 return -EINVAL;
12012
12013         return 0;
12014 }
12015
12016 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
12017                                                 struct vmcs12 *vmcs12)
12018 {
12019         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
12020                 return 0;
12021
12022         if (!page_address_valid(vcpu, vmcs12->msr_bitmap))
12023                 return -EINVAL;
12024
12025         return 0;
12026 }
12027
12028 static int nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu *vcpu,
12029                                                 struct vmcs12 *vmcs12)
12030 {
12031         if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
12032                 return 0;
12033
12034         if (!page_address_valid(vcpu, vmcs12->virtual_apic_page_addr))
12035                 return -EINVAL;
12036
12037         return 0;
12038 }
12039
12040 /*
12041  * Merge L0's and L1's MSR bitmap, return false to indicate that
12042  * we do not use the hardware.
12043  */
12044 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
12045                                                  struct vmcs12 *vmcs12)
12046 {
12047         int msr;
12048         struct page *page;
12049         unsigned long *msr_bitmap_l1;
12050         unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.vmcs02.msr_bitmap;
12051         /*
12052          * pred_cmd & spec_ctrl are trying to verify two things:
12053          *
12054          * 1. L0 gave a permission to L1 to actually passthrough the MSR. This
12055          *    ensures that we do not accidentally generate an L02 MSR bitmap
12056          *    from the L12 MSR bitmap that is too permissive.
12057          * 2. That L1 or L2s have actually used the MSR. This avoids
12058          *    unnecessarily merging of the bitmap if the MSR is unused. This
12059          *    works properly because we only update the L01 MSR bitmap lazily.
12060          *    So even if L0 should pass L1 these MSRs, the L01 bitmap is only
12061          *    updated to reflect this when L1 (or its L2s) actually write to
12062          *    the MSR.
12063          */
12064         bool pred_cmd = !msr_write_intercepted_l01(vcpu, MSR_IA32_PRED_CMD);
12065         bool spec_ctrl = !msr_write_intercepted_l01(vcpu, MSR_IA32_SPEC_CTRL);
12066
12067         /* Nothing to do if the MSR bitmap is not in use.  */
12068         if (!cpu_has_vmx_msr_bitmap() ||
12069             !nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
12070                 return false;
12071
12072         if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
12073             !pred_cmd && !spec_ctrl)
12074                 return false;
12075
12076         page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->msr_bitmap);
12077         if (is_error_page(page))
12078                 return false;
12079
12080         msr_bitmap_l1 = (unsigned long *)kmap(page);
12081         if (nested_cpu_has_apic_reg_virt(vmcs12)) {
12082                 /*
12083                  * L0 need not intercept reads for MSRs between 0x800 and 0x8ff, it
12084                  * just lets the processor take the value from the virtual-APIC page;
12085                  * take those 256 bits directly from the L1 bitmap.
12086                  */
12087                 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
12088                         unsigned word = msr / BITS_PER_LONG;
12089                         msr_bitmap_l0[word] = msr_bitmap_l1[word];
12090                         msr_bitmap_l0[word + (0x800 / sizeof(long))] = ~0;
12091                 }
12092         } else {
12093                 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
12094                         unsigned word = msr / BITS_PER_LONG;
12095                         msr_bitmap_l0[word] = ~0;
12096                         msr_bitmap_l0[word + (0x800 / sizeof(long))] = ~0;
12097                 }
12098         }
12099
12100         nested_vmx_disable_intercept_for_msr(
12101                 msr_bitmap_l1, msr_bitmap_l0,
12102                 X2APIC_MSR(APIC_TASKPRI),
12103                 MSR_TYPE_W);
12104
12105         if (nested_cpu_has_vid(vmcs12)) {
12106                 nested_vmx_disable_intercept_for_msr(
12107                         msr_bitmap_l1, msr_bitmap_l0,
12108                         X2APIC_MSR(APIC_EOI),
12109                         MSR_TYPE_W);
12110                 nested_vmx_disable_intercept_for_msr(
12111                         msr_bitmap_l1, msr_bitmap_l0,
12112                         X2APIC_MSR(APIC_SELF_IPI),
12113                         MSR_TYPE_W);
12114         }
12115
12116         if (spec_ctrl)
12117                 nested_vmx_disable_intercept_for_msr(
12118                                         msr_bitmap_l1, msr_bitmap_l0,
12119                                         MSR_IA32_SPEC_CTRL,
12120                                         MSR_TYPE_R | MSR_TYPE_W);
12121
12122         if (pred_cmd)
12123                 nested_vmx_disable_intercept_for_msr(
12124                                         msr_bitmap_l1, msr_bitmap_l0,
12125                                         MSR_IA32_PRED_CMD,
12126                                         MSR_TYPE_W);
12127
12128         kunmap(page);
12129         kvm_release_page_clean(page);
12130
12131         return true;
12132 }
12133
12134 static void nested_cache_shadow_vmcs12(struct kvm_vcpu *vcpu,
12135                                        struct vmcs12 *vmcs12)
12136 {
12137         struct vmcs12 *shadow;
12138         struct page *page;
12139
12140         if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
12141             vmcs12->vmcs_link_pointer == -1ull)
12142                 return;
12143
12144         shadow = get_shadow_vmcs12(vcpu);
12145         page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->vmcs_link_pointer);
12146
12147         memcpy(shadow, kmap(page), VMCS12_SIZE);
12148
12149         kunmap(page);
12150         kvm_release_page_clean(page);
12151 }
12152
12153 static void nested_flush_cached_shadow_vmcs12(struct kvm_vcpu *vcpu,
12154                                               struct vmcs12 *vmcs12)
12155 {
12156         struct vcpu_vmx *vmx = to_vmx(vcpu);
12157
12158         if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
12159             vmcs12->vmcs_link_pointer == -1ull)
12160                 return;
12161
12162         kvm_write_guest(vmx->vcpu.kvm, vmcs12->vmcs_link_pointer,
12163                         get_shadow_vmcs12(vcpu), VMCS12_SIZE);
12164 }
12165
12166 static int nested_vmx_check_apic_access_controls(struct kvm_vcpu *vcpu,
12167                                           struct vmcs12 *vmcs12)
12168 {
12169         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
12170             !page_address_valid(vcpu, vmcs12->apic_access_addr))
12171                 return -EINVAL;
12172         else
12173                 return 0;
12174 }
12175
12176 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
12177                                            struct vmcs12 *vmcs12)
12178 {
12179         if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
12180             !nested_cpu_has_apic_reg_virt(vmcs12) &&
12181             !nested_cpu_has_vid(vmcs12) &&
12182             !nested_cpu_has_posted_intr(vmcs12))
12183                 return 0;
12184
12185         /*
12186          * If virtualize x2apic mode is enabled,
12187          * virtualize apic access must be disabled.
12188          */
12189         if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
12190             nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
12191                 return -EINVAL;
12192
12193         /*
12194          * If virtual interrupt delivery is enabled,
12195          * we must exit on external interrupts.
12196          */
12197         if (nested_cpu_has_vid(vmcs12) &&
12198            !nested_exit_on_intr(vcpu))
12199                 return -EINVAL;
12200
12201         /*
12202          * bits 15:8 should be zero in posted_intr_nv,
12203          * the descriptor address has been already checked
12204          * in nested_get_vmcs12_pages.
12205          *
12206          * bits 5:0 of posted_intr_desc_addr should be zero.
12207          */
12208         if (nested_cpu_has_posted_intr(vmcs12) &&
12209            (!nested_cpu_has_vid(vmcs12) ||
12210             !nested_exit_intr_ack_set(vcpu) ||
12211             (vmcs12->posted_intr_nv & 0xff00) ||
12212             (vmcs12->posted_intr_desc_addr & 0x3f) ||
12213             (vmcs12->posted_intr_desc_addr >> cpuid_maxphyaddr(vcpu))))
12214                 return -EINVAL;
12215
12216         /* tpr shadow is needed by all apicv features. */
12217         if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
12218                 return -EINVAL;
12219
12220         return 0;
12221 }
12222
12223 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
12224                                        unsigned long count_field,
12225                                        unsigned long addr_field)
12226 {
12227         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
12228         int maxphyaddr;
12229         u64 count, addr;
12230
12231         if (vmcs12_read_any(vmcs12, count_field, &count) ||
12232             vmcs12_read_any(vmcs12, addr_field, &addr)) {
12233                 WARN_ON(1);
12234                 return -EINVAL;
12235         }
12236         if (count == 0)
12237                 return 0;
12238         maxphyaddr = cpuid_maxphyaddr(vcpu);
12239         if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
12240             (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
12241                 pr_debug_ratelimited(
12242                         "nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
12243                         addr_field, maxphyaddr, count, addr);
12244                 return -EINVAL;
12245         }
12246         return 0;
12247 }
12248
12249 static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
12250                                                 struct vmcs12 *vmcs12)
12251 {
12252         if (vmcs12->vm_exit_msr_load_count == 0 &&
12253             vmcs12->vm_exit_msr_store_count == 0 &&
12254             vmcs12->vm_entry_msr_load_count == 0)
12255                 return 0; /* Fast path */
12256         if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
12257                                         VM_EXIT_MSR_LOAD_ADDR) ||
12258             nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
12259                                         VM_EXIT_MSR_STORE_ADDR) ||
12260             nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
12261                                         VM_ENTRY_MSR_LOAD_ADDR))
12262                 return -EINVAL;
12263         return 0;
12264 }
12265
12266 static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
12267                                          struct vmcs12 *vmcs12)
12268 {
12269         if (!nested_cpu_has_pml(vmcs12))
12270                 return 0;
12271
12272         if (!nested_cpu_has_ept(vmcs12) ||
12273             !page_address_valid(vcpu, vmcs12->pml_address))
12274                 return -EINVAL;
12275
12276         return 0;
12277 }
12278
12279 static int nested_vmx_check_shadow_vmcs_controls(struct kvm_vcpu *vcpu,
12280                                                  struct vmcs12 *vmcs12)
12281 {
12282         if (!nested_cpu_has_shadow_vmcs(vmcs12))
12283                 return 0;
12284
12285         if (!page_address_valid(vcpu, vmcs12->vmread_bitmap) ||
12286             !page_address_valid(vcpu, vmcs12->vmwrite_bitmap))
12287                 return -EINVAL;
12288
12289         return 0;
12290 }
12291
12292 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
12293                                        struct vmx_msr_entry *e)
12294 {
12295         /* x2APIC MSR accesses are not allowed */
12296         if (vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8)
12297                 return -EINVAL;
12298         if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
12299             e->index == MSR_IA32_UCODE_REV)
12300                 return -EINVAL;
12301         if (e->reserved != 0)
12302                 return -EINVAL;
12303         return 0;
12304 }
12305
12306 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
12307                                      struct vmx_msr_entry *e)
12308 {
12309         if (e->index == MSR_FS_BASE ||
12310             e->index == MSR_GS_BASE ||
12311             e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
12312             nested_vmx_msr_check_common(vcpu, e))
12313                 return -EINVAL;
12314         return 0;
12315 }
12316
12317 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
12318                                       struct vmx_msr_entry *e)
12319 {
12320         if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
12321             nested_vmx_msr_check_common(vcpu, e))
12322                 return -EINVAL;
12323         return 0;
12324 }
12325
12326 /*
12327  * Load guest's/host's msr at nested entry/exit.
12328  * return 0 for success, entry index for failure.
12329  */
12330 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
12331 {
12332         u32 i;
12333         struct vmx_msr_entry e;
12334         struct msr_data msr;
12335
12336         msr.host_initiated = false;
12337         for (i = 0; i < count; i++) {
12338                 if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
12339                                         &e, sizeof(e))) {
12340                         pr_debug_ratelimited(
12341                                 "%s cannot read MSR entry (%u, 0x%08llx)\n",
12342                                 __func__, i, gpa + i * sizeof(e));
12343                         goto fail;
12344                 }
12345                 if (nested_vmx_load_msr_check(vcpu, &e)) {
12346                         pr_debug_ratelimited(
12347                                 "%s check failed (%u, 0x%x, 0x%x)\n",
12348                                 __func__, i, e.index, e.reserved);
12349                         goto fail;
12350                 }
12351                 msr.index = e.index;
12352                 msr.data = e.value;
12353                 if (kvm_set_msr(vcpu, &msr)) {
12354                         pr_debug_ratelimited(
12355                                 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
12356                                 __func__, i, e.index, e.value);
12357                         goto fail;
12358                 }
12359         }
12360         return 0;
12361 fail:
12362         return i + 1;
12363 }
12364
12365 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
12366 {
12367         u32 i;
12368         struct vmx_msr_entry e;
12369
12370         for (i = 0; i < count; i++) {
12371                 struct msr_data msr_info;
12372                 if (kvm_vcpu_read_guest(vcpu,
12373                                         gpa + i * sizeof(e),
12374                                         &e, 2 * sizeof(u32))) {
12375                         pr_debug_ratelimited(
12376                                 "%s cannot read MSR entry (%u, 0x%08llx)\n",
12377                                 __func__, i, gpa + i * sizeof(e));
12378                         return -EINVAL;
12379                 }
12380                 if (nested_vmx_store_msr_check(vcpu, &e)) {
12381                         pr_debug_ratelimited(
12382                                 "%s check failed (%u, 0x%x, 0x%x)\n",
12383                                 __func__, i, e.index, e.reserved);
12384                         return -EINVAL;
12385                 }
12386                 msr_info.host_initiated = false;
12387                 msr_info.index = e.index;
12388                 if (kvm_get_msr(vcpu, &msr_info)) {
12389                         pr_debug_ratelimited(
12390                                 "%s cannot read MSR (%u, 0x%x)\n",
12391                                 __func__, i, e.index);
12392                         return -EINVAL;
12393                 }
12394                 if (kvm_vcpu_write_guest(vcpu,
12395                                          gpa + i * sizeof(e) +
12396                                              offsetof(struct vmx_msr_entry, value),
12397                                          &msr_info.data, sizeof(msr_info.data))) {
12398                         pr_debug_ratelimited(
12399                                 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
12400                                 __func__, i, e.index, msr_info.data);
12401                         return -EINVAL;
12402                 }
12403         }
12404         return 0;
12405 }
12406
12407 static bool nested_cr3_valid(struct kvm_vcpu *vcpu, unsigned long val)
12408 {
12409         unsigned long invalid_mask;
12410
12411         invalid_mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
12412         return (val & invalid_mask) == 0;
12413 }
12414
12415 /*
12416  * Load guest's/host's cr3 at nested entry/exit. nested_ept is true if we are
12417  * emulating VM entry into a guest with EPT enabled.
12418  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
12419  * is assigned to entry_failure_code on failure.
12420  */
12421 static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool nested_ept,
12422                                u32 *entry_failure_code)
12423 {
12424         if (cr3 != kvm_read_cr3(vcpu) || (!nested_ept && pdptrs_changed(vcpu))) {
12425                 if (!nested_cr3_valid(vcpu, cr3)) {
12426                         *entry_failure_code = ENTRY_FAIL_DEFAULT;
12427                         return 1;
12428                 }
12429
12430                 /*
12431                  * If PAE paging and EPT are both on, CR3 is not used by the CPU and
12432                  * must not be dereferenced.
12433                  */
12434                 if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu) &&
12435                     !nested_ept) {
12436                         if (!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)) {
12437                                 *entry_failure_code = ENTRY_FAIL_PDPTE;
12438                                 return 1;
12439                         }
12440                 }
12441         }
12442
12443         if (!nested_ept)
12444                 kvm_mmu_new_cr3(vcpu, cr3, false);
12445
12446         vcpu->arch.cr3 = cr3;
12447         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
12448
12449         kvm_init_mmu(vcpu, false);
12450
12451         return 0;
12452 }
12453
12454 /*
12455  * Returns if KVM is able to config CPU to tag TLB entries
12456  * populated by L2 differently than TLB entries populated
12457  * by L1.
12458  *
12459  * If L1 uses EPT, then TLB entries are tagged with different EPTP.
12460  *
12461  * If L1 uses VPID and we allocated a vpid02, TLB entries are tagged
12462  * with different VPID (L1 entries are tagged with vmx->vpid
12463  * while L2 entries are tagged with vmx->nested.vpid02).
12464  */
12465 static bool nested_has_guest_tlb_tag(struct kvm_vcpu *vcpu)
12466 {
12467         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
12468
12469         return nested_cpu_has_ept(vmcs12) ||
12470                (nested_cpu_has_vpid(vmcs12) && to_vmx(vcpu)->nested.vpid02);
12471 }
12472
12473 static u64 nested_vmx_calc_efer(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
12474 {
12475         if (vmx->nested.nested_run_pending &&
12476             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
12477                 return vmcs12->guest_ia32_efer;
12478         else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
12479                 return vmx->vcpu.arch.efer | (EFER_LMA | EFER_LME);
12480         else
12481                 return vmx->vcpu.arch.efer & ~(EFER_LMA | EFER_LME);
12482 }
12483
12484 static void prepare_vmcs02_constant_state(struct vcpu_vmx *vmx)
12485 {
12486         /*
12487          * If vmcs02 hasn't been initialized, set the constant vmcs02 state
12488          * according to L0's settings (vmcs12 is irrelevant here).  Host
12489          * fields that come from L0 and are not constant, e.g. HOST_CR3,
12490          * will be set as needed prior to VMLAUNCH/VMRESUME.
12491          */
12492         if (vmx->nested.vmcs02_initialized)
12493                 return;
12494         vmx->nested.vmcs02_initialized = true;
12495
12496         /*
12497          * We don't care what the EPTP value is we just need to guarantee
12498          * it's valid so we don't get a false positive when doing early
12499          * consistency checks.
12500          */
12501         if (enable_ept && nested_early_check)
12502                 vmcs_write64(EPT_POINTER, construct_eptp(&vmx->vcpu, 0));
12503
12504         /* All VMFUNCs are currently emulated through L0 vmexits.  */
12505         if (cpu_has_vmx_vmfunc())
12506                 vmcs_write64(VM_FUNCTION_CONTROL, 0);
12507
12508         if (cpu_has_vmx_posted_intr())
12509                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
12510
12511         if (cpu_has_vmx_msr_bitmap())
12512                 vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
12513
12514         if (enable_pml)
12515                 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
12516
12517         /*
12518          * Set the MSR load/store lists to match L0's settings.  Only the
12519          * addresses are constant (for vmcs02), the counts can change based
12520          * on L2's behavior, e.g. switching to/from long mode.
12521          */
12522         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
12523         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
12524         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
12525
12526         vmx_set_constant_host_state(vmx);
12527 }
12528
12529 static void prepare_vmcs02_early_full(struct vcpu_vmx *vmx,
12530                                       struct vmcs12 *vmcs12)
12531 {
12532         prepare_vmcs02_constant_state(vmx);
12533
12534         vmcs_write64(VMCS_LINK_POINTER, -1ull);
12535
12536         if (enable_vpid) {
12537                 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02)
12538                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
12539                 else
12540                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
12541         }
12542 }
12543
12544 static void prepare_vmcs02_early(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
12545 {
12546         u32 exec_control, vmcs12_exec_ctrl;
12547         u64 guest_efer = nested_vmx_calc_efer(vmx, vmcs12);
12548
12549         if (vmx->nested.dirty_vmcs12 || vmx->nested.hv_evmcs)
12550                 prepare_vmcs02_early_full(vmx, vmcs12);
12551
12552         /*
12553          * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
12554          * entry, but only if the current (host) sp changed from the value
12555          * we wrote last (vmx->host_rsp).  This cache is no longer relevant
12556          * if we switch vmcs, and rather than hold a separate cache per vmcs,
12557          * here we just force the write to happen on entry.  host_rsp will
12558          * also be written unconditionally by nested_vmx_check_vmentry_hw()
12559          * if we are doing early consistency checks via hardware.
12560          */
12561         vmx->host_rsp = 0;
12562
12563         /*
12564          * PIN CONTROLS
12565          */
12566         exec_control = vmcs12->pin_based_vm_exec_control;
12567
12568         /* Preemption timer setting is computed directly in vmx_vcpu_run.  */
12569         exec_control |= vmcs_config.pin_based_exec_ctrl;
12570         exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
12571         vmx->loaded_vmcs->hv_timer_armed = false;
12572
12573         /* Posted interrupts setting is only taken from vmcs12.  */
12574         if (nested_cpu_has_posted_intr(vmcs12)) {
12575                 vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
12576                 vmx->nested.pi_pending = false;
12577         } else {
12578                 exec_control &= ~PIN_BASED_POSTED_INTR;
12579         }
12580         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
12581
12582         /*
12583          * EXEC CONTROLS
12584          */
12585         exec_control = vmx_exec_control(vmx); /* L0's desires */
12586         exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
12587         exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
12588         exec_control &= ~CPU_BASED_TPR_SHADOW;
12589         exec_control |= vmcs12->cpu_based_vm_exec_control;
12590
12591         /*
12592          * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR. Later, if
12593          * nested_get_vmcs12_pages can't fix it up, the illegal value
12594          * will result in a VM entry failure.
12595          */
12596         if (exec_control & CPU_BASED_TPR_SHADOW) {
12597                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
12598                 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
12599         } else {
12600 #ifdef CONFIG_X86_64
12601                 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
12602                                 CPU_BASED_CR8_STORE_EXITING;
12603 #endif
12604         }
12605
12606         /*
12607          * A vmexit (to either L1 hypervisor or L0 userspace) is always needed
12608          * for I/O port accesses.
12609          */
12610         exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
12611         exec_control |= CPU_BASED_UNCOND_IO_EXITING;
12612         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
12613
12614         /*
12615          * SECONDARY EXEC CONTROLS
12616          */
12617         if (cpu_has_secondary_exec_ctrls()) {
12618                 exec_control = vmx->secondary_exec_control;
12619
12620                 /* Take the following fields only from vmcs12 */
12621                 exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
12622                                   SECONDARY_EXEC_ENABLE_INVPCID |
12623                                   SECONDARY_EXEC_RDTSCP |
12624                                   SECONDARY_EXEC_XSAVES |
12625                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
12626                                   SECONDARY_EXEC_APIC_REGISTER_VIRT |
12627                                   SECONDARY_EXEC_ENABLE_VMFUNC);
12628                 if (nested_cpu_has(vmcs12,
12629                                    CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
12630                         vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
12631                                 ~SECONDARY_EXEC_ENABLE_PML;
12632                         exec_control |= vmcs12_exec_ctrl;
12633                 }
12634
12635                 /* VMCS shadowing for L2 is emulated for now */
12636                 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
12637
12638                 if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
12639                         vmcs_write16(GUEST_INTR_STATUS,
12640                                 vmcs12->guest_intr_status);
12641
12642                 /*
12643                  * Write an illegal value to APIC_ACCESS_ADDR. Later,
12644                  * nested_get_vmcs12_pages will either fix it up or
12645                  * remove the VM execution control.
12646                  */
12647                 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
12648                         vmcs_write64(APIC_ACCESS_ADDR, -1ull);
12649
12650                 if (exec_control & SECONDARY_EXEC_ENCLS_EXITING)
12651                         vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
12652
12653                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
12654         }
12655
12656         /*
12657          * ENTRY CONTROLS
12658          *
12659          * vmcs12's VM_{ENTRY,EXIT}_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE
12660          * are emulated by vmx_set_efer() in prepare_vmcs02(), but speculate
12661          * on the related bits (if supported by the CPU) in the hope that
12662          * we can avoid VMWrites during vmx_set_efer().
12663          */
12664         exec_control = (vmcs12->vm_entry_controls | vmcs_config.vmentry_ctrl) &
12665                         ~VM_ENTRY_IA32E_MODE & ~VM_ENTRY_LOAD_IA32_EFER;
12666         if (cpu_has_load_ia32_efer) {
12667                 if (guest_efer & EFER_LMA)
12668                         exec_control |= VM_ENTRY_IA32E_MODE;
12669                 if (guest_efer != host_efer)
12670                         exec_control |= VM_ENTRY_LOAD_IA32_EFER;
12671         }
12672         vm_entry_controls_init(vmx, exec_control);
12673
12674         /*
12675          * EXIT CONTROLS
12676          *
12677          * L2->L1 exit controls are emulated - the hardware exit is to L0 so
12678          * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
12679          * bits may be modified by vmx_set_efer() in prepare_vmcs02().
12680          */
12681         exec_control = vmcs_config.vmexit_ctrl;
12682         if (cpu_has_load_ia32_efer && guest_efer != host_efer)
12683                 exec_control |= VM_EXIT_LOAD_IA32_EFER;
12684         vm_exit_controls_init(vmx, exec_control);
12685
12686         /*
12687          * Conceptually we want to copy the PML address and index from
12688          * vmcs01 here, and then back to vmcs01 on nested vmexit. But,
12689          * since we always flush the log on each vmexit and never change
12690          * the PML address (once set), this happens to be equivalent to
12691          * simply resetting the index in vmcs02.
12692          */
12693         if (enable_pml)
12694                 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
12695
12696         /*
12697          * Interrupt/Exception Fields
12698          */
12699         if (vmx->nested.nested_run_pending) {
12700                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
12701                              vmcs12->vm_entry_intr_info_field);
12702                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
12703                              vmcs12->vm_entry_exception_error_code);
12704                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
12705                              vmcs12->vm_entry_instruction_len);
12706                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
12707                              vmcs12->guest_interruptibility_info);
12708                 vmx->loaded_vmcs->nmi_known_unmasked =
12709                         !(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
12710         } else {
12711                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
12712         }
12713 }
12714
12715 static void prepare_vmcs02_full(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
12716 {
12717         struct hv_enlightened_vmcs *hv_evmcs = vmx->nested.hv_evmcs;
12718
12719         if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
12720                            HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2)) {
12721                 vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
12722                 vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
12723                 vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
12724                 vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
12725                 vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
12726                 vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
12727                 vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
12728                 vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
12729                 vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
12730                 vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
12731                 vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
12732                 vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
12733                 vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
12734                 vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
12735                 vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
12736                 vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
12737                 vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
12738                 vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
12739                 vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
12740                 vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
12741                 vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
12742                 vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
12743                 vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
12744                 vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
12745                 vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
12746                 vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
12747                 vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
12748                 vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
12749                 vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
12750                 vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
12751                 vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
12752                 vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
12753                 vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
12754                 vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
12755         }
12756
12757         if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
12758                            HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1)) {
12759                 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
12760                 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
12761                             vmcs12->guest_pending_dbg_exceptions);
12762                 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
12763                 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
12764
12765                 /*
12766                  * L1 may access the L2's PDPTR, so save them to construct
12767                  * vmcs12
12768                  */
12769                 if (enable_ept) {
12770                         vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
12771                         vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
12772                         vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
12773                         vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
12774                 }
12775         }
12776
12777         if (nested_cpu_has_xsaves(vmcs12))
12778                 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
12779
12780         /*
12781          * Whether page-faults are trapped is determined by a combination of
12782          * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
12783          * If enable_ept, L0 doesn't care about page faults and we should
12784          * set all of these to L1's desires. However, if !enable_ept, L0 does
12785          * care about (at least some) page faults, and because it is not easy
12786          * (if at all possible?) to merge L0 and L1's desires, we simply ask
12787          * to exit on each and every L2 page fault. This is done by setting
12788          * MASK=MATCH=0 and (see below) EB.PF=1.
12789          * Note that below we don't need special code to set EB.PF beyond the
12790          * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
12791          * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
12792          * !enable_ept, EB.PF is 1, so the "or" will always be 1.
12793          */
12794         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
12795                 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
12796         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
12797                 enable_ept ? vmcs12->page_fault_error_code_match : 0);
12798
12799         if (cpu_has_vmx_apicv()) {
12800                 vmcs_write64(EOI_EXIT_BITMAP0, vmcs12->eoi_exit_bitmap0);
12801                 vmcs_write64(EOI_EXIT_BITMAP1, vmcs12->eoi_exit_bitmap1);
12802                 vmcs_write64(EOI_EXIT_BITMAP2, vmcs12->eoi_exit_bitmap2);
12803                 vmcs_write64(EOI_EXIT_BITMAP3, vmcs12->eoi_exit_bitmap3);
12804         }
12805
12806         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
12807         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
12808
12809         set_cr4_guest_host_mask(vmx);
12810
12811         if (kvm_mpx_supported()) {
12812                 if (vmx->nested.nested_run_pending &&
12813                         (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
12814                         vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
12815                 else
12816                         vmcs_write64(GUEST_BNDCFGS, vmx->nested.vmcs01_guest_bndcfgs);
12817         }
12818 }
12819
12820 /*
12821  * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
12822  * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
12823  * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
12824  * guest in a way that will both be appropriate to L1's requests, and our
12825  * needs. In addition to modifying the active vmcs (which is vmcs02), this
12826  * function also has additional necessary side-effects, like setting various
12827  * vcpu->arch fields.
12828  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
12829  * is assigned to entry_failure_code on failure.
12830  */
12831 static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12832                           u32 *entry_failure_code)
12833 {
12834         struct vcpu_vmx *vmx = to_vmx(vcpu);
12835         struct hv_enlightened_vmcs *hv_evmcs = vmx->nested.hv_evmcs;
12836
12837         if (vmx->nested.dirty_vmcs12 || vmx->nested.hv_evmcs) {
12838                 prepare_vmcs02_full(vmx, vmcs12);
12839                 vmx->nested.dirty_vmcs12 = false;
12840         }
12841
12842         /*
12843          * First, the fields that are shadowed.  This must be kept in sync
12844          * with vmx_shadow_fields.h.
12845          */
12846         if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
12847                            HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2)) {
12848                 vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
12849                 vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
12850         }
12851
12852         if (vmx->nested.nested_run_pending &&
12853             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
12854                 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
12855                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
12856         } else {
12857                 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
12858                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
12859         }
12860         vmx_set_rflags(vcpu, vmcs12->guest_rflags);
12861
12862         vmx->nested.preemption_timer_expired = false;
12863         if (nested_cpu_has_preemption_timer(vmcs12))
12864                 vmx_start_preemption_timer(vcpu);
12865
12866         /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
12867          * bitwise-or of what L1 wants to trap for L2, and what we want to
12868          * trap. Note that CR0.TS also needs updating - we do this later.
12869          */
12870         update_exception_bitmap(vcpu);
12871         vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
12872         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
12873
12874         if (vmx->nested.nested_run_pending &&
12875             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
12876                 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
12877                 vcpu->arch.pat = vmcs12->guest_ia32_pat;
12878         } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
12879                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
12880         }
12881
12882         vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
12883
12884         if (kvm_has_tsc_control)
12885                 decache_tsc_multiplier(vmx);
12886
12887         if (enable_vpid) {
12888                 /*
12889                  * There is no direct mapping between vpid02 and vpid12, the
12890                  * vpid02 is per-vCPU for L0 and reused while the value of
12891                  * vpid12 is changed w/ one invvpid during nested vmentry.
12892                  * The vpid12 is allocated by L1 for L2, so it will not
12893                  * influence global bitmap(for vpid01 and vpid02 allocation)
12894                  * even if spawn a lot of nested vCPUs.
12895                  */
12896                 if (nested_cpu_has_vpid(vmcs12) && nested_has_guest_tlb_tag(vcpu)) {
12897                         if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
12898                                 vmx->nested.last_vpid = vmcs12->virtual_processor_id;
12899                                 __vmx_flush_tlb(vcpu, nested_get_vpid02(vcpu), false);
12900                         }
12901                 } else {
12902                         /*
12903                          * If L1 use EPT, then L0 needs to execute INVEPT on
12904                          * EPTP02 instead of EPTP01. Therefore, delay TLB
12905                          * flush until vmcs02->eptp is fully updated by
12906                          * KVM_REQ_LOAD_CR3. Note that this assumes
12907                          * KVM_REQ_TLB_FLUSH is evaluated after
12908                          * KVM_REQ_LOAD_CR3 in vcpu_enter_guest().
12909                          */
12910                         kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
12911                 }
12912         }
12913
12914         if (nested_cpu_has_ept(vmcs12))
12915                 nested_ept_init_mmu_context(vcpu);
12916         else if (nested_cpu_has2(vmcs12,
12917                                  SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
12918                 vmx_flush_tlb(vcpu, true);
12919
12920         /*
12921          * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
12922          * bits which we consider mandatory enabled.
12923          * The CR0_READ_SHADOW is what L2 should have expected to read given
12924          * the specifications by L1; It's not enough to take
12925          * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
12926          * have more bits than L1 expected.
12927          */
12928         vmx_set_cr0(vcpu, vmcs12->guest_cr0);
12929         vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
12930
12931         vmx_set_cr4(vcpu, vmcs12->guest_cr4);
12932         vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
12933
12934         vcpu->arch.efer = nested_vmx_calc_efer(vmx, vmcs12);
12935         /* Note: may modify VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
12936         vmx_set_efer(vcpu, vcpu->arch.efer);
12937
12938         /*
12939          * Guest state is invalid and unrestricted guest is disabled,
12940          * which means L1 attempted VMEntry to L2 with invalid state.
12941          * Fail the VMEntry.
12942          */
12943         if (vmx->emulation_required) {
12944                 *entry_failure_code = ENTRY_FAIL_DEFAULT;
12945                 return 1;
12946         }
12947
12948         /* Shadow page tables on either EPT or shadow page tables. */
12949         if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
12950                                 entry_failure_code))
12951                 return 1;
12952
12953         if (!enable_ept)
12954                 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
12955
12956         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
12957         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
12958         return 0;
12959 }
12960
12961 static int nested_vmx_check_nmi_controls(struct vmcs12 *vmcs12)
12962 {
12963         if (!nested_cpu_has_nmi_exiting(vmcs12) &&
12964             nested_cpu_has_virtual_nmis(vmcs12))
12965                 return -EINVAL;
12966
12967         if (!nested_cpu_has_virtual_nmis(vmcs12) &&
12968             nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING))
12969                 return -EINVAL;
12970
12971         return 0;
12972 }
12973
12974 static int check_vmentry_prereqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12975 {
12976         struct vcpu_vmx *vmx = to_vmx(vcpu);
12977         bool ia32e;
12978
12979         if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
12980             vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT)
12981                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12982
12983         if (nested_cpu_has_vpid(vmcs12) && !vmcs12->virtual_processor_id)
12984                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12985
12986         if (nested_vmx_check_io_bitmap_controls(vcpu, vmcs12))
12987                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12988
12989         if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12))
12990                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12991
12992         if (nested_vmx_check_apic_access_controls(vcpu, vmcs12))
12993                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12994
12995         if (nested_vmx_check_tpr_shadow_controls(vcpu, vmcs12))
12996                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12997
12998         if (nested_vmx_check_apicv_controls(vcpu, vmcs12))
12999                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13000
13001         if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12))
13002                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13003
13004         if (nested_vmx_check_pml_controls(vcpu, vmcs12))
13005                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13006
13007         if (nested_vmx_check_shadow_vmcs_controls(vcpu, vmcs12))
13008                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13009
13010         if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
13011                                 vmx->nested.msrs.procbased_ctls_low,
13012                                 vmx->nested.msrs.procbased_ctls_high) ||
13013             (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
13014              !vmx_control_verify(vmcs12->secondary_vm_exec_control,
13015                                  vmx->nested.msrs.secondary_ctls_low,
13016                                  vmx->nested.msrs.secondary_ctls_high)) ||
13017             !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
13018                                 vmx->nested.msrs.pinbased_ctls_low,
13019                                 vmx->nested.msrs.pinbased_ctls_high) ||
13020             !vmx_control_verify(vmcs12->vm_exit_controls,
13021                                 vmx->nested.msrs.exit_ctls_low,
13022                                 vmx->nested.msrs.exit_ctls_high) ||
13023             !vmx_control_verify(vmcs12->vm_entry_controls,
13024                                 vmx->nested.msrs.entry_ctls_low,
13025                                 vmx->nested.msrs.entry_ctls_high))
13026                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13027
13028         if (nested_vmx_check_nmi_controls(vmcs12))
13029                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13030
13031         if (nested_cpu_has_vmfunc(vmcs12)) {
13032                 if (vmcs12->vm_function_control &
13033                     ~vmx->nested.msrs.vmfunc_controls)
13034                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13035
13036                 if (nested_cpu_has_eptp_switching(vmcs12)) {
13037                         if (!nested_cpu_has_ept(vmcs12) ||
13038                             !page_address_valid(vcpu, vmcs12->eptp_list_address))
13039                                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13040                 }
13041         }
13042
13043         if (vmcs12->cr3_target_count > nested_cpu_vmx_misc_cr3_count(vcpu))
13044                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13045
13046         if (!nested_host_cr0_valid(vcpu, vmcs12->host_cr0) ||
13047             !nested_host_cr4_valid(vcpu, vmcs12->host_cr4) ||
13048             !nested_cr3_valid(vcpu, vmcs12->host_cr3))
13049                 return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
13050
13051         /*
13052          * If the load IA32_EFER VM-exit control is 1, bits reserved in the
13053          * IA32_EFER MSR must be 0 in the field for that register. In addition,
13054          * the values of the LMA and LME bits in the field must each be that of
13055          * the host address-space size VM-exit control.
13056          */
13057         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
13058                 ia32e = (vmcs12->vm_exit_controls &
13059                          VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
13060                 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
13061                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
13062                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LME))
13063                         return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
13064         }
13065
13066         /*
13067          * From the Intel SDM, volume 3:
13068          * Fields relevant to VM-entry event injection must be set properly.
13069          * These fields are the VM-entry interruption-information field, the
13070          * VM-entry exception error code, and the VM-entry instruction length.
13071          */
13072         if (vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) {
13073                 u32 intr_info = vmcs12->vm_entry_intr_info_field;
13074                 u8 vector = intr_info & INTR_INFO_VECTOR_MASK;
13075                 u32 intr_type = intr_info & INTR_INFO_INTR_TYPE_MASK;
13076                 bool has_error_code = intr_info & INTR_INFO_DELIVER_CODE_MASK;
13077                 bool should_have_error_code;
13078                 bool urg = nested_cpu_has2(vmcs12,
13079                                            SECONDARY_EXEC_UNRESTRICTED_GUEST);
13080                 bool prot_mode = !urg || vmcs12->guest_cr0 & X86_CR0_PE;
13081
13082                 /* VM-entry interruption-info field: interruption type */
13083                 if (intr_type == INTR_TYPE_RESERVED ||
13084                     (intr_type == INTR_TYPE_OTHER_EVENT &&
13085                      !nested_cpu_supports_monitor_trap_flag(vcpu)))
13086                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13087
13088                 /* VM-entry interruption-info field: vector */
13089                 if ((intr_type == INTR_TYPE_NMI_INTR && vector != NMI_VECTOR) ||
13090                     (intr_type == INTR_TYPE_HARD_EXCEPTION && vector > 31) ||
13091                     (intr_type == INTR_TYPE_OTHER_EVENT && vector != 0))
13092                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13093
13094                 /* VM-entry interruption-info field: deliver error code */
13095                 should_have_error_code =
13096                         intr_type == INTR_TYPE_HARD_EXCEPTION && prot_mode &&
13097                         x86_exception_has_error_code(vector);
13098                 if (has_error_code != should_have_error_code)
13099                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13100
13101                 /* VM-entry exception error code */
13102                 if (has_error_code &&
13103                     vmcs12->vm_entry_exception_error_code & GENMASK(31, 15))
13104                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13105
13106                 /* VM-entry interruption-info field: reserved bits */
13107                 if (intr_info & INTR_INFO_RESVD_BITS_MASK)
13108                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13109
13110                 /* VM-entry instruction length */
13111                 switch (intr_type) {
13112                 case INTR_TYPE_SOFT_EXCEPTION:
13113                 case INTR_TYPE_SOFT_INTR:
13114                 case INTR_TYPE_PRIV_SW_EXCEPTION:
13115                         if ((vmcs12->vm_entry_instruction_len > 15) ||
13116                             (vmcs12->vm_entry_instruction_len == 0 &&
13117                              !nested_cpu_has_zero_length_injection(vcpu)))
13118                                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13119                 }
13120         }
13121
13122         if (nested_cpu_has_ept(vmcs12) &&
13123             !valid_ept_address(vcpu, vmcs12->ept_pointer))
13124                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13125
13126         return 0;
13127 }
13128
13129 static int nested_vmx_check_vmcs_link_ptr(struct kvm_vcpu *vcpu,
13130                                           struct vmcs12 *vmcs12)
13131 {
13132         int r;
13133         struct page *page;
13134         struct vmcs12 *shadow;
13135
13136         if (vmcs12->vmcs_link_pointer == -1ull)
13137                 return 0;
13138
13139         if (!page_address_valid(vcpu, vmcs12->vmcs_link_pointer))
13140                 return -EINVAL;
13141
13142         page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->vmcs_link_pointer);
13143         if (is_error_page(page))
13144                 return -EINVAL;
13145
13146         r = 0;
13147         shadow = kmap(page);
13148         if (shadow->hdr.revision_id != VMCS12_REVISION ||
13149             shadow->hdr.shadow_vmcs != nested_cpu_has_shadow_vmcs(vmcs12))
13150                 r = -EINVAL;
13151         kunmap(page);
13152         kvm_release_page_clean(page);
13153         return r;
13154 }
13155
13156 static int check_vmentry_postreqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
13157                                   u32 *exit_qual)
13158 {
13159         bool ia32e;
13160
13161         *exit_qual = ENTRY_FAIL_DEFAULT;
13162
13163         if (!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0) ||
13164             !nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4))
13165                 return 1;
13166
13167         if (nested_vmx_check_vmcs_link_ptr(vcpu, vmcs12)) {
13168                 *exit_qual = ENTRY_FAIL_VMCS_LINK_PTR;
13169                 return 1;
13170         }
13171
13172         /*
13173          * If the load IA32_EFER VM-entry control is 1, the following checks
13174          * are performed on the field for the IA32_EFER MSR:
13175          * - Bits reserved in the IA32_EFER MSR must be 0.
13176          * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
13177          *   the IA-32e mode guest VM-exit control. It must also be identical
13178          *   to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
13179          *   CR0.PG) is 1.
13180          */
13181         if (to_vmx(vcpu)->nested.nested_run_pending &&
13182             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {
13183                 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
13184                 if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
13185                     ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
13186                     ((vmcs12->guest_cr0 & X86_CR0_PG) &&
13187                      ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME)))
13188                         return 1;
13189         }
13190
13191         if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS) &&
13192                 (is_noncanonical_address(vmcs12->guest_bndcfgs & PAGE_MASK, vcpu) ||
13193                 (vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD)))
13194                         return 1;
13195
13196         return 0;
13197 }
13198
13199 static int __noclone nested_vmx_check_vmentry_hw(struct kvm_vcpu *vcpu)
13200 {
13201         struct vcpu_vmx *vmx = to_vmx(vcpu);
13202         unsigned long cr3, cr4;
13203
13204         if (!nested_early_check)
13205                 return 0;
13206
13207         if (vmx->msr_autoload.host.nr)
13208                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
13209         if (vmx->msr_autoload.guest.nr)
13210                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
13211
13212         preempt_disable();
13213
13214         vmx_prepare_switch_to_guest(vcpu);
13215
13216         /*
13217          * Induce a consistency check VMExit by clearing bit 1 in GUEST_RFLAGS,
13218          * which is reserved to '1' by hardware.  GUEST_RFLAGS is guaranteed to
13219          * be written (by preparve_vmcs02()) before the "real" VMEnter, i.e.
13220          * there is no need to preserve other bits or save/restore the field.
13221          */
13222         vmcs_writel(GUEST_RFLAGS, 0);
13223
13224         vmcs_writel(HOST_RIP, vmx_early_consistency_check_return);
13225
13226         cr3 = __get_current_cr3_fast();
13227         if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
13228                 vmcs_writel(HOST_CR3, cr3);
13229                 vmx->loaded_vmcs->host_state.cr3 = cr3;
13230         }
13231
13232         cr4 = cr4_read_shadow();
13233         if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
13234                 vmcs_writel(HOST_CR4, cr4);
13235                 vmx->loaded_vmcs->host_state.cr4 = cr4;
13236         }
13237
13238         vmx->__launched = vmx->loaded_vmcs->launched;
13239
13240         asm(
13241                 /* Set HOST_RSP */
13242                 __ex("vmwrite %%" _ASM_SP ", %%" _ASM_DX) "\n\t"
13243                 "mov %%" _ASM_SP ", %c[host_rsp](%0)\n\t"
13244
13245                 /* Check if vmlaunch of vmresume is needed */
13246                 "cmpl $0, %c[launched](%0)\n\t"
13247                 "je 1f\n\t"
13248                 __ex("vmresume") "\n\t"
13249                 "jmp 2f\n\t"
13250                 "1: " __ex("vmlaunch") "\n\t"
13251                 "jmp 2f\n\t"
13252                 "2: "
13253
13254                 /* Set vmx->fail accordingly */
13255                 "setbe %c[fail](%0)\n\t"
13256
13257                 ".pushsection .rodata\n\t"
13258                 ".global vmx_early_consistency_check_return\n\t"
13259                 "vmx_early_consistency_check_return: " _ASM_PTR " 2b\n\t"
13260                 ".popsection"
13261               :
13262               : "c"(vmx), "d"((unsigned long)HOST_RSP),
13263                 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
13264                 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
13265                 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp))
13266               : "rax", "cc", "memory"
13267         );
13268
13269         vmcs_writel(HOST_RIP, vmx_return);
13270
13271         preempt_enable();
13272
13273         if (vmx->msr_autoload.host.nr)
13274                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
13275         if (vmx->msr_autoload.guest.nr)
13276                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
13277
13278         if (vmx->fail) {
13279                 WARN_ON_ONCE(vmcs_read32(VM_INSTRUCTION_ERROR) !=
13280                              VMXERR_ENTRY_INVALID_CONTROL_FIELD);
13281                 vmx->fail = 0;
13282                 return 1;
13283         }
13284
13285         /*
13286          * VMExit clears RFLAGS.IF and DR7, even on a consistency check.
13287          */
13288         local_irq_enable();
13289         if (hw_breakpoint_active())
13290                 set_debugreg(__this_cpu_read(cpu_dr7), 7);
13291
13292         /*
13293          * A non-failing VMEntry means we somehow entered guest mode with
13294          * an illegal RIP, and that's just the tip of the iceberg.  There
13295          * is no telling what memory has been modified or what state has
13296          * been exposed to unknown code.  Hitting this all but guarantees
13297          * a (very critical) hardware issue.
13298          */
13299         WARN_ON(!(vmcs_read32(VM_EXIT_REASON) &
13300                 VMX_EXIT_REASONS_FAILED_VMENTRY));
13301
13302         return 0;
13303 }
13304 STACK_FRAME_NON_STANDARD(nested_vmx_check_vmentry_hw);
13305
13306 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
13307                                    struct vmcs12 *vmcs12);
13308
13309 /*
13310  * If from_vmentry is false, this is being called from state restore (either RSM
13311  * or KVM_SET_NESTED_STATE).  Otherwise it's called from vmlaunch/vmresume.
13312 + *
13313 + * Returns:
13314 + *   0 - success, i.e. proceed with actual VMEnter
13315 + *   1 - consistency check VMExit
13316 + *  -1 - consistency check VMFail
13317  */
13318 static int nested_vmx_enter_non_root_mode(struct kvm_vcpu *vcpu,
13319                                           bool from_vmentry)
13320 {
13321         struct vcpu_vmx *vmx = to_vmx(vcpu);
13322         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
13323         bool evaluate_pending_interrupts;
13324         u32 exit_reason = EXIT_REASON_INVALID_STATE;
13325         u32 exit_qual;
13326
13327         evaluate_pending_interrupts = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
13328                 (CPU_BASED_VIRTUAL_INTR_PENDING | CPU_BASED_VIRTUAL_NMI_PENDING);
13329         if (likely(!evaluate_pending_interrupts) && kvm_vcpu_apicv_active(vcpu))
13330                 evaluate_pending_interrupts |= vmx_has_apicv_interrupt(vcpu);
13331
13332         if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
13333                 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
13334         if (kvm_mpx_supported() &&
13335                 !(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
13336                 vmx->nested.vmcs01_guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
13337
13338         vmx_switch_vmcs(vcpu, &vmx->nested.vmcs02);
13339
13340         prepare_vmcs02_early(vmx, vmcs12);
13341
13342         if (from_vmentry) {
13343                 nested_get_vmcs12_pages(vcpu);
13344
13345                 if (nested_vmx_check_vmentry_hw(vcpu)) {
13346                         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
13347                         return -1;
13348                 }
13349
13350                 if (check_vmentry_postreqs(vcpu, vmcs12, &exit_qual))
13351                         goto vmentry_fail_vmexit;
13352         }
13353
13354         enter_guest_mode(vcpu);
13355         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
13356                 vcpu->arch.tsc_offset += vmcs12->tsc_offset;
13357
13358         if (prepare_vmcs02(vcpu, vmcs12, &exit_qual))
13359                 goto vmentry_fail_vmexit_guest_mode;
13360
13361         if (from_vmentry) {
13362                 exit_reason = EXIT_REASON_MSR_LOAD_FAIL;
13363                 exit_qual = nested_vmx_load_msr(vcpu,
13364                                                 vmcs12->vm_entry_msr_load_addr,
13365                                                 vmcs12->vm_entry_msr_load_count);
13366                 if (exit_qual)
13367                         goto vmentry_fail_vmexit_guest_mode;
13368         } else {
13369                 /*
13370                  * The MMU is not initialized to point at the right entities yet and
13371                  * "get pages" would need to read data from the guest (i.e. we will
13372                  * need to perform gpa to hpa translation). Request a call
13373                  * to nested_get_vmcs12_pages before the next VM-entry.  The MSRs
13374                  * have already been set at vmentry time and should not be reset.
13375                  */
13376                 kvm_make_request(KVM_REQ_GET_VMCS12_PAGES, vcpu);
13377         }
13378
13379         /*
13380          * If L1 had a pending IRQ/NMI until it executed
13381          * VMLAUNCH/VMRESUME which wasn't delivered because it was
13382          * disallowed (e.g. interrupts disabled), L0 needs to
13383          * evaluate if this pending event should cause an exit from L2
13384          * to L1 or delivered directly to L2 (e.g. In case L1 don't
13385          * intercept EXTERNAL_INTERRUPT).
13386          *
13387          * Usually this would be handled by the processor noticing an
13388          * IRQ/NMI window request, or checking RVI during evaluation of
13389          * pending virtual interrupts.  However, this setting was done
13390          * on VMCS01 and now VMCS02 is active instead. Thus, we force L0
13391          * to perform pending event evaluation by requesting a KVM_REQ_EVENT.
13392          */
13393         if (unlikely(evaluate_pending_interrupts))
13394                 kvm_make_request(KVM_REQ_EVENT, vcpu);
13395
13396         /*
13397          * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
13398          * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
13399          * returned as far as L1 is concerned. It will only return (and set
13400          * the success flag) when L2 exits (see nested_vmx_vmexit()).
13401          */
13402         return 0;
13403
13404         /*
13405          * A failed consistency check that leads to a VMExit during L1's
13406          * VMEnter to L2 is a variation of a normal VMexit, as explained in
13407          * 26.7 "VM-entry failures during or after loading guest state".
13408          */
13409 vmentry_fail_vmexit_guest_mode:
13410         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
13411                 vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
13412         leave_guest_mode(vcpu);
13413
13414 vmentry_fail_vmexit:
13415         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
13416
13417         if (!from_vmentry)
13418                 return 1;
13419
13420         load_vmcs12_host_state(vcpu, vmcs12);
13421         vmcs12->vm_exit_reason = exit_reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
13422         vmcs12->exit_qualification = exit_qual;
13423         if (enable_shadow_vmcs || vmx->nested.hv_evmcs)
13424                 vmx->nested.need_vmcs12_sync = true;
13425         return 1;
13426 }
13427
13428 /*
13429  * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
13430  * for running an L2 nested guest.
13431  */
13432 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
13433 {
13434         struct vmcs12 *vmcs12;
13435         struct vcpu_vmx *vmx = to_vmx(vcpu);
13436         u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
13437         int ret;
13438
13439         if (!nested_vmx_check_permission(vcpu))
13440                 return 1;
13441
13442         if (!nested_vmx_handle_enlightened_vmptrld(vcpu, true))
13443                 return 1;
13444
13445         if (!vmx->nested.hv_evmcs && vmx->nested.current_vmptr == -1ull)
13446                 return nested_vmx_failInvalid(vcpu);
13447
13448         vmcs12 = get_vmcs12(vcpu);
13449
13450         /*
13451          * Can't VMLAUNCH or VMRESUME a shadow VMCS. Despite the fact
13452          * that there *is* a valid VMCS pointer, RFLAGS.CF is set
13453          * rather than RFLAGS.ZF, and no error number is stored to the
13454          * VM-instruction error field.
13455          */
13456         if (vmcs12->hdr.shadow_vmcs)
13457                 return nested_vmx_failInvalid(vcpu);
13458
13459         if (vmx->nested.hv_evmcs) {
13460                 copy_enlightened_to_vmcs12(vmx);
13461                 /* Enlightened VMCS doesn't have launch state */
13462                 vmcs12->launch_state = !launch;
13463         } else if (enable_shadow_vmcs) {
13464                 copy_shadow_to_vmcs12(vmx);
13465         }
13466
13467         /*
13468          * The nested entry process starts with enforcing various prerequisites
13469          * on vmcs12 as required by the Intel SDM, and act appropriately when
13470          * they fail: As the SDM explains, some conditions should cause the
13471          * instruction to fail, while others will cause the instruction to seem
13472          * to succeed, but return an EXIT_REASON_INVALID_STATE.
13473          * To speed up the normal (success) code path, we should avoid checking
13474          * for misconfigurations which will anyway be caught by the processor
13475          * when using the merged vmcs02.
13476          */
13477         if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS)
13478                 return nested_vmx_failValid(vcpu,
13479                         VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
13480
13481         if (vmcs12->launch_state == launch)
13482                 return nested_vmx_failValid(vcpu,
13483                         launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
13484                                : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
13485
13486         ret = check_vmentry_prereqs(vcpu, vmcs12);
13487         if (ret)
13488                 return nested_vmx_failValid(vcpu, ret);
13489
13490         /*
13491          * We're finally done with prerequisite checking, and can start with
13492          * the nested entry.
13493          */
13494         vmx->nested.nested_run_pending = 1;
13495         ret = nested_vmx_enter_non_root_mode(vcpu, true);
13496         vmx->nested.nested_run_pending = !ret;
13497         if (ret > 0)
13498                 return 1;
13499         else if (ret)
13500                 return nested_vmx_failValid(vcpu,
13501                         VMXERR_ENTRY_INVALID_CONTROL_FIELD);
13502
13503         /* Hide L1D cache contents from the nested guest.  */
13504         vmx->vcpu.arch.l1tf_flush_l1d = true;
13505
13506         /*
13507          * Must happen outside of nested_vmx_enter_non_root_mode() as it will
13508          * also be used as part of restoring nVMX state for
13509          * snapshot restore (migration).
13510          *
13511          * In this flow, it is assumed that vmcs12 cache was
13512          * trasferred as part of captured nVMX state and should
13513          * therefore not be read from guest memory (which may not
13514          * exist on destination host yet).
13515          */
13516         nested_cache_shadow_vmcs12(vcpu, vmcs12);
13517
13518         /*
13519          * If we're entering a halted L2 vcpu and the L2 vcpu won't be woken
13520          * by event injection, halt vcpu.
13521          */
13522         if ((vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT) &&
13523             !(vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK)) {
13524                 vmx->nested.nested_run_pending = 0;
13525                 return kvm_vcpu_halt(vcpu);
13526         }
13527         return 1;
13528 }
13529
13530 /*
13531  * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
13532  * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
13533  * This function returns the new value we should put in vmcs12.guest_cr0.
13534  * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
13535  *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
13536  *     available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
13537  *     didn't trap the bit, because if L1 did, so would L0).
13538  *  2. Bits that L1 asked to trap (and therefore L0 also did) could not have
13539  *     been modified by L2, and L1 knows it. So just leave the old value of
13540  *     the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
13541  *     isn't relevant, because if L0 traps this bit it can set it to anything.
13542  *  3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
13543  *     changed these bits, and therefore they need to be updated, but L0
13544  *     didn't necessarily allow them to be changed in GUEST_CR0 - and rather
13545  *     put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
13546  */
13547 static inline unsigned long
13548 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
13549 {
13550         return
13551         /*1*/   (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
13552         /*2*/   (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
13553         /*3*/   (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
13554                         vcpu->arch.cr0_guest_owned_bits));
13555 }
13556
13557 static inline unsigned long
13558 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
13559 {
13560         return
13561         /*1*/   (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
13562         /*2*/   (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
13563         /*3*/   (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
13564                         vcpu->arch.cr4_guest_owned_bits));
13565 }
13566
13567 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
13568                                        struct vmcs12 *vmcs12)
13569 {
13570         u32 idt_vectoring;
13571         unsigned int nr;
13572
13573         if (vcpu->arch.exception.injected) {
13574                 nr = vcpu->arch.exception.nr;
13575                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
13576
13577                 if (kvm_exception_is_soft(nr)) {
13578                         vmcs12->vm_exit_instruction_len =
13579                                 vcpu->arch.event_exit_inst_len;
13580                         idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
13581                 } else
13582                         idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
13583
13584                 if (vcpu->arch.exception.has_error_code) {
13585                         idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
13586                         vmcs12->idt_vectoring_error_code =
13587                                 vcpu->arch.exception.error_code;
13588                 }
13589
13590                 vmcs12->idt_vectoring_info_field = idt_vectoring;
13591         } else if (vcpu->arch.nmi_injected) {
13592                 vmcs12->idt_vectoring_info_field =
13593                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
13594         } else if (vcpu->arch.interrupt.injected) {
13595                 nr = vcpu->arch.interrupt.nr;
13596                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
13597
13598                 if (vcpu->arch.interrupt.soft) {
13599                         idt_vectoring |= INTR_TYPE_SOFT_INTR;
13600                         vmcs12->vm_entry_instruction_len =
13601                                 vcpu->arch.event_exit_inst_len;
13602                 } else
13603                         idt_vectoring |= INTR_TYPE_EXT_INTR;
13604
13605                 vmcs12->idt_vectoring_info_field = idt_vectoring;
13606         }
13607 }
13608
13609 static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
13610 {
13611         struct vcpu_vmx *vmx = to_vmx(vcpu);
13612         unsigned long exit_qual;
13613         bool block_nested_events =
13614             vmx->nested.nested_run_pending || kvm_event_needs_reinjection(vcpu);
13615
13616         if (vcpu->arch.exception.pending &&
13617                 nested_vmx_check_exception(vcpu, &exit_qual)) {
13618                 if (block_nested_events)
13619                         return -EBUSY;
13620                 nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
13621                 return 0;
13622         }
13623
13624         if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
13625             vmx->nested.preemption_timer_expired) {
13626                 if (block_nested_events)
13627                         return -EBUSY;
13628                 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
13629                 return 0;
13630         }
13631
13632         if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
13633                 if (block_nested_events)
13634                         return -EBUSY;
13635                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
13636                                   NMI_VECTOR | INTR_TYPE_NMI_INTR |
13637                                   INTR_INFO_VALID_MASK, 0);
13638                 /*
13639                  * The NMI-triggered VM exit counts as injection:
13640                  * clear this one and block further NMIs.
13641                  */
13642                 vcpu->arch.nmi_pending = 0;
13643                 vmx_set_nmi_mask(vcpu, true);
13644                 return 0;
13645         }
13646
13647         if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
13648             nested_exit_on_intr(vcpu)) {
13649                 if (block_nested_events)
13650                         return -EBUSY;
13651                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
13652                 return 0;
13653         }
13654
13655         vmx_complete_nested_posted_interrupt(vcpu);
13656         return 0;
13657 }
13658
13659 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
13660 {
13661         to_vmx(vcpu)->req_immediate_exit = true;
13662 }
13663
13664 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
13665 {
13666         ktime_t remaining =
13667                 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
13668         u64 value;
13669
13670         if (ktime_to_ns(remaining) <= 0)
13671                 return 0;
13672
13673         value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
13674         do_div(value, 1000000);
13675         return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
13676 }
13677
13678 /*
13679  * Update the guest state fields of vmcs12 to reflect changes that
13680  * occurred while L2 was running. (The "IA-32e mode guest" bit of the
13681  * VM-entry controls is also updated, since this is really a guest
13682  * state bit.)
13683  */
13684 static void sync_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
13685 {
13686         vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
13687         vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
13688
13689         vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
13690         vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
13691         vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
13692
13693         vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
13694         vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
13695         vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
13696         vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
13697         vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
13698         vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
13699         vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
13700         vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
13701         vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
13702         vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
13703         vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
13704         vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
13705         vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
13706         vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
13707         vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
13708         vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
13709         vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
13710         vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
13711         vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
13712         vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
13713         vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
13714         vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
13715         vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
13716         vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
13717         vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
13718         vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
13719         vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
13720         vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
13721         vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
13722         vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
13723         vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
13724         vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
13725         vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
13726         vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
13727         vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
13728         vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
13729
13730         vmcs12->guest_interruptibility_info =
13731                 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
13732         vmcs12->guest_pending_dbg_exceptions =
13733                 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
13734         if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
13735                 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
13736         else
13737                 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
13738
13739         if (nested_cpu_has_preemption_timer(vmcs12)) {
13740                 if (vmcs12->vm_exit_controls &
13741                     VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
13742                         vmcs12->vmx_preemption_timer_value =
13743                                 vmx_get_preemption_timer_value(vcpu);
13744                 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
13745         }
13746
13747         /*
13748          * In some cases (usually, nested EPT), L2 is allowed to change its
13749          * own CR3 without exiting. If it has changed it, we must keep it.
13750          * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
13751          * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
13752          *
13753          * Additionally, restore L2's PDPTR to vmcs12.
13754          */
13755         if (enable_ept) {
13756                 vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
13757                 vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
13758                 vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
13759                 vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
13760                 vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
13761         }
13762
13763         vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
13764
13765         if (nested_cpu_has_vid(vmcs12))
13766                 vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
13767
13768         vmcs12->vm_entry_controls =
13769                 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
13770                 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
13771
13772         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
13773                 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
13774                 vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
13775         }
13776
13777         /* TODO: These cannot have changed unless we have MSR bitmaps and
13778          * the relevant bit asks not to trap the change */
13779         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
13780                 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
13781         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
13782                 vmcs12->guest_ia32_efer = vcpu->arch.efer;
13783         vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
13784         vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
13785         vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
13786         if (kvm_mpx_supported())
13787                 vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
13788 }
13789
13790 /*
13791  * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
13792  * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
13793  * and this function updates it to reflect the changes to the guest state while
13794  * L2 was running (and perhaps made some exits which were handled directly by L0
13795  * without going back to L1), and to reflect the exit reason.
13796  * Note that we do not have to copy here all VMCS fields, just those that
13797  * could have changed by the L2 guest or the exit - i.e., the guest-state and
13798  * exit-information fields only. Other fields are modified by L1 with VMWRITE,
13799  * which already writes to vmcs12 directly.
13800  */
13801 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
13802                            u32 exit_reason, u32 exit_intr_info,
13803                            unsigned long exit_qualification)
13804 {
13805         /* update guest state fields: */
13806         sync_vmcs12(vcpu, vmcs12);
13807
13808         /* update exit information fields: */
13809
13810         vmcs12->vm_exit_reason = exit_reason;
13811         vmcs12->exit_qualification = exit_qualification;
13812         vmcs12->vm_exit_intr_info = exit_intr_info;
13813
13814         vmcs12->idt_vectoring_info_field = 0;
13815         vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
13816         vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
13817
13818         if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
13819                 vmcs12->launch_state = 1;
13820
13821                 /* vm_entry_intr_info_field is cleared on exit. Emulate this
13822                  * instead of reading the real value. */
13823                 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
13824
13825                 /*
13826                  * Transfer the event that L0 or L1 may wanted to inject into
13827                  * L2 to IDT_VECTORING_INFO_FIELD.
13828                  */
13829                 vmcs12_save_pending_event(vcpu, vmcs12);
13830         }
13831
13832         /*
13833          * Drop what we picked up for L2 via vmx_complete_interrupts. It is
13834          * preserved above and would only end up incorrectly in L1.
13835          */
13836         vcpu->arch.nmi_injected = false;
13837         kvm_clear_exception_queue(vcpu);
13838         kvm_clear_interrupt_queue(vcpu);
13839 }
13840
13841 /*
13842  * A part of what we need to when the nested L2 guest exits and we want to
13843  * run its L1 parent, is to reset L1's guest state to the host state specified
13844  * in vmcs12.
13845  * This function is to be called not only on normal nested exit, but also on
13846  * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
13847  * Failures During or After Loading Guest State").
13848  * This function should be called when the active VMCS is L1's (vmcs01).
13849  */
13850 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
13851                                    struct vmcs12 *vmcs12)
13852 {
13853         struct kvm_segment seg;
13854         u32 entry_failure_code;
13855
13856         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
13857                 vcpu->arch.efer = vmcs12->host_ia32_efer;
13858         else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
13859                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
13860         else
13861                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
13862         vmx_set_efer(vcpu, vcpu->arch.efer);
13863
13864         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
13865         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
13866         vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
13867         vmx_set_interrupt_shadow(vcpu, 0);
13868
13869         /*
13870          * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
13871          * actually changed, because vmx_set_cr0 refers to efer set above.
13872          *
13873          * CR0_GUEST_HOST_MASK is already set in the original vmcs01
13874          * (KVM doesn't change it);
13875          */
13876         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
13877         vmx_set_cr0(vcpu, vmcs12->host_cr0);
13878
13879         /* Same as above - no reason to call set_cr4_guest_host_mask().  */
13880         vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
13881         vmx_set_cr4(vcpu, vmcs12->host_cr4);
13882
13883         nested_ept_uninit_mmu_context(vcpu);
13884
13885         /*
13886          * Only PDPTE load can fail as the value of cr3 was checked on entry and
13887          * couldn't have changed.
13888          */
13889         if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
13890                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
13891
13892         if (!enable_ept)
13893                 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
13894
13895         /*
13896          * If vmcs01 doesn't use VPID, CPU flushes TLB on every
13897          * VMEntry/VMExit. Thus, no need to flush TLB.
13898          *
13899          * If vmcs12 doesn't use VPID, L1 expects TLB to be
13900          * flushed on every VMEntry/VMExit.
13901          *
13902          * Otherwise, we can preserve TLB entries as long as we are
13903          * able to tag L1 TLB entries differently than L2 TLB entries.
13904          *
13905          * If vmcs12 uses EPT, we need to execute this flush on EPTP01
13906          * and therefore we request the TLB flush to happen only after VMCS EPTP
13907          * has been set by KVM_REQ_LOAD_CR3.
13908          */
13909         if (enable_vpid &&
13910             (!nested_cpu_has_vpid(vmcs12) || !nested_has_guest_tlb_tag(vcpu))) {
13911                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
13912         }
13913
13914         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
13915         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
13916         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
13917         vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
13918         vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
13919         vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
13920         vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
13921
13922         /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1.  */
13923         if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
13924                 vmcs_write64(GUEST_BNDCFGS, 0);
13925
13926         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
13927                 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
13928                 vcpu->arch.pat = vmcs12->host_ia32_pat;
13929         }
13930         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
13931                 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
13932                         vmcs12->host_ia32_perf_global_ctrl);
13933
13934         /* Set L1 segment info according to Intel SDM
13935             27.5.2 Loading Host Segment and Descriptor-Table Registers */
13936         seg = (struct kvm_segment) {
13937                 .base = 0,
13938                 .limit = 0xFFFFFFFF,
13939                 .selector = vmcs12->host_cs_selector,
13940                 .type = 11,
13941                 .present = 1,
13942                 .s = 1,
13943                 .g = 1
13944         };
13945         if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
13946                 seg.l = 1;
13947         else
13948                 seg.db = 1;
13949         vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
13950         seg = (struct kvm_segment) {
13951                 .base = 0,
13952                 .limit = 0xFFFFFFFF,
13953                 .type = 3,
13954                 .present = 1,
13955                 .s = 1,
13956                 .db = 1,
13957                 .g = 1
13958         };
13959         seg.selector = vmcs12->host_ds_selector;
13960         vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
13961         seg.selector = vmcs12->host_es_selector;
13962         vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
13963         seg.selector = vmcs12->host_ss_selector;
13964         vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
13965         seg.selector = vmcs12->host_fs_selector;
13966         seg.base = vmcs12->host_fs_base;
13967         vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
13968         seg.selector = vmcs12->host_gs_selector;
13969         seg.base = vmcs12->host_gs_base;
13970         vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
13971         seg = (struct kvm_segment) {
13972                 .base = vmcs12->host_tr_base,
13973                 .limit = 0x67,
13974                 .selector = vmcs12->host_tr_selector,
13975                 .type = 11,
13976                 .present = 1
13977         };
13978         vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
13979
13980         kvm_set_dr(vcpu, 7, 0x400);
13981         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
13982
13983         if (cpu_has_vmx_msr_bitmap())
13984                 vmx_update_msr_bitmap(vcpu);
13985
13986         if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
13987                                 vmcs12->vm_exit_msr_load_count))
13988                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
13989 }
13990
13991 static inline u64 nested_vmx_get_vmcs01_guest_efer(struct vcpu_vmx *vmx)
13992 {
13993         struct shared_msr_entry *efer_msr;
13994         unsigned int i;
13995
13996         if (vm_entry_controls_get(vmx) & VM_ENTRY_LOAD_IA32_EFER)
13997                 return vmcs_read64(GUEST_IA32_EFER);
13998
13999         if (cpu_has_load_ia32_efer)
14000                 return host_efer;
14001
14002         for (i = 0; i < vmx->msr_autoload.guest.nr; ++i) {
14003                 if (vmx->msr_autoload.guest.val[i].index == MSR_EFER)
14004                         return vmx->msr_autoload.guest.val[i].value;
14005         }
14006
14007         efer_msr = find_msr_entry(vmx, MSR_EFER);
14008         if (efer_msr)
14009                 return efer_msr->data;
14010
14011         return host_efer;
14012 }
14013
14014 static void nested_vmx_restore_host_state(struct kvm_vcpu *vcpu)
14015 {
14016         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
14017         struct vcpu_vmx *vmx = to_vmx(vcpu);
14018         struct vmx_msr_entry g, h;
14019         struct msr_data msr;
14020         gpa_t gpa;
14021         u32 i, j;
14022
14023         vcpu->arch.pat = vmcs_read64(GUEST_IA32_PAT);
14024
14025         if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
14026                 /*
14027                  * L1's host DR7 is lost if KVM_GUESTDBG_USE_HW_BP is set
14028                  * as vmcs01.GUEST_DR7 contains a userspace defined value
14029                  * and vcpu->arch.dr7 is not squirreled away before the
14030                  * nested VMENTER (not worth adding a variable in nested_vmx).
14031                  */
14032                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
14033                         kvm_set_dr(vcpu, 7, DR7_FIXED_1);
14034                 else
14035                         WARN_ON(kvm_set_dr(vcpu, 7, vmcs_readl(GUEST_DR7)));
14036         }
14037
14038         /*
14039          * Note that calling vmx_set_{efer,cr0,cr4} is important as they
14040          * handle a variety of side effects to KVM's software model.
14041          */
14042         vmx_set_efer(vcpu, nested_vmx_get_vmcs01_guest_efer(vmx));
14043
14044         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
14045         vmx_set_cr0(vcpu, vmcs_readl(CR0_READ_SHADOW));
14046
14047         vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
14048         vmx_set_cr4(vcpu, vmcs_readl(CR4_READ_SHADOW));
14049
14050         nested_ept_uninit_mmu_context(vcpu);
14051         vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
14052         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
14053
14054         /*
14055          * Use ept_save_pdptrs(vcpu) to load the MMU's cached PDPTRs
14056          * from vmcs01 (if necessary).  The PDPTRs are not loaded on
14057          * VMFail, like everything else we just need to ensure our
14058          * software model is up-to-date.
14059          */
14060         ept_save_pdptrs(vcpu);
14061
14062         kvm_mmu_reset_context(vcpu);
14063
14064         if (cpu_has_vmx_msr_bitmap())
14065                 vmx_update_msr_bitmap(vcpu);
14066
14067         /*
14068          * This nasty bit of open coding is a compromise between blindly
14069          * loading L1's MSRs using the exit load lists (incorrect emulation
14070          * of VMFail), leaving the nested VM's MSRs in the software model
14071          * (incorrect behavior) and snapshotting the modified MSRs (too
14072          * expensive since the lists are unbound by hardware).  For each
14073          * MSR that was (prematurely) loaded from the nested VMEntry load
14074          * list, reload it from the exit load list if it exists and differs
14075          * from the guest value.  The intent is to stuff host state as
14076          * silently as possible, not to fully process the exit load list.
14077          */
14078         msr.host_initiated = false;
14079         for (i = 0; i < vmcs12->vm_entry_msr_load_count; i++) {
14080                 gpa = vmcs12->vm_entry_msr_load_addr + (i * sizeof(g));
14081                 if (kvm_vcpu_read_guest(vcpu, gpa, &g, sizeof(g))) {
14082                         pr_debug_ratelimited(
14083                                 "%s read MSR index failed (%u, 0x%08llx)\n",
14084                                 __func__, i, gpa);
14085                         goto vmabort;
14086                 }
14087
14088                 for (j = 0; j < vmcs12->vm_exit_msr_load_count; j++) {
14089                         gpa = vmcs12->vm_exit_msr_load_addr + (j * sizeof(h));
14090                         if (kvm_vcpu_read_guest(vcpu, gpa, &h, sizeof(h))) {
14091                                 pr_debug_ratelimited(
14092                                         "%s read MSR failed (%u, 0x%08llx)\n",
14093                                         __func__, j, gpa);
14094                                 goto vmabort;
14095                         }
14096                         if (h.index != g.index)
14097                                 continue;
14098                         if (h.value == g.value)
14099                                 break;
14100
14101                         if (nested_vmx_load_msr_check(vcpu, &h)) {
14102                                 pr_debug_ratelimited(
14103                                         "%s check failed (%u, 0x%x, 0x%x)\n",
14104                                         __func__, j, h.index, h.reserved);
14105                                 goto vmabort;
14106                         }
14107
14108                         msr.index = h.index;
14109                         msr.data = h.value;
14110                         if (kvm_set_msr(vcpu, &msr)) {
14111                                 pr_debug_ratelimited(
14112                                         "%s WRMSR failed (%u, 0x%x, 0x%llx)\n",
14113                                         __func__, j, h.index, h.value);
14114                                 goto vmabort;
14115                         }
14116                 }
14117         }
14118
14119         return;
14120
14121 vmabort:
14122         nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
14123 }
14124
14125 /*
14126  * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
14127  * and modify vmcs12 to make it see what it would expect to see there if
14128  * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
14129  */
14130 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
14131                               u32 exit_intr_info,
14132                               unsigned long exit_qualification)
14133 {
14134         struct vcpu_vmx *vmx = to_vmx(vcpu);
14135         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
14136
14137         /* trying to cancel vmlaunch/vmresume is a bug */
14138         WARN_ON_ONCE(vmx->nested.nested_run_pending);
14139
14140         leave_guest_mode(vcpu);
14141
14142         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
14143                 vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
14144
14145         if (likely(!vmx->fail)) {
14146                 if (exit_reason == -1)
14147                         sync_vmcs12(vcpu, vmcs12);
14148                 else
14149                         prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
14150                                        exit_qualification);
14151
14152                 /*
14153                  * Must happen outside of sync_vmcs12() as it will
14154                  * also be used to capture vmcs12 cache as part of
14155                  * capturing nVMX state for snapshot (migration).
14156                  *
14157                  * Otherwise, this flush will dirty guest memory at a
14158                  * point it is already assumed by user-space to be
14159                  * immutable.
14160                  */
14161                 nested_flush_cached_shadow_vmcs12(vcpu, vmcs12);
14162
14163                 if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
14164                                          vmcs12->vm_exit_msr_store_count))
14165                         nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
14166         } else {
14167                 /*
14168                  * The only expected VM-instruction error is "VM entry with
14169                  * invalid control field(s)." Anything else indicates a
14170                  * problem with L0.  And we should never get here with a
14171                  * VMFail of any type if early consistency checks are enabled.
14172                  */
14173                 WARN_ON_ONCE(vmcs_read32(VM_INSTRUCTION_ERROR) !=
14174                              VMXERR_ENTRY_INVALID_CONTROL_FIELD);
14175                 WARN_ON_ONCE(nested_early_check);
14176         }
14177
14178         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
14179
14180         /* Update any VMCS fields that might have changed while L2 ran */
14181         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
14182         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
14183         vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
14184
14185         if (kvm_has_tsc_control)
14186                 decache_tsc_multiplier(vmx);
14187
14188         if (vmx->nested.change_vmcs01_virtual_apic_mode) {
14189                 vmx->nested.change_vmcs01_virtual_apic_mode = false;
14190                 vmx_set_virtual_apic_mode(vcpu);
14191         } else if (!nested_cpu_has_ept(vmcs12) &&
14192                    nested_cpu_has2(vmcs12,
14193                                    SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
14194                 vmx_flush_tlb(vcpu, true);
14195         }
14196
14197         /* This is needed for same reason as it was needed in prepare_vmcs02 */
14198         vmx->host_rsp = 0;
14199
14200         /* Unpin physical memory we referred to in vmcs02 */
14201         if (vmx->nested.apic_access_page) {
14202                 kvm_release_page_dirty(vmx->nested.apic_access_page);
14203                 vmx->nested.apic_access_page = NULL;
14204         }
14205         if (vmx->nested.virtual_apic_page) {
14206                 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
14207                 vmx->nested.virtual_apic_page = NULL;
14208         }
14209         if (vmx->nested.pi_desc_page) {
14210                 kunmap(vmx->nested.pi_desc_page);
14211                 kvm_release_page_dirty(vmx->nested.pi_desc_page);
14212                 vmx->nested.pi_desc_page = NULL;
14213                 vmx->nested.pi_desc = NULL;
14214         }
14215
14216         /*
14217          * We are now running in L2, mmu_notifier will force to reload the
14218          * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
14219          */
14220         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
14221
14222         if ((exit_reason != -1) && (enable_shadow_vmcs || vmx->nested.hv_evmcs))
14223                 vmx->nested.need_vmcs12_sync = true;
14224
14225         /* in case we halted in L2 */
14226         vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
14227
14228         if (likely(!vmx->fail)) {
14229                 /*
14230                  * TODO: SDM says that with acknowledge interrupt on
14231                  * exit, bit 31 of the VM-exit interrupt information
14232                  * (valid interrupt) is always set to 1 on
14233                  * EXIT_REASON_EXTERNAL_INTERRUPT, so we shouldn't
14234                  * need kvm_cpu_has_interrupt().  See the commit
14235                  * message for details.
14236                  */
14237                 if (nested_exit_intr_ack_set(vcpu) &&
14238                     exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT &&
14239                     kvm_cpu_has_interrupt(vcpu)) {
14240                         int irq = kvm_cpu_get_interrupt(vcpu);
14241                         WARN_ON(irq < 0);
14242                         vmcs12->vm_exit_intr_info = irq |
14243                                 INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
14244                 }
14245
14246                 if (exit_reason != -1)
14247                         trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
14248                                                        vmcs12->exit_qualification,
14249                                                        vmcs12->idt_vectoring_info_field,
14250                                                        vmcs12->vm_exit_intr_info,
14251                                                        vmcs12->vm_exit_intr_error_code,
14252                                                        KVM_ISA_VMX);
14253
14254                 load_vmcs12_host_state(vcpu, vmcs12);
14255
14256                 return;
14257         }
14258
14259         /*
14260          * After an early L2 VM-entry failure, we're now back
14261          * in L1 which thinks it just finished a VMLAUNCH or
14262          * VMRESUME instruction, so we need to set the failure
14263          * flag and the VM-instruction error field of the VMCS
14264          * accordingly, and skip the emulated instruction.
14265          */
14266         (void)nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
14267
14268         /*
14269          * Restore L1's host state to KVM's software model.  We're here
14270          * because a consistency check was caught by hardware, which
14271          * means some amount of guest state has been propagated to KVM's
14272          * model and needs to be unwound to the host's state.
14273          */
14274         nested_vmx_restore_host_state(vcpu);
14275
14276         vmx->fail = 0;
14277 }
14278
14279 /*
14280  * Forcibly leave nested mode in order to be able to reset the VCPU later on.
14281  */
14282 static void vmx_leave_nested(struct kvm_vcpu *vcpu)
14283 {
14284         if (is_guest_mode(vcpu)) {
14285                 to_vmx(vcpu)->nested.nested_run_pending = 0;
14286                 nested_vmx_vmexit(vcpu, -1, 0, 0);
14287         }
14288         free_nested(vcpu);
14289 }
14290
14291 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
14292                                struct x86_instruction_info *info,
14293                                enum x86_intercept_stage stage)
14294 {
14295         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
14296         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
14297
14298         /*
14299          * RDPID causes #UD if disabled through secondary execution controls.
14300          * Because it is marked as EmulateOnUD, we need to intercept it here.
14301          */
14302         if (info->intercept == x86_intercept_rdtscp &&
14303             !nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
14304                 ctxt->exception.vector = UD_VECTOR;
14305                 ctxt->exception.error_code_valid = false;
14306                 return X86EMUL_PROPAGATE_FAULT;
14307         }
14308
14309         /* TODO: check more intercepts... */
14310         return X86EMUL_CONTINUE;
14311 }
14312
14313 #ifdef CONFIG_X86_64
14314 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
14315 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
14316                                   u64 divisor, u64 *result)
14317 {
14318         u64 low = a << shift, high = a >> (64 - shift);
14319
14320         /* To avoid the overflow on divq */
14321         if (high >= divisor)
14322                 return 1;
14323
14324         /* Low hold the result, high hold rem which is discarded */
14325         asm("divq %2\n\t" : "=a" (low), "=d" (high) :
14326             "rm" (divisor), "0" (low), "1" (high));
14327         *result = low;
14328
14329         return 0;
14330 }
14331
14332 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
14333 {
14334         struct vcpu_vmx *vmx;
14335         u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
14336
14337         if (kvm_mwait_in_guest(vcpu->kvm))
14338                 return -EOPNOTSUPP;
14339
14340         vmx = to_vmx(vcpu);
14341         tscl = rdtsc();
14342         guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
14343         delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
14344         lapic_timer_advance_cycles = nsec_to_cycles(vcpu, lapic_timer_advance_ns);
14345
14346         if (delta_tsc > lapic_timer_advance_cycles)
14347                 delta_tsc -= lapic_timer_advance_cycles;
14348         else
14349                 delta_tsc = 0;
14350
14351         /* Convert to host delta tsc if tsc scaling is enabled */
14352         if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
14353                         u64_shl_div_u64(delta_tsc,
14354                                 kvm_tsc_scaling_ratio_frac_bits,
14355                                 vcpu->arch.tsc_scaling_ratio,
14356                                 &delta_tsc))
14357                 return -ERANGE;
14358
14359         /*
14360          * If the delta tsc can't fit in the 32 bit after the multi shift,
14361          * we can't use the preemption timer.
14362          * It's possible that it fits on later vmentries, but checking
14363          * on every vmentry is costly so we just use an hrtimer.
14364          */
14365         if (delta_tsc >> (cpu_preemption_timer_multi + 32))
14366                 return -ERANGE;
14367
14368         vmx->hv_deadline_tsc = tscl + delta_tsc;
14369         return delta_tsc == 0;
14370 }
14371
14372 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
14373 {
14374         to_vmx(vcpu)->hv_deadline_tsc = -1;
14375 }
14376 #endif
14377
14378 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
14379 {
14380         if (!kvm_pause_in_guest(vcpu->kvm))
14381                 shrink_ple_window(vcpu);
14382 }
14383
14384 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
14385                                      struct kvm_memory_slot *slot)
14386 {
14387         kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
14388         kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
14389 }
14390
14391 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
14392                                        struct kvm_memory_slot *slot)
14393 {
14394         kvm_mmu_slot_set_dirty(kvm, slot);
14395 }
14396
14397 static void vmx_flush_log_dirty(struct kvm *kvm)
14398 {
14399         kvm_flush_pml_buffers(kvm);
14400 }
14401
14402 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
14403 {
14404         struct vmcs12 *vmcs12;
14405         struct vcpu_vmx *vmx = to_vmx(vcpu);
14406         gpa_t gpa;
14407         struct page *page = NULL;
14408         u64 *pml_address;
14409
14410         if (is_guest_mode(vcpu)) {
14411                 WARN_ON_ONCE(vmx->nested.pml_full);
14412
14413                 /*
14414                  * Check if PML is enabled for the nested guest.
14415                  * Whether eptp bit 6 is set is already checked
14416                  * as part of A/D emulation.
14417                  */
14418                 vmcs12 = get_vmcs12(vcpu);
14419                 if (!nested_cpu_has_pml(vmcs12))
14420                         return 0;
14421
14422                 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
14423                         vmx->nested.pml_full = true;
14424                         return 1;
14425                 }
14426
14427                 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
14428
14429                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->pml_address);
14430                 if (is_error_page(page))
14431                         return 0;
14432
14433                 pml_address = kmap(page);
14434                 pml_address[vmcs12->guest_pml_index--] = gpa;
14435                 kunmap(page);
14436                 kvm_release_page_clean(page);
14437         }
14438
14439         return 0;
14440 }
14441
14442 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
14443                                            struct kvm_memory_slot *memslot,
14444                                            gfn_t offset, unsigned long mask)
14445 {
14446         kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
14447 }
14448
14449 static void __pi_post_block(struct kvm_vcpu *vcpu)
14450 {
14451         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
14452         struct pi_desc old, new;
14453         unsigned int dest;
14454
14455         do {
14456                 old.control = new.control = pi_desc->control;
14457                 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
14458                      "Wakeup handler not enabled while the VCPU is blocked\n");
14459
14460                 dest = cpu_physical_id(vcpu->cpu);
14461
14462                 if (x2apic_enabled())
14463                         new.ndst = dest;
14464                 else
14465                         new.ndst = (dest << 8) & 0xFF00;
14466
14467                 /* set 'NV' to 'notification vector' */
14468                 new.nv = POSTED_INTR_VECTOR;
14469         } while (cmpxchg64(&pi_desc->control, old.control,
14470                            new.control) != old.control);
14471
14472         if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
14473                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
14474                 list_del(&vcpu->blocked_vcpu_list);
14475                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
14476                 vcpu->pre_pcpu = -1;
14477         }
14478 }
14479
14480 /*
14481  * This routine does the following things for vCPU which is going
14482  * to be blocked if VT-d PI is enabled.
14483  * - Store the vCPU to the wakeup list, so when interrupts happen
14484  *   we can find the right vCPU to wake up.
14485  * - Change the Posted-interrupt descriptor as below:
14486  *      'NDST' <-- vcpu->pre_pcpu
14487  *      'NV' <-- POSTED_INTR_WAKEUP_VECTOR
14488  * - If 'ON' is set during this process, which means at least one
14489  *   interrupt is posted for this vCPU, we cannot block it, in
14490  *   this case, return 1, otherwise, return 0.
14491  *
14492  */
14493 static int pi_pre_block(struct kvm_vcpu *vcpu)
14494 {
14495         unsigned int dest;
14496         struct pi_desc old, new;
14497         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
14498
14499         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
14500                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
14501                 !kvm_vcpu_apicv_active(vcpu))
14502                 return 0;
14503
14504         WARN_ON(irqs_disabled());
14505         local_irq_disable();
14506         if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
14507                 vcpu->pre_pcpu = vcpu->cpu;
14508                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
14509                 list_add_tail(&vcpu->blocked_vcpu_list,
14510                               &per_cpu(blocked_vcpu_on_cpu,
14511                                        vcpu->pre_pcpu));
14512                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
14513         }
14514
14515         do {
14516                 old.control = new.control = pi_desc->control;
14517
14518                 WARN((pi_desc->sn == 1),
14519                      "Warning: SN field of posted-interrupts "
14520                      "is set before blocking\n");
14521
14522                 /*
14523                  * Since vCPU can be preempted during this process,
14524                  * vcpu->cpu could be different with pre_pcpu, we
14525                  * need to set pre_pcpu as the destination of wakeup
14526                  * notification event, then we can find the right vCPU
14527                  * to wakeup in wakeup handler if interrupts happen
14528                  * when the vCPU is in blocked state.
14529                  */
14530                 dest = cpu_physical_id(vcpu->pre_pcpu);
14531
14532                 if (x2apic_enabled())
14533                         new.ndst = dest;
14534                 else
14535                         new.ndst = (dest << 8) & 0xFF00;
14536
14537                 /* set 'NV' to 'wakeup vector' */
14538                 new.nv = POSTED_INTR_WAKEUP_VECTOR;
14539         } while (cmpxchg64(&pi_desc->control, old.control,
14540                            new.control) != old.control);
14541
14542         /* We should not block the vCPU if an interrupt is posted for it.  */
14543         if (pi_test_on(pi_desc) == 1)
14544                 __pi_post_block(vcpu);
14545
14546         local_irq_enable();
14547         return (vcpu->pre_pcpu == -1);
14548 }
14549
14550 static int vmx_pre_block(struct kvm_vcpu *vcpu)
14551 {
14552         if (pi_pre_block(vcpu))
14553                 return 1;
14554
14555         if (kvm_lapic_hv_timer_in_use(vcpu))
14556                 kvm_lapic_switch_to_sw_timer(vcpu);
14557
14558         return 0;
14559 }
14560
14561 static void pi_post_block(struct kvm_vcpu *vcpu)
14562 {
14563         if (vcpu->pre_pcpu == -1)
14564                 return;
14565
14566         WARN_ON(irqs_disabled());
14567         local_irq_disable();
14568         __pi_post_block(vcpu);
14569         local_irq_enable();
14570 }
14571
14572 static void vmx_post_block(struct kvm_vcpu *vcpu)
14573 {
14574         if (kvm_x86_ops->set_hv_timer)
14575                 kvm_lapic_switch_to_hv_timer(vcpu);
14576
14577         pi_post_block(vcpu);
14578 }
14579
14580 /*
14581  * vmx_update_pi_irte - set IRTE for Posted-Interrupts
14582  *
14583  * @kvm: kvm
14584  * @host_irq: host irq of the interrupt
14585  * @guest_irq: gsi of the interrupt
14586  * @set: set or unset PI
14587  * returns 0 on success, < 0 on failure
14588  */
14589 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
14590                               uint32_t guest_irq, bool set)
14591 {
14592         struct kvm_kernel_irq_routing_entry *e;
14593         struct kvm_irq_routing_table *irq_rt;
14594         struct kvm_lapic_irq irq;
14595         struct kvm_vcpu *vcpu;
14596         struct vcpu_data vcpu_info;
14597         int idx, ret = 0;
14598
14599         if (!kvm_arch_has_assigned_device(kvm) ||
14600                 !irq_remapping_cap(IRQ_POSTING_CAP) ||
14601                 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
14602                 return 0;
14603
14604         idx = srcu_read_lock(&kvm->irq_srcu);
14605         irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
14606         if (guest_irq >= irq_rt->nr_rt_entries ||
14607             hlist_empty(&irq_rt->map[guest_irq])) {
14608                 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
14609                              guest_irq, irq_rt->nr_rt_entries);
14610                 goto out;
14611         }
14612
14613         hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
14614                 if (e->type != KVM_IRQ_ROUTING_MSI)
14615                         continue;
14616                 /*
14617                  * VT-d PI cannot support posting multicast/broadcast
14618                  * interrupts to a vCPU, we still use interrupt remapping
14619                  * for these kind of interrupts.
14620                  *
14621                  * For lowest-priority interrupts, we only support
14622                  * those with single CPU as the destination, e.g. user
14623                  * configures the interrupts via /proc/irq or uses
14624                  * irqbalance to make the interrupts single-CPU.
14625                  *
14626                  * We will support full lowest-priority interrupt later.
14627                  */
14628
14629                 kvm_set_msi_irq(kvm, e, &irq);
14630                 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
14631                         /*
14632                          * Make sure the IRTE is in remapped mode if
14633                          * we don't handle it in posted mode.
14634                          */
14635                         ret = irq_set_vcpu_affinity(host_irq, NULL);
14636                         if (ret < 0) {
14637                                 printk(KERN_INFO
14638                                    "failed to back to remapped mode, irq: %u\n",
14639                                    host_irq);
14640                                 goto out;
14641                         }
14642
14643                         continue;
14644                 }
14645
14646                 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
14647                 vcpu_info.vector = irq.vector;
14648
14649                 trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
14650                                 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
14651
14652                 if (set)
14653                         ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
14654                 else
14655                         ret = irq_set_vcpu_affinity(host_irq, NULL);
14656
14657                 if (ret < 0) {
14658                         printk(KERN_INFO "%s: failed to update PI IRTE\n",
14659                                         __func__);
14660                         goto out;
14661                 }
14662         }
14663
14664         ret = 0;
14665 out:
14666         srcu_read_unlock(&kvm->irq_srcu, idx);
14667         return ret;
14668 }
14669
14670 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
14671 {
14672         if (vcpu->arch.mcg_cap & MCG_LMCE_P)
14673                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
14674                         FEATURE_CONTROL_LMCE;
14675         else
14676                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
14677                         ~FEATURE_CONTROL_LMCE;
14678 }
14679
14680 static int vmx_smi_allowed(struct kvm_vcpu *vcpu)
14681 {
14682         /* we need a nested vmexit to enter SMM, postpone if run is pending */
14683         if (to_vmx(vcpu)->nested.nested_run_pending)
14684                 return 0;
14685         return 1;
14686 }
14687
14688 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
14689 {
14690         struct vcpu_vmx *vmx = to_vmx(vcpu);
14691
14692         vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
14693         if (vmx->nested.smm.guest_mode)
14694                 nested_vmx_vmexit(vcpu, -1, 0, 0);
14695
14696         vmx->nested.smm.vmxon = vmx->nested.vmxon;
14697         vmx->nested.vmxon = false;
14698         vmx_clear_hlt(vcpu);
14699         return 0;
14700 }
14701
14702 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
14703 {
14704         struct vcpu_vmx *vmx = to_vmx(vcpu);
14705         int ret;
14706
14707         if (vmx->nested.smm.vmxon) {
14708                 vmx->nested.vmxon = true;
14709                 vmx->nested.smm.vmxon = false;
14710         }
14711
14712         if (vmx->nested.smm.guest_mode) {
14713                 vcpu->arch.hflags &= ~HF_SMM_MASK;
14714                 ret = nested_vmx_enter_non_root_mode(vcpu, false);
14715                 vcpu->arch.hflags |= HF_SMM_MASK;
14716                 if (ret)
14717                         return ret;
14718
14719                 vmx->nested.smm.guest_mode = false;
14720         }
14721         return 0;
14722 }
14723
14724 static int enable_smi_window(struct kvm_vcpu *vcpu)
14725 {
14726         return 0;
14727 }
14728
14729 static inline int vmx_has_valid_vmcs12(struct kvm_vcpu *vcpu)
14730 {
14731         struct vcpu_vmx *vmx = to_vmx(vcpu);
14732
14733         /*
14734          * In case we do two consecutive get/set_nested_state()s while L2 was
14735          * running hv_evmcs may end up not being mapped (we map it from
14736          * nested_vmx_run()/vmx_vcpu_run()). Check is_guest_mode() as we always
14737          * have vmcs12 if it is true.
14738          */
14739         return is_guest_mode(vcpu) || vmx->nested.current_vmptr != -1ull ||
14740                 vmx->nested.hv_evmcs;
14741 }
14742
14743 static int vmx_get_nested_state(struct kvm_vcpu *vcpu,
14744                                 struct kvm_nested_state __user *user_kvm_nested_state,
14745                                 u32 user_data_size)
14746 {
14747         struct vcpu_vmx *vmx;
14748         struct vmcs12 *vmcs12;
14749         struct kvm_nested_state kvm_state = {
14750                 .flags = 0,
14751                 .format = 0,
14752                 .size = sizeof(kvm_state),
14753                 .vmx.vmxon_pa = -1ull,
14754                 .vmx.vmcs_pa = -1ull,
14755         };
14756
14757         if (!vcpu)
14758                 return kvm_state.size + 2 * VMCS12_SIZE;
14759
14760         vmx = to_vmx(vcpu);
14761         vmcs12 = get_vmcs12(vcpu);
14762
14763         if (nested_vmx_allowed(vcpu) && vmx->nested.enlightened_vmcs_enabled)
14764                 kvm_state.flags |= KVM_STATE_NESTED_EVMCS;
14765
14766         if (nested_vmx_allowed(vcpu) &&
14767             (vmx->nested.vmxon || vmx->nested.smm.vmxon)) {
14768                 kvm_state.vmx.vmxon_pa = vmx->nested.vmxon_ptr;
14769                 kvm_state.vmx.vmcs_pa = vmx->nested.current_vmptr;
14770
14771                 if (vmx_has_valid_vmcs12(vcpu)) {
14772                         kvm_state.size += VMCS12_SIZE;
14773
14774                         if (is_guest_mode(vcpu) &&
14775                             nested_cpu_has_shadow_vmcs(vmcs12) &&
14776                             vmcs12->vmcs_link_pointer != -1ull)
14777                                 kvm_state.size += VMCS12_SIZE;
14778                 }
14779
14780                 if (vmx->nested.smm.vmxon)
14781                         kvm_state.vmx.smm.flags |= KVM_STATE_NESTED_SMM_VMXON;
14782
14783                 if (vmx->nested.smm.guest_mode)
14784                         kvm_state.vmx.smm.flags |= KVM_STATE_NESTED_SMM_GUEST_MODE;
14785
14786                 if (is_guest_mode(vcpu)) {
14787                         kvm_state.flags |= KVM_STATE_NESTED_GUEST_MODE;
14788
14789                         if (vmx->nested.nested_run_pending)
14790                                 kvm_state.flags |= KVM_STATE_NESTED_RUN_PENDING;
14791                 }
14792         }
14793
14794         if (user_data_size < kvm_state.size)
14795                 goto out;
14796
14797         if (copy_to_user(user_kvm_nested_state, &kvm_state, sizeof(kvm_state)))
14798                 return -EFAULT;
14799
14800         if (!vmx_has_valid_vmcs12(vcpu))
14801                 goto out;
14802
14803         /*
14804          * When running L2, the authoritative vmcs12 state is in the
14805          * vmcs02. When running L1, the authoritative vmcs12 state is
14806          * in the shadow or enlightened vmcs linked to vmcs01, unless
14807          * need_vmcs12_sync is set, in which case, the authoritative
14808          * vmcs12 state is in the vmcs12 already.
14809          */
14810         if (is_guest_mode(vcpu)) {
14811                 sync_vmcs12(vcpu, vmcs12);
14812         } else if (!vmx->nested.need_vmcs12_sync) {
14813                 if (vmx->nested.hv_evmcs)
14814                         copy_enlightened_to_vmcs12(vmx);
14815                 else if (enable_shadow_vmcs)
14816                         copy_shadow_to_vmcs12(vmx);
14817         }
14818
14819         if (copy_to_user(user_kvm_nested_state->data, vmcs12, sizeof(*vmcs12)))
14820                 return -EFAULT;
14821
14822         if (nested_cpu_has_shadow_vmcs(vmcs12) &&
14823             vmcs12->vmcs_link_pointer != -1ull) {
14824                 if (copy_to_user(user_kvm_nested_state->data + VMCS12_SIZE,
14825                                  get_shadow_vmcs12(vcpu), sizeof(*vmcs12)))
14826                         return -EFAULT;
14827         }
14828
14829 out:
14830         return kvm_state.size;
14831 }
14832
14833 static int vmx_set_nested_state(struct kvm_vcpu *vcpu,
14834                                 struct kvm_nested_state __user *user_kvm_nested_state,
14835                                 struct kvm_nested_state *kvm_state)
14836 {
14837         struct vcpu_vmx *vmx = to_vmx(vcpu);
14838         struct vmcs12 *vmcs12;
14839         u32 exit_qual;
14840         int ret;
14841
14842         if (kvm_state->format != 0)
14843                 return -EINVAL;
14844
14845         if (kvm_state->flags & KVM_STATE_NESTED_EVMCS)
14846                 nested_enable_evmcs(vcpu, NULL);
14847
14848         if (!nested_vmx_allowed(vcpu))
14849                 return kvm_state->vmx.vmxon_pa == -1ull ? 0 : -EINVAL;
14850
14851         if (kvm_state->vmx.vmxon_pa == -1ull) {
14852                 if (kvm_state->vmx.smm.flags)
14853                         return -EINVAL;
14854
14855                 if (kvm_state->vmx.vmcs_pa != -1ull)
14856                         return -EINVAL;
14857
14858                 vmx_leave_nested(vcpu);
14859                 return 0;
14860         }
14861
14862         if (!page_address_valid(vcpu, kvm_state->vmx.vmxon_pa))
14863                 return -EINVAL;
14864
14865         if ((kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
14866             (kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
14867                 return -EINVAL;
14868
14869         if (kvm_state->vmx.smm.flags &
14870             ~(KVM_STATE_NESTED_SMM_GUEST_MODE | KVM_STATE_NESTED_SMM_VMXON))
14871                 return -EINVAL;
14872
14873         /*
14874          * SMM temporarily disables VMX, so we cannot be in guest mode,
14875          * nor can VMLAUNCH/VMRESUME be pending.  Outside SMM, SMM flags
14876          * must be zero.
14877          */
14878         if (is_smm(vcpu) ? kvm_state->flags : kvm_state->vmx.smm.flags)
14879                 return -EINVAL;
14880
14881         if ((kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
14882             !(kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON))
14883                 return -EINVAL;
14884
14885         vmx_leave_nested(vcpu);
14886         if (kvm_state->vmx.vmxon_pa == -1ull)
14887                 return 0;
14888
14889         vmx->nested.vmxon_ptr = kvm_state->vmx.vmxon_pa;
14890         ret = enter_vmx_operation(vcpu);
14891         if (ret)
14892                 return ret;
14893
14894         /* Empty 'VMXON' state is permitted */
14895         if (kvm_state->size < sizeof(kvm_state) + sizeof(*vmcs12))
14896                 return 0;
14897
14898         if (kvm_state->vmx.vmcs_pa != -1ull) {
14899                 if (kvm_state->vmx.vmcs_pa == kvm_state->vmx.vmxon_pa ||
14900                     !page_address_valid(vcpu, kvm_state->vmx.vmcs_pa))
14901                         return -EINVAL;
14902
14903                 set_current_vmptr(vmx, kvm_state->vmx.vmcs_pa);
14904         } else if (kvm_state->flags & KVM_STATE_NESTED_EVMCS) {
14905                 /*
14906                  * Sync eVMCS upon entry as we may not have
14907                  * HV_X64_MSR_VP_ASSIST_PAGE set up yet.
14908                  */
14909                 vmx->nested.need_vmcs12_sync = true;
14910         } else {
14911                 return -EINVAL;
14912         }
14913
14914         if (kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON) {
14915                 vmx->nested.smm.vmxon = true;
14916                 vmx->nested.vmxon = false;
14917
14918                 if (kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE)
14919                         vmx->nested.smm.guest_mode = true;
14920         }
14921
14922         vmcs12 = get_vmcs12(vcpu);
14923         if (copy_from_user(vmcs12, user_kvm_nested_state->data, sizeof(*vmcs12)))
14924                 return -EFAULT;
14925
14926         if (vmcs12->hdr.revision_id != VMCS12_REVISION)
14927                 return -EINVAL;
14928
14929         if (!(kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
14930                 return 0;
14931
14932         vmx->nested.nested_run_pending =
14933                 !!(kvm_state->flags & KVM_STATE_NESTED_RUN_PENDING);
14934
14935         if (nested_cpu_has_shadow_vmcs(vmcs12) &&
14936             vmcs12->vmcs_link_pointer != -1ull) {
14937                 struct vmcs12 *shadow_vmcs12 = get_shadow_vmcs12(vcpu);
14938                 if (kvm_state->size < sizeof(kvm_state) + 2 * sizeof(*vmcs12))
14939                         return -EINVAL;
14940
14941                 if (copy_from_user(shadow_vmcs12,
14942                                    user_kvm_nested_state->data + VMCS12_SIZE,
14943                                    sizeof(*vmcs12)))
14944                         return -EFAULT;
14945
14946                 if (shadow_vmcs12->hdr.revision_id != VMCS12_REVISION ||
14947                     !shadow_vmcs12->hdr.shadow_vmcs)
14948                         return -EINVAL;
14949         }
14950
14951         if (check_vmentry_prereqs(vcpu, vmcs12) ||
14952             check_vmentry_postreqs(vcpu, vmcs12, &exit_qual))
14953                 return -EINVAL;
14954
14955         vmx->nested.dirty_vmcs12 = true;
14956         ret = nested_vmx_enter_non_root_mode(vcpu, false);
14957         if (ret)
14958                 return -EINVAL;
14959
14960         return 0;
14961 }
14962
14963 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
14964         .cpu_has_kvm_support = cpu_has_kvm_support,
14965         .disabled_by_bios = vmx_disabled_by_bios,
14966         .hardware_setup = hardware_setup,
14967         .hardware_unsetup = hardware_unsetup,
14968         .check_processor_compatibility = vmx_check_processor_compat,
14969         .hardware_enable = hardware_enable,
14970         .hardware_disable = hardware_disable,
14971         .cpu_has_accelerated_tpr = report_flexpriority,
14972         .has_emulated_msr = vmx_has_emulated_msr,
14973
14974         .vm_init = vmx_vm_init,
14975         .vm_alloc = vmx_vm_alloc,
14976         .vm_free = vmx_vm_free,
14977
14978         .vcpu_create = vmx_create_vcpu,
14979         .vcpu_free = vmx_free_vcpu,
14980         .vcpu_reset = vmx_vcpu_reset,
14981
14982         .prepare_guest_switch = vmx_prepare_switch_to_guest,
14983         .vcpu_load = vmx_vcpu_load,
14984         .vcpu_put = vmx_vcpu_put,
14985
14986         .update_bp_intercept = update_exception_bitmap,
14987         .get_msr_feature = vmx_get_msr_feature,
14988         .get_msr = vmx_get_msr,
14989         .set_msr = vmx_set_msr,
14990         .get_segment_base = vmx_get_segment_base,
14991         .get_segment = vmx_get_segment,
14992         .set_segment = vmx_set_segment,
14993         .get_cpl = vmx_get_cpl,
14994         .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
14995         .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
14996         .decache_cr3 = vmx_decache_cr3,
14997         .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
14998         .set_cr0 = vmx_set_cr0,
14999         .set_cr3 = vmx_set_cr3,
15000         .set_cr4 = vmx_set_cr4,
15001         .set_efer = vmx_set_efer,
15002         .get_idt = vmx_get_idt,
15003         .set_idt = vmx_set_idt,
15004         .get_gdt = vmx_get_gdt,
15005         .set_gdt = vmx_set_gdt,
15006         .get_dr6 = vmx_get_dr6,
15007         .set_dr6 = vmx_set_dr6,
15008         .set_dr7 = vmx_set_dr7,
15009         .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
15010         .cache_reg = vmx_cache_reg,
15011         .get_rflags = vmx_get_rflags,
15012         .set_rflags = vmx_set_rflags,
15013
15014         .tlb_flush = vmx_flush_tlb,
15015         .tlb_flush_gva = vmx_flush_tlb_gva,
15016
15017         .run = vmx_vcpu_run,
15018         .handle_exit = vmx_handle_exit,
15019         .skip_emulated_instruction = skip_emulated_instruction,
15020         .set_interrupt_shadow = vmx_set_interrupt_shadow,
15021         .get_interrupt_shadow = vmx_get_interrupt_shadow,
15022         .patch_hypercall = vmx_patch_hypercall,
15023         .set_irq = vmx_inject_irq,
15024         .set_nmi = vmx_inject_nmi,
15025         .queue_exception = vmx_queue_exception,
15026         .cancel_injection = vmx_cancel_injection,
15027         .interrupt_allowed = vmx_interrupt_allowed,
15028         .nmi_allowed = vmx_nmi_allowed,
15029         .get_nmi_mask = vmx_get_nmi_mask,
15030         .set_nmi_mask = vmx_set_nmi_mask,
15031         .enable_nmi_window = enable_nmi_window,
15032         .enable_irq_window = enable_irq_window,
15033         .update_cr8_intercept = update_cr8_intercept,
15034         .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
15035         .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
15036         .get_enable_apicv = vmx_get_enable_apicv,
15037         .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
15038         .load_eoi_exitmap = vmx_load_eoi_exitmap,
15039         .apicv_post_state_restore = vmx_apicv_post_state_restore,
15040         .hwapic_irr_update = vmx_hwapic_irr_update,
15041         .hwapic_isr_update = vmx_hwapic_isr_update,
15042         .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
15043         .sync_pir_to_irr = vmx_sync_pir_to_irr,
15044         .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
15045
15046         .set_tss_addr = vmx_set_tss_addr,
15047         .set_identity_map_addr = vmx_set_identity_map_addr,
15048         .get_tdp_level = get_ept_level,
15049         .get_mt_mask = vmx_get_mt_mask,
15050
15051         .get_exit_info = vmx_get_exit_info,
15052
15053         .get_lpage_level = vmx_get_lpage_level,
15054
15055         .cpuid_update = vmx_cpuid_update,
15056
15057         .rdtscp_supported = vmx_rdtscp_supported,
15058         .invpcid_supported = vmx_invpcid_supported,
15059
15060         .set_supported_cpuid = vmx_set_supported_cpuid,
15061
15062         .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
15063
15064         .read_l1_tsc_offset = vmx_read_l1_tsc_offset,
15065         .write_tsc_offset = vmx_write_tsc_offset,
15066
15067         .set_tdp_cr3 = vmx_set_cr3,
15068
15069         .check_intercept = vmx_check_intercept,
15070         .handle_external_intr = vmx_handle_external_intr,
15071         .mpx_supported = vmx_mpx_supported,
15072         .xsaves_supported = vmx_xsaves_supported,
15073         .umip_emulated = vmx_umip_emulated,
15074
15075         .check_nested_events = vmx_check_nested_events,
15076         .request_immediate_exit = vmx_request_immediate_exit,
15077
15078         .sched_in = vmx_sched_in,
15079
15080         .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
15081         .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
15082         .flush_log_dirty = vmx_flush_log_dirty,
15083         .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
15084         .write_log_dirty = vmx_write_pml_buffer,
15085
15086         .pre_block = vmx_pre_block,
15087         .post_block = vmx_post_block,
15088
15089         .pmu_ops = &intel_pmu_ops,
15090
15091         .update_pi_irte = vmx_update_pi_irte,
15092
15093 #ifdef CONFIG_X86_64
15094         .set_hv_timer = vmx_set_hv_timer,
15095         .cancel_hv_timer = vmx_cancel_hv_timer,
15096 #endif
15097
15098         .setup_mce = vmx_setup_mce,
15099
15100         .get_nested_state = vmx_get_nested_state,
15101         .set_nested_state = vmx_set_nested_state,
15102         .get_vmcs12_pages = nested_get_vmcs12_pages,
15103
15104         .smi_allowed = vmx_smi_allowed,
15105         .pre_enter_smm = vmx_pre_enter_smm,
15106         .pre_leave_smm = vmx_pre_leave_smm,
15107         .enable_smi_window = enable_smi_window,
15108
15109         .nested_enable_evmcs = nested_enable_evmcs,
15110 };
15111
15112 static void vmx_cleanup_l1d_flush(void)
15113 {
15114         if (vmx_l1d_flush_pages) {
15115                 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
15116                 vmx_l1d_flush_pages = NULL;
15117         }
15118         /* Restore state so sysfs ignores VMX */
15119         l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
15120 }
15121
15122 static void vmx_exit(void)
15123 {
15124 #ifdef CONFIG_KEXEC_CORE
15125         RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
15126         synchronize_rcu();
15127 #endif
15128
15129         kvm_exit();
15130
15131 #if IS_ENABLED(CONFIG_HYPERV)
15132         if (static_branch_unlikely(&enable_evmcs)) {
15133                 int cpu;
15134                 struct hv_vp_assist_page *vp_ap;
15135                 /*
15136                  * Reset everything to support using non-enlightened VMCS
15137                  * access later (e.g. when we reload the module with
15138                  * enlightened_vmcs=0)
15139                  */
15140                 for_each_online_cpu(cpu) {
15141                         vp_ap = hv_get_vp_assist_page(cpu);
15142
15143                         if (!vp_ap)
15144                                 continue;
15145
15146                         vp_ap->current_nested_vmcs = 0;
15147                         vp_ap->enlighten_vmentry = 0;
15148                 }
15149
15150                 static_branch_disable(&enable_evmcs);
15151         }
15152 #endif
15153         vmx_cleanup_l1d_flush();
15154 }
15155 module_exit(vmx_exit);
15156
15157 static int __init vmx_init(void)
15158 {
15159         int r;
15160
15161 #if IS_ENABLED(CONFIG_HYPERV)
15162         /*
15163          * Enlightened VMCS usage should be recommended and the host needs
15164          * to support eVMCS v1 or above. We can also disable eVMCS support
15165          * with module parameter.
15166          */
15167         if (enlightened_vmcs &&
15168             ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
15169             (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
15170             KVM_EVMCS_VERSION) {
15171                 int cpu;
15172
15173                 /* Check that we have assist pages on all online CPUs */
15174                 for_each_online_cpu(cpu) {
15175                         if (!hv_get_vp_assist_page(cpu)) {
15176                                 enlightened_vmcs = false;
15177                                 break;
15178                         }
15179                 }
15180
15181                 if (enlightened_vmcs) {
15182                         pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
15183                         static_branch_enable(&enable_evmcs);
15184                 }
15185         } else {
15186                 enlightened_vmcs = false;
15187         }
15188 #endif
15189
15190         r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
15191                      __alignof__(struct vcpu_vmx), THIS_MODULE);
15192         if (r)
15193                 return r;
15194
15195         /*
15196          * Must be called after kvm_init() so enable_ept is properly set
15197          * up. Hand the parameter mitigation value in which was stored in
15198          * the pre module init parser. If no parameter was given, it will
15199          * contain 'auto' which will be turned into the default 'cond'
15200          * mitigation mode.
15201          */
15202         if (boot_cpu_has(X86_BUG_L1TF)) {
15203                 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
15204                 if (r) {
15205                         vmx_exit();
15206                         return r;
15207                 }
15208         }
15209
15210 #ifdef CONFIG_KEXEC_CORE
15211         rcu_assign_pointer(crash_vmclear_loaded_vmcss,
15212                            crash_vmclear_local_loaded_vmcss);
15213 #endif
15214         vmx_check_vmcs12_offsets();
15215
15216         return 0;
15217 }
15218 module_init(vmx_init);