Merge tag 'xtensa-20181128' of git://github.com/jcmvbkbc/linux-xtensa
[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 module_param(ple_gap, uint, 0444);
178
179 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
180 module_param(ple_window, uint, 0444);
181
182 /* Default doubles per-vcpu window every exit. */
183 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
184 module_param(ple_window_grow, uint, 0444);
185
186 /* Default resets per-vcpu window every exit to ple_window. */
187 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
188 module_param(ple_window_shrink, uint, 0444);
189
190 /* Default is to compute the maximum so we can never overflow. */
191 static unsigned int ple_window_max        = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
192 module_param(ple_window_max, uint, 0444);
193
194 extern const ulong vmx_return;
195 extern const ulong vmx_early_consistency_check_return;
196
197 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
198 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
199 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
200
201 /* Storage for pre module init parameter parsing */
202 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
203
204 static const struct {
205         const char *option;
206         bool for_parse;
207 } vmentry_l1d_param[] = {
208         [VMENTER_L1D_FLUSH_AUTO]         = {"auto", true},
209         [VMENTER_L1D_FLUSH_NEVER]        = {"never", true},
210         [VMENTER_L1D_FLUSH_COND]         = {"cond", true},
211         [VMENTER_L1D_FLUSH_ALWAYS]       = {"always", true},
212         [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
213         [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
214 };
215
216 #define L1D_CACHE_ORDER 4
217 static void *vmx_l1d_flush_pages;
218
219 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
220 {
221         struct page *page;
222         unsigned int i;
223
224         if (!enable_ept) {
225                 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
226                 return 0;
227         }
228
229         if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
230                 u64 msr;
231
232                 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
233                 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
234                         l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
235                         return 0;
236                 }
237         }
238
239         /* If set to auto use the default l1tf mitigation method */
240         if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
241                 switch (l1tf_mitigation) {
242                 case L1TF_MITIGATION_OFF:
243                         l1tf = VMENTER_L1D_FLUSH_NEVER;
244                         break;
245                 case L1TF_MITIGATION_FLUSH_NOWARN:
246                 case L1TF_MITIGATION_FLUSH:
247                 case L1TF_MITIGATION_FLUSH_NOSMT:
248                         l1tf = VMENTER_L1D_FLUSH_COND;
249                         break;
250                 case L1TF_MITIGATION_FULL:
251                 case L1TF_MITIGATION_FULL_FORCE:
252                         l1tf = VMENTER_L1D_FLUSH_ALWAYS;
253                         break;
254                 }
255         } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
256                 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
257         }
258
259         if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
260             !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
261                 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
262                 if (!page)
263                         return -ENOMEM;
264                 vmx_l1d_flush_pages = page_address(page);
265
266                 /*
267                  * Initialize each page with a different pattern in
268                  * order to protect against KSM in the nested
269                  * virtualization case.
270                  */
271                 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
272                         memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
273                                PAGE_SIZE);
274                 }
275         }
276
277         l1tf_vmx_mitigation = l1tf;
278
279         if (l1tf != VMENTER_L1D_FLUSH_NEVER)
280                 static_branch_enable(&vmx_l1d_should_flush);
281         else
282                 static_branch_disable(&vmx_l1d_should_flush);
283
284         if (l1tf == VMENTER_L1D_FLUSH_COND)
285                 static_branch_enable(&vmx_l1d_flush_cond);
286         else
287                 static_branch_disable(&vmx_l1d_flush_cond);
288         return 0;
289 }
290
291 static int vmentry_l1d_flush_parse(const char *s)
292 {
293         unsigned int i;
294
295         if (s) {
296                 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
297                         if (vmentry_l1d_param[i].for_parse &&
298                             sysfs_streq(s, vmentry_l1d_param[i].option))
299                                 return i;
300                 }
301         }
302         return -EINVAL;
303 }
304
305 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
306 {
307         int l1tf, ret;
308
309         l1tf = vmentry_l1d_flush_parse(s);
310         if (l1tf < 0)
311                 return l1tf;
312
313         if (!boot_cpu_has(X86_BUG_L1TF))
314                 return 0;
315
316         /*
317          * Has vmx_init() run already? If not then this is the pre init
318          * parameter parsing. In that case just store the value and let
319          * vmx_init() do the proper setup after enable_ept has been
320          * established.
321          */
322         if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
323                 vmentry_l1d_flush_param = l1tf;
324                 return 0;
325         }
326
327         mutex_lock(&vmx_l1d_flush_mutex);
328         ret = vmx_setup_l1d_flush(l1tf);
329         mutex_unlock(&vmx_l1d_flush_mutex);
330         return ret;
331 }
332
333 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
334 {
335         if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
336                 return sprintf(s, "???\n");
337
338         return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
339 }
340
341 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
342         .set = vmentry_l1d_flush_set,
343         .get = vmentry_l1d_flush_get,
344 };
345 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
346
347 enum ept_pointers_status {
348         EPT_POINTERS_CHECK = 0,
349         EPT_POINTERS_MATCH = 1,
350         EPT_POINTERS_MISMATCH = 2
351 };
352
353 struct kvm_vmx {
354         struct kvm kvm;
355
356         unsigned int tss_addr;
357         bool ept_identity_pagetable_done;
358         gpa_t ept_identity_map_addr;
359
360         enum ept_pointers_status ept_pointers_match;
361         spinlock_t ept_pointer_lock;
362 };
363
364 #define NR_AUTOLOAD_MSRS 8
365
366 struct vmcs_hdr {
367         u32 revision_id:31;
368         u32 shadow_vmcs:1;
369 };
370
371 struct vmcs {
372         struct vmcs_hdr hdr;
373         u32 abort;
374         char data[0];
375 };
376
377 /*
378  * vmcs_host_state tracks registers that are loaded from the VMCS on VMEXIT
379  * and whose values change infrequently, but are not constant.  I.e. this is
380  * used as a write-through cache of the corresponding VMCS fields.
381  */
382 struct vmcs_host_state {
383         unsigned long cr3;      /* May not match real cr3 */
384         unsigned long cr4;      /* May not match real cr4 */
385         unsigned long gs_base;
386         unsigned long fs_base;
387
388         u16           fs_sel, gs_sel, ldt_sel;
389 #ifdef CONFIG_X86_64
390         u16           ds_sel, es_sel;
391 #endif
392 };
393
394 /*
395  * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
396  * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
397  * loaded on this CPU (so we can clear them if the CPU goes down).
398  */
399 struct loaded_vmcs {
400         struct vmcs *vmcs;
401         struct vmcs *shadow_vmcs;
402         int cpu;
403         bool launched;
404         bool nmi_known_unmasked;
405         bool hv_timer_armed;
406         /* Support for vnmi-less CPUs */
407         int soft_vnmi_blocked;
408         ktime_t entry_time;
409         s64 vnmi_blocked_time;
410         unsigned long *msr_bitmap;
411         struct list_head loaded_vmcss_on_cpu_link;
412         struct vmcs_host_state host_state;
413 };
414
415 struct shared_msr_entry {
416         unsigned index;
417         u64 data;
418         u64 mask;
419 };
420
421 /*
422  * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
423  * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
424  * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
425  * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
426  * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
427  * More than one of these structures may exist, if L1 runs multiple L2 guests.
428  * nested_vmx_run() will use the data here to build the vmcs02: a VMCS for the
429  * underlying hardware which will be used to run L2.
430  * This structure is packed to ensure that its layout is identical across
431  * machines (necessary for live migration).
432  *
433  * IMPORTANT: Changing the layout of existing fields in this structure
434  * will break save/restore compatibility with older kvm releases. When
435  * adding new fields, either use space in the reserved padding* arrays
436  * or add the new fields to the end of the structure.
437  */
438 typedef u64 natural_width;
439 struct __packed vmcs12 {
440         /* According to the Intel spec, a VMCS region must start with the
441          * following two fields. Then follow implementation-specific data.
442          */
443         struct vmcs_hdr hdr;
444         u32 abort;
445
446         u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
447         u32 padding[7]; /* room for future expansion */
448
449         u64 io_bitmap_a;
450         u64 io_bitmap_b;
451         u64 msr_bitmap;
452         u64 vm_exit_msr_store_addr;
453         u64 vm_exit_msr_load_addr;
454         u64 vm_entry_msr_load_addr;
455         u64 tsc_offset;
456         u64 virtual_apic_page_addr;
457         u64 apic_access_addr;
458         u64 posted_intr_desc_addr;
459         u64 ept_pointer;
460         u64 eoi_exit_bitmap0;
461         u64 eoi_exit_bitmap1;
462         u64 eoi_exit_bitmap2;
463         u64 eoi_exit_bitmap3;
464         u64 xss_exit_bitmap;
465         u64 guest_physical_address;
466         u64 vmcs_link_pointer;
467         u64 guest_ia32_debugctl;
468         u64 guest_ia32_pat;
469         u64 guest_ia32_efer;
470         u64 guest_ia32_perf_global_ctrl;
471         u64 guest_pdptr0;
472         u64 guest_pdptr1;
473         u64 guest_pdptr2;
474         u64 guest_pdptr3;
475         u64 guest_bndcfgs;
476         u64 host_ia32_pat;
477         u64 host_ia32_efer;
478         u64 host_ia32_perf_global_ctrl;
479         u64 vmread_bitmap;
480         u64 vmwrite_bitmap;
481         u64 vm_function_control;
482         u64 eptp_list_address;
483         u64 pml_address;
484         u64 padding64[3]; /* room for future expansion */
485         /*
486          * To allow migration of L1 (complete with its L2 guests) between
487          * machines of different natural widths (32 or 64 bit), we cannot have
488          * unsigned long fields with no explict size. We use u64 (aliased
489          * natural_width) instead. Luckily, x86 is little-endian.
490          */
491         natural_width cr0_guest_host_mask;
492         natural_width cr4_guest_host_mask;
493         natural_width cr0_read_shadow;
494         natural_width cr4_read_shadow;
495         natural_width cr3_target_value0;
496         natural_width cr3_target_value1;
497         natural_width cr3_target_value2;
498         natural_width cr3_target_value3;
499         natural_width exit_qualification;
500         natural_width guest_linear_address;
501         natural_width guest_cr0;
502         natural_width guest_cr3;
503         natural_width guest_cr4;
504         natural_width guest_es_base;
505         natural_width guest_cs_base;
506         natural_width guest_ss_base;
507         natural_width guest_ds_base;
508         natural_width guest_fs_base;
509         natural_width guest_gs_base;
510         natural_width guest_ldtr_base;
511         natural_width guest_tr_base;
512         natural_width guest_gdtr_base;
513         natural_width guest_idtr_base;
514         natural_width guest_dr7;
515         natural_width guest_rsp;
516         natural_width guest_rip;
517         natural_width guest_rflags;
518         natural_width guest_pending_dbg_exceptions;
519         natural_width guest_sysenter_esp;
520         natural_width guest_sysenter_eip;
521         natural_width host_cr0;
522         natural_width host_cr3;
523         natural_width host_cr4;
524         natural_width host_fs_base;
525         natural_width host_gs_base;
526         natural_width host_tr_base;
527         natural_width host_gdtr_base;
528         natural_width host_idtr_base;
529         natural_width host_ia32_sysenter_esp;
530         natural_width host_ia32_sysenter_eip;
531         natural_width host_rsp;
532         natural_width host_rip;
533         natural_width paddingl[8]; /* room for future expansion */
534         u32 pin_based_vm_exec_control;
535         u32 cpu_based_vm_exec_control;
536         u32 exception_bitmap;
537         u32 page_fault_error_code_mask;
538         u32 page_fault_error_code_match;
539         u32 cr3_target_count;
540         u32 vm_exit_controls;
541         u32 vm_exit_msr_store_count;
542         u32 vm_exit_msr_load_count;
543         u32 vm_entry_controls;
544         u32 vm_entry_msr_load_count;
545         u32 vm_entry_intr_info_field;
546         u32 vm_entry_exception_error_code;
547         u32 vm_entry_instruction_len;
548         u32 tpr_threshold;
549         u32 secondary_vm_exec_control;
550         u32 vm_instruction_error;
551         u32 vm_exit_reason;
552         u32 vm_exit_intr_info;
553         u32 vm_exit_intr_error_code;
554         u32 idt_vectoring_info_field;
555         u32 idt_vectoring_error_code;
556         u32 vm_exit_instruction_len;
557         u32 vmx_instruction_info;
558         u32 guest_es_limit;
559         u32 guest_cs_limit;
560         u32 guest_ss_limit;
561         u32 guest_ds_limit;
562         u32 guest_fs_limit;
563         u32 guest_gs_limit;
564         u32 guest_ldtr_limit;
565         u32 guest_tr_limit;
566         u32 guest_gdtr_limit;
567         u32 guest_idtr_limit;
568         u32 guest_es_ar_bytes;
569         u32 guest_cs_ar_bytes;
570         u32 guest_ss_ar_bytes;
571         u32 guest_ds_ar_bytes;
572         u32 guest_fs_ar_bytes;
573         u32 guest_gs_ar_bytes;
574         u32 guest_ldtr_ar_bytes;
575         u32 guest_tr_ar_bytes;
576         u32 guest_interruptibility_info;
577         u32 guest_activity_state;
578         u32 guest_sysenter_cs;
579         u32 host_ia32_sysenter_cs;
580         u32 vmx_preemption_timer_value;
581         u32 padding32[7]; /* room for future expansion */
582         u16 virtual_processor_id;
583         u16 posted_intr_nv;
584         u16 guest_es_selector;
585         u16 guest_cs_selector;
586         u16 guest_ss_selector;
587         u16 guest_ds_selector;
588         u16 guest_fs_selector;
589         u16 guest_gs_selector;
590         u16 guest_ldtr_selector;
591         u16 guest_tr_selector;
592         u16 guest_intr_status;
593         u16 host_es_selector;
594         u16 host_cs_selector;
595         u16 host_ss_selector;
596         u16 host_ds_selector;
597         u16 host_fs_selector;
598         u16 host_gs_selector;
599         u16 host_tr_selector;
600         u16 guest_pml_index;
601 };
602
603 /*
604  * For save/restore compatibility, the vmcs12 field offsets must not change.
605  */
606 #define CHECK_OFFSET(field, loc)                                \
607         BUILD_BUG_ON_MSG(offsetof(struct vmcs12, field) != (loc),       \
608                 "Offset of " #field " in struct vmcs12 has changed.")
609
610 static inline void vmx_check_vmcs12_offsets(void) {
611         CHECK_OFFSET(hdr, 0);
612         CHECK_OFFSET(abort, 4);
613         CHECK_OFFSET(launch_state, 8);
614         CHECK_OFFSET(io_bitmap_a, 40);
615         CHECK_OFFSET(io_bitmap_b, 48);
616         CHECK_OFFSET(msr_bitmap, 56);
617         CHECK_OFFSET(vm_exit_msr_store_addr, 64);
618         CHECK_OFFSET(vm_exit_msr_load_addr, 72);
619         CHECK_OFFSET(vm_entry_msr_load_addr, 80);
620         CHECK_OFFSET(tsc_offset, 88);
621         CHECK_OFFSET(virtual_apic_page_addr, 96);
622         CHECK_OFFSET(apic_access_addr, 104);
623         CHECK_OFFSET(posted_intr_desc_addr, 112);
624         CHECK_OFFSET(ept_pointer, 120);
625         CHECK_OFFSET(eoi_exit_bitmap0, 128);
626         CHECK_OFFSET(eoi_exit_bitmap1, 136);
627         CHECK_OFFSET(eoi_exit_bitmap2, 144);
628         CHECK_OFFSET(eoi_exit_bitmap3, 152);
629         CHECK_OFFSET(xss_exit_bitmap, 160);
630         CHECK_OFFSET(guest_physical_address, 168);
631         CHECK_OFFSET(vmcs_link_pointer, 176);
632         CHECK_OFFSET(guest_ia32_debugctl, 184);
633         CHECK_OFFSET(guest_ia32_pat, 192);
634         CHECK_OFFSET(guest_ia32_efer, 200);
635         CHECK_OFFSET(guest_ia32_perf_global_ctrl, 208);
636         CHECK_OFFSET(guest_pdptr0, 216);
637         CHECK_OFFSET(guest_pdptr1, 224);
638         CHECK_OFFSET(guest_pdptr2, 232);
639         CHECK_OFFSET(guest_pdptr3, 240);
640         CHECK_OFFSET(guest_bndcfgs, 248);
641         CHECK_OFFSET(host_ia32_pat, 256);
642         CHECK_OFFSET(host_ia32_efer, 264);
643         CHECK_OFFSET(host_ia32_perf_global_ctrl, 272);
644         CHECK_OFFSET(vmread_bitmap, 280);
645         CHECK_OFFSET(vmwrite_bitmap, 288);
646         CHECK_OFFSET(vm_function_control, 296);
647         CHECK_OFFSET(eptp_list_address, 304);
648         CHECK_OFFSET(pml_address, 312);
649         CHECK_OFFSET(cr0_guest_host_mask, 344);
650         CHECK_OFFSET(cr4_guest_host_mask, 352);
651         CHECK_OFFSET(cr0_read_shadow, 360);
652         CHECK_OFFSET(cr4_read_shadow, 368);
653         CHECK_OFFSET(cr3_target_value0, 376);
654         CHECK_OFFSET(cr3_target_value1, 384);
655         CHECK_OFFSET(cr3_target_value2, 392);
656         CHECK_OFFSET(cr3_target_value3, 400);
657         CHECK_OFFSET(exit_qualification, 408);
658         CHECK_OFFSET(guest_linear_address, 416);
659         CHECK_OFFSET(guest_cr0, 424);
660         CHECK_OFFSET(guest_cr3, 432);
661         CHECK_OFFSET(guest_cr4, 440);
662         CHECK_OFFSET(guest_es_base, 448);
663         CHECK_OFFSET(guest_cs_base, 456);
664         CHECK_OFFSET(guest_ss_base, 464);
665         CHECK_OFFSET(guest_ds_base, 472);
666         CHECK_OFFSET(guest_fs_base, 480);
667         CHECK_OFFSET(guest_gs_base, 488);
668         CHECK_OFFSET(guest_ldtr_base, 496);
669         CHECK_OFFSET(guest_tr_base, 504);
670         CHECK_OFFSET(guest_gdtr_base, 512);
671         CHECK_OFFSET(guest_idtr_base, 520);
672         CHECK_OFFSET(guest_dr7, 528);
673         CHECK_OFFSET(guest_rsp, 536);
674         CHECK_OFFSET(guest_rip, 544);
675         CHECK_OFFSET(guest_rflags, 552);
676         CHECK_OFFSET(guest_pending_dbg_exceptions, 560);
677         CHECK_OFFSET(guest_sysenter_esp, 568);
678         CHECK_OFFSET(guest_sysenter_eip, 576);
679         CHECK_OFFSET(host_cr0, 584);
680         CHECK_OFFSET(host_cr3, 592);
681         CHECK_OFFSET(host_cr4, 600);
682         CHECK_OFFSET(host_fs_base, 608);
683         CHECK_OFFSET(host_gs_base, 616);
684         CHECK_OFFSET(host_tr_base, 624);
685         CHECK_OFFSET(host_gdtr_base, 632);
686         CHECK_OFFSET(host_idtr_base, 640);
687         CHECK_OFFSET(host_ia32_sysenter_esp, 648);
688         CHECK_OFFSET(host_ia32_sysenter_eip, 656);
689         CHECK_OFFSET(host_rsp, 664);
690         CHECK_OFFSET(host_rip, 672);
691         CHECK_OFFSET(pin_based_vm_exec_control, 744);
692         CHECK_OFFSET(cpu_based_vm_exec_control, 748);
693         CHECK_OFFSET(exception_bitmap, 752);
694         CHECK_OFFSET(page_fault_error_code_mask, 756);
695         CHECK_OFFSET(page_fault_error_code_match, 760);
696         CHECK_OFFSET(cr3_target_count, 764);
697         CHECK_OFFSET(vm_exit_controls, 768);
698         CHECK_OFFSET(vm_exit_msr_store_count, 772);
699         CHECK_OFFSET(vm_exit_msr_load_count, 776);
700         CHECK_OFFSET(vm_entry_controls, 780);
701         CHECK_OFFSET(vm_entry_msr_load_count, 784);
702         CHECK_OFFSET(vm_entry_intr_info_field, 788);
703         CHECK_OFFSET(vm_entry_exception_error_code, 792);
704         CHECK_OFFSET(vm_entry_instruction_len, 796);
705         CHECK_OFFSET(tpr_threshold, 800);
706         CHECK_OFFSET(secondary_vm_exec_control, 804);
707         CHECK_OFFSET(vm_instruction_error, 808);
708         CHECK_OFFSET(vm_exit_reason, 812);
709         CHECK_OFFSET(vm_exit_intr_info, 816);
710         CHECK_OFFSET(vm_exit_intr_error_code, 820);
711         CHECK_OFFSET(idt_vectoring_info_field, 824);
712         CHECK_OFFSET(idt_vectoring_error_code, 828);
713         CHECK_OFFSET(vm_exit_instruction_len, 832);
714         CHECK_OFFSET(vmx_instruction_info, 836);
715         CHECK_OFFSET(guest_es_limit, 840);
716         CHECK_OFFSET(guest_cs_limit, 844);
717         CHECK_OFFSET(guest_ss_limit, 848);
718         CHECK_OFFSET(guest_ds_limit, 852);
719         CHECK_OFFSET(guest_fs_limit, 856);
720         CHECK_OFFSET(guest_gs_limit, 860);
721         CHECK_OFFSET(guest_ldtr_limit, 864);
722         CHECK_OFFSET(guest_tr_limit, 868);
723         CHECK_OFFSET(guest_gdtr_limit, 872);
724         CHECK_OFFSET(guest_idtr_limit, 876);
725         CHECK_OFFSET(guest_es_ar_bytes, 880);
726         CHECK_OFFSET(guest_cs_ar_bytes, 884);
727         CHECK_OFFSET(guest_ss_ar_bytes, 888);
728         CHECK_OFFSET(guest_ds_ar_bytes, 892);
729         CHECK_OFFSET(guest_fs_ar_bytes, 896);
730         CHECK_OFFSET(guest_gs_ar_bytes, 900);
731         CHECK_OFFSET(guest_ldtr_ar_bytes, 904);
732         CHECK_OFFSET(guest_tr_ar_bytes, 908);
733         CHECK_OFFSET(guest_interruptibility_info, 912);
734         CHECK_OFFSET(guest_activity_state, 916);
735         CHECK_OFFSET(guest_sysenter_cs, 920);
736         CHECK_OFFSET(host_ia32_sysenter_cs, 924);
737         CHECK_OFFSET(vmx_preemption_timer_value, 928);
738         CHECK_OFFSET(virtual_processor_id, 960);
739         CHECK_OFFSET(posted_intr_nv, 962);
740         CHECK_OFFSET(guest_es_selector, 964);
741         CHECK_OFFSET(guest_cs_selector, 966);
742         CHECK_OFFSET(guest_ss_selector, 968);
743         CHECK_OFFSET(guest_ds_selector, 970);
744         CHECK_OFFSET(guest_fs_selector, 972);
745         CHECK_OFFSET(guest_gs_selector, 974);
746         CHECK_OFFSET(guest_ldtr_selector, 976);
747         CHECK_OFFSET(guest_tr_selector, 978);
748         CHECK_OFFSET(guest_intr_status, 980);
749         CHECK_OFFSET(host_es_selector, 982);
750         CHECK_OFFSET(host_cs_selector, 984);
751         CHECK_OFFSET(host_ss_selector, 986);
752         CHECK_OFFSET(host_ds_selector, 988);
753         CHECK_OFFSET(host_fs_selector, 990);
754         CHECK_OFFSET(host_gs_selector, 992);
755         CHECK_OFFSET(host_tr_selector, 994);
756         CHECK_OFFSET(guest_pml_index, 996);
757 }
758
759 /*
760  * VMCS12_REVISION is an arbitrary id that should be changed if the content or
761  * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
762  * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
763  *
764  * IMPORTANT: Changing this value will break save/restore compatibility with
765  * older kvm releases.
766  */
767 #define VMCS12_REVISION 0x11e57ed0
768
769 /*
770  * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
771  * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
772  * current implementation, 4K are reserved to avoid future complications.
773  */
774 #define VMCS12_SIZE 0x1000
775
776 /*
777  * VMCS12_MAX_FIELD_INDEX is the highest index value used in any
778  * supported VMCS12 field encoding.
779  */
780 #define VMCS12_MAX_FIELD_INDEX 0x17
781
782 struct nested_vmx_msrs {
783         /*
784          * We only store the "true" versions of the VMX capability MSRs. We
785          * generate the "non-true" versions by setting the must-be-1 bits
786          * according to the SDM.
787          */
788         u32 procbased_ctls_low;
789         u32 procbased_ctls_high;
790         u32 secondary_ctls_low;
791         u32 secondary_ctls_high;
792         u32 pinbased_ctls_low;
793         u32 pinbased_ctls_high;
794         u32 exit_ctls_low;
795         u32 exit_ctls_high;
796         u32 entry_ctls_low;
797         u32 entry_ctls_high;
798         u32 misc_low;
799         u32 misc_high;
800         u32 ept_caps;
801         u32 vpid_caps;
802         u64 basic;
803         u64 cr0_fixed0;
804         u64 cr0_fixed1;
805         u64 cr4_fixed0;
806         u64 cr4_fixed1;
807         u64 vmcs_enum;
808         u64 vmfunc_controls;
809 };
810
811 /*
812  * The nested_vmx structure is part of vcpu_vmx, and holds information we need
813  * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
814  */
815 struct nested_vmx {
816         /* Has the level1 guest done vmxon? */
817         bool vmxon;
818         gpa_t vmxon_ptr;
819         bool pml_full;
820
821         /* The guest-physical address of the current VMCS L1 keeps for L2 */
822         gpa_t current_vmptr;
823         /*
824          * Cache of the guest's VMCS, existing outside of guest memory.
825          * Loaded from guest memory during VMPTRLD. Flushed to guest
826          * memory during VMCLEAR and VMPTRLD.
827          */
828         struct vmcs12 *cached_vmcs12;
829         /*
830          * Cache of the guest's shadow VMCS, existing outside of guest
831          * memory. Loaded from guest memory during VM entry. Flushed
832          * to guest memory during VM exit.
833          */
834         struct vmcs12 *cached_shadow_vmcs12;
835         /*
836          * Indicates if the shadow vmcs or enlightened vmcs must be updated
837          * with the data held by struct vmcs12.
838          */
839         bool need_vmcs12_sync;
840         bool dirty_vmcs12;
841
842         /*
843          * vmcs02 has been initialized, i.e. state that is constant for
844          * vmcs02 has been written to the backing VMCS.  Initialization
845          * is delayed until L1 actually attempts to run a nested VM.
846          */
847         bool vmcs02_initialized;
848
849         bool change_vmcs01_virtual_apic_mode;
850
851         /*
852          * Enlightened VMCS has been enabled. It does not mean that L1 has to
853          * use it. However, VMX features available to L1 will be limited based
854          * on what the enlightened VMCS supports.
855          */
856         bool enlightened_vmcs_enabled;
857
858         /* L2 must run next, and mustn't decide to exit to L1. */
859         bool nested_run_pending;
860
861         struct loaded_vmcs vmcs02;
862
863         /*
864          * Guest pages referred to in the vmcs02 with host-physical
865          * pointers, so we must keep them pinned while L2 runs.
866          */
867         struct page *apic_access_page;
868         struct page *virtual_apic_page;
869         struct page *pi_desc_page;
870         struct pi_desc *pi_desc;
871         bool pi_pending;
872         u16 posted_intr_nv;
873
874         struct hrtimer preemption_timer;
875         bool preemption_timer_expired;
876
877         /* to migrate it to L2 if VM_ENTRY_LOAD_DEBUG_CONTROLS is off */
878         u64 vmcs01_debugctl;
879         u64 vmcs01_guest_bndcfgs;
880
881         u16 vpid02;
882         u16 last_vpid;
883
884         struct nested_vmx_msrs msrs;
885
886         /* SMM related state */
887         struct {
888                 /* in VMX operation on SMM entry? */
889                 bool vmxon;
890                 /* in guest mode on SMM entry? */
891                 bool guest_mode;
892         } smm;
893
894         gpa_t hv_evmcs_vmptr;
895         struct page *hv_evmcs_page;
896         struct hv_enlightened_vmcs *hv_evmcs;
897 };
898
899 #define POSTED_INTR_ON  0
900 #define POSTED_INTR_SN  1
901
902 /* Posted-Interrupt Descriptor */
903 struct pi_desc {
904         u32 pir[8];     /* Posted interrupt requested */
905         union {
906                 struct {
907                                 /* bit 256 - Outstanding Notification */
908                         u16     on      : 1,
909                                 /* bit 257 - Suppress Notification */
910                                 sn      : 1,
911                                 /* bit 271:258 - Reserved */
912                                 rsvd_1  : 14;
913                                 /* bit 279:272 - Notification Vector */
914                         u8      nv;
915                                 /* bit 287:280 - Reserved */
916                         u8      rsvd_2;
917                                 /* bit 319:288 - Notification Destination */
918                         u32     ndst;
919                 };
920                 u64 control;
921         };
922         u32 rsvd[6];
923 } __aligned(64);
924
925 static bool pi_test_and_set_on(struct pi_desc *pi_desc)
926 {
927         return test_and_set_bit(POSTED_INTR_ON,
928                         (unsigned long *)&pi_desc->control);
929 }
930
931 static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
932 {
933         return test_and_clear_bit(POSTED_INTR_ON,
934                         (unsigned long *)&pi_desc->control);
935 }
936
937 static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
938 {
939         return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
940 }
941
942 static inline void pi_clear_sn(struct pi_desc *pi_desc)
943 {
944         return clear_bit(POSTED_INTR_SN,
945                         (unsigned long *)&pi_desc->control);
946 }
947
948 static inline void pi_set_sn(struct pi_desc *pi_desc)
949 {
950         return set_bit(POSTED_INTR_SN,
951                         (unsigned long *)&pi_desc->control);
952 }
953
954 static inline void pi_clear_on(struct pi_desc *pi_desc)
955 {
956         clear_bit(POSTED_INTR_ON,
957                   (unsigned long *)&pi_desc->control);
958 }
959
960 static inline int pi_test_on(struct pi_desc *pi_desc)
961 {
962         return test_bit(POSTED_INTR_ON,
963                         (unsigned long *)&pi_desc->control);
964 }
965
966 static inline int pi_test_sn(struct pi_desc *pi_desc)
967 {
968         return test_bit(POSTED_INTR_SN,
969                         (unsigned long *)&pi_desc->control);
970 }
971
972 struct vmx_msrs {
973         unsigned int            nr;
974         struct vmx_msr_entry    val[NR_AUTOLOAD_MSRS];
975 };
976
977 struct vcpu_vmx {
978         struct kvm_vcpu       vcpu;
979         unsigned long         host_rsp;
980         u8                    fail;
981         u8                    msr_bitmap_mode;
982         u32                   exit_intr_info;
983         u32                   idt_vectoring_info;
984         ulong                 rflags;
985         struct shared_msr_entry *guest_msrs;
986         int                   nmsrs;
987         int                   save_nmsrs;
988         bool                  guest_msrs_dirty;
989         unsigned long         host_idt_base;
990 #ifdef CONFIG_X86_64
991         u64                   msr_host_kernel_gs_base;
992         u64                   msr_guest_kernel_gs_base;
993 #endif
994
995         u64                   arch_capabilities;
996         u64                   spec_ctrl;
997
998         u32 vm_entry_controls_shadow;
999         u32 vm_exit_controls_shadow;
1000         u32 secondary_exec_control;
1001
1002         /*
1003          * loaded_vmcs points to the VMCS currently used in this vcpu. For a
1004          * non-nested (L1) guest, it always points to vmcs01. For a nested
1005          * guest (L2), it points to a different VMCS.  loaded_cpu_state points
1006          * to the VMCS whose state is loaded into the CPU registers that only
1007          * need to be switched when transitioning to/from the kernel; a NULL
1008          * value indicates that host state is loaded.
1009          */
1010         struct loaded_vmcs    vmcs01;
1011         struct loaded_vmcs   *loaded_vmcs;
1012         struct loaded_vmcs   *loaded_cpu_state;
1013         bool                  __launched; /* temporary, used in vmx_vcpu_run */
1014         struct msr_autoload {
1015                 struct vmx_msrs guest;
1016                 struct vmx_msrs host;
1017         } msr_autoload;
1018
1019         struct {
1020                 int vm86_active;
1021                 ulong save_rflags;
1022                 struct kvm_segment segs[8];
1023         } rmode;
1024         struct {
1025                 u32 bitmask; /* 4 bits per segment (1 bit per field) */
1026                 struct kvm_save_segment {
1027                         u16 selector;
1028                         unsigned long base;
1029                         u32 limit;
1030                         u32 ar;
1031                 } seg[8];
1032         } segment_cache;
1033         int vpid;
1034         bool emulation_required;
1035
1036         u32 exit_reason;
1037
1038         /* Posted interrupt descriptor */
1039         struct pi_desc pi_desc;
1040
1041         /* Support for a guest hypervisor (nested VMX) */
1042         struct nested_vmx nested;
1043
1044         /* Dynamic PLE window. */
1045         int ple_window;
1046         bool ple_window_dirty;
1047
1048         bool req_immediate_exit;
1049
1050         /* Support for PML */
1051 #define PML_ENTITY_NUM          512
1052         struct page *pml_pg;
1053
1054         /* apic deadline value in host tsc */
1055         u64 hv_deadline_tsc;
1056
1057         u64 current_tsc_ratio;
1058
1059         u32 host_pkru;
1060
1061         unsigned long host_debugctlmsr;
1062
1063         /*
1064          * Only bits masked by msr_ia32_feature_control_valid_bits can be set in
1065          * msr_ia32_feature_control. FEATURE_CONTROL_LOCKED is always included
1066          * in msr_ia32_feature_control_valid_bits.
1067          */
1068         u64 msr_ia32_feature_control;
1069         u64 msr_ia32_feature_control_valid_bits;
1070         u64 ept_pointer;
1071 };
1072
1073 enum segment_cache_field {
1074         SEG_FIELD_SEL = 0,
1075         SEG_FIELD_BASE = 1,
1076         SEG_FIELD_LIMIT = 2,
1077         SEG_FIELD_AR = 3,
1078
1079         SEG_FIELD_NR = 4
1080 };
1081
1082 static inline struct kvm_vmx *to_kvm_vmx(struct kvm *kvm)
1083 {
1084         return container_of(kvm, struct kvm_vmx, kvm);
1085 }
1086
1087 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
1088 {
1089         return container_of(vcpu, struct vcpu_vmx, vcpu);
1090 }
1091
1092 static struct pi_desc *vcpu_to_pi_desc(struct kvm_vcpu *vcpu)
1093 {
1094         return &(to_vmx(vcpu)->pi_desc);
1095 }
1096
1097 #define ROL16(val, n) ((u16)(((u16)(val) << (n)) | ((u16)(val) >> (16 - (n)))))
1098 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
1099 #define FIELD(number, name)     [ROL16(number, 6)] = VMCS12_OFFSET(name)
1100 #define FIELD64(number, name)                                           \
1101         FIELD(number, name),                                            \
1102         [ROL16(number##_HIGH, 6)] = VMCS12_OFFSET(name) + sizeof(u32)
1103
1104
1105 static u16 shadow_read_only_fields[] = {
1106 #define SHADOW_FIELD_RO(x) x,
1107 #include "vmx_shadow_fields.h"
1108 };
1109 static int max_shadow_read_only_fields =
1110         ARRAY_SIZE(shadow_read_only_fields);
1111
1112 static u16 shadow_read_write_fields[] = {
1113 #define SHADOW_FIELD_RW(x) x,
1114 #include "vmx_shadow_fields.h"
1115 };
1116 static int max_shadow_read_write_fields =
1117         ARRAY_SIZE(shadow_read_write_fields);
1118
1119 static const unsigned short vmcs_field_to_offset_table[] = {
1120         FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
1121         FIELD(POSTED_INTR_NV, posted_intr_nv),
1122         FIELD(GUEST_ES_SELECTOR, guest_es_selector),
1123         FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
1124         FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
1125         FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
1126         FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
1127         FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
1128         FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
1129         FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
1130         FIELD(GUEST_INTR_STATUS, guest_intr_status),
1131         FIELD(GUEST_PML_INDEX, guest_pml_index),
1132         FIELD(HOST_ES_SELECTOR, host_es_selector),
1133         FIELD(HOST_CS_SELECTOR, host_cs_selector),
1134         FIELD(HOST_SS_SELECTOR, host_ss_selector),
1135         FIELD(HOST_DS_SELECTOR, host_ds_selector),
1136         FIELD(HOST_FS_SELECTOR, host_fs_selector),
1137         FIELD(HOST_GS_SELECTOR, host_gs_selector),
1138         FIELD(HOST_TR_SELECTOR, host_tr_selector),
1139         FIELD64(IO_BITMAP_A, io_bitmap_a),
1140         FIELD64(IO_BITMAP_B, io_bitmap_b),
1141         FIELD64(MSR_BITMAP, msr_bitmap),
1142         FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
1143         FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
1144         FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
1145         FIELD64(PML_ADDRESS, pml_address),
1146         FIELD64(TSC_OFFSET, tsc_offset),
1147         FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
1148         FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
1149         FIELD64(POSTED_INTR_DESC_ADDR, posted_intr_desc_addr),
1150         FIELD64(VM_FUNCTION_CONTROL, vm_function_control),
1151         FIELD64(EPT_POINTER, ept_pointer),
1152         FIELD64(EOI_EXIT_BITMAP0, eoi_exit_bitmap0),
1153         FIELD64(EOI_EXIT_BITMAP1, eoi_exit_bitmap1),
1154         FIELD64(EOI_EXIT_BITMAP2, eoi_exit_bitmap2),
1155         FIELD64(EOI_EXIT_BITMAP3, eoi_exit_bitmap3),
1156         FIELD64(EPTP_LIST_ADDRESS, eptp_list_address),
1157         FIELD64(VMREAD_BITMAP, vmread_bitmap),
1158         FIELD64(VMWRITE_BITMAP, vmwrite_bitmap),
1159         FIELD64(XSS_EXIT_BITMAP, xss_exit_bitmap),
1160         FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
1161         FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
1162         FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
1163         FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
1164         FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
1165         FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
1166         FIELD64(GUEST_PDPTR0, guest_pdptr0),
1167         FIELD64(GUEST_PDPTR1, guest_pdptr1),
1168         FIELD64(GUEST_PDPTR2, guest_pdptr2),
1169         FIELD64(GUEST_PDPTR3, guest_pdptr3),
1170         FIELD64(GUEST_BNDCFGS, guest_bndcfgs),
1171         FIELD64(HOST_IA32_PAT, host_ia32_pat),
1172         FIELD64(HOST_IA32_EFER, host_ia32_efer),
1173         FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
1174         FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
1175         FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
1176         FIELD(EXCEPTION_BITMAP, exception_bitmap),
1177         FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
1178         FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
1179         FIELD(CR3_TARGET_COUNT, cr3_target_count),
1180         FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
1181         FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
1182         FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
1183         FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
1184         FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
1185         FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
1186         FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
1187         FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
1188         FIELD(TPR_THRESHOLD, tpr_threshold),
1189         FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
1190         FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
1191         FIELD(VM_EXIT_REASON, vm_exit_reason),
1192         FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
1193         FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
1194         FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
1195         FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
1196         FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
1197         FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
1198         FIELD(GUEST_ES_LIMIT, guest_es_limit),
1199         FIELD(GUEST_CS_LIMIT, guest_cs_limit),
1200         FIELD(GUEST_SS_LIMIT, guest_ss_limit),
1201         FIELD(GUEST_DS_LIMIT, guest_ds_limit),
1202         FIELD(GUEST_FS_LIMIT, guest_fs_limit),
1203         FIELD(GUEST_GS_LIMIT, guest_gs_limit),
1204         FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
1205         FIELD(GUEST_TR_LIMIT, guest_tr_limit),
1206         FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
1207         FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
1208         FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
1209         FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
1210         FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
1211         FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
1212         FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
1213         FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
1214         FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
1215         FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
1216         FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
1217         FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
1218         FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
1219         FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
1220         FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
1221         FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
1222         FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
1223         FIELD(CR0_READ_SHADOW, cr0_read_shadow),
1224         FIELD(CR4_READ_SHADOW, cr4_read_shadow),
1225         FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
1226         FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
1227         FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
1228         FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
1229         FIELD(EXIT_QUALIFICATION, exit_qualification),
1230         FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
1231         FIELD(GUEST_CR0, guest_cr0),
1232         FIELD(GUEST_CR3, guest_cr3),
1233         FIELD(GUEST_CR4, guest_cr4),
1234         FIELD(GUEST_ES_BASE, guest_es_base),
1235         FIELD(GUEST_CS_BASE, guest_cs_base),
1236         FIELD(GUEST_SS_BASE, guest_ss_base),
1237         FIELD(GUEST_DS_BASE, guest_ds_base),
1238         FIELD(GUEST_FS_BASE, guest_fs_base),
1239         FIELD(GUEST_GS_BASE, guest_gs_base),
1240         FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
1241         FIELD(GUEST_TR_BASE, guest_tr_base),
1242         FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
1243         FIELD(GUEST_IDTR_BASE, guest_idtr_base),
1244         FIELD(GUEST_DR7, guest_dr7),
1245         FIELD(GUEST_RSP, guest_rsp),
1246         FIELD(GUEST_RIP, guest_rip),
1247         FIELD(GUEST_RFLAGS, guest_rflags),
1248         FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
1249         FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
1250         FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
1251         FIELD(HOST_CR0, host_cr0),
1252         FIELD(HOST_CR3, host_cr3),
1253         FIELD(HOST_CR4, host_cr4),
1254         FIELD(HOST_FS_BASE, host_fs_base),
1255         FIELD(HOST_GS_BASE, host_gs_base),
1256         FIELD(HOST_TR_BASE, host_tr_base),
1257         FIELD(HOST_GDTR_BASE, host_gdtr_base),
1258         FIELD(HOST_IDTR_BASE, host_idtr_base),
1259         FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
1260         FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
1261         FIELD(HOST_RSP, host_rsp),
1262         FIELD(HOST_RIP, host_rip),
1263 };
1264
1265 static inline short vmcs_field_to_offset(unsigned long field)
1266 {
1267         const size_t size = ARRAY_SIZE(vmcs_field_to_offset_table);
1268         unsigned short offset;
1269         unsigned index;
1270
1271         if (field >> 15)
1272                 return -ENOENT;
1273
1274         index = ROL16(field, 6);
1275         if (index >= size)
1276                 return -ENOENT;
1277
1278         index = array_index_nospec(index, size);
1279         offset = vmcs_field_to_offset_table[index];
1280         if (offset == 0)
1281                 return -ENOENT;
1282         return offset;
1283 }
1284
1285 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
1286 {
1287         return to_vmx(vcpu)->nested.cached_vmcs12;
1288 }
1289
1290 static inline struct vmcs12 *get_shadow_vmcs12(struct kvm_vcpu *vcpu)
1291 {
1292         return to_vmx(vcpu)->nested.cached_shadow_vmcs12;
1293 }
1294
1295 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu);
1296 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
1297 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa);
1298 static bool vmx_xsaves_supported(void);
1299 static void vmx_set_segment(struct kvm_vcpu *vcpu,
1300                             struct kvm_segment *var, int seg);
1301 static void vmx_get_segment(struct kvm_vcpu *vcpu,
1302                             struct kvm_segment *var, int seg);
1303 static bool guest_state_valid(struct kvm_vcpu *vcpu);
1304 static u32 vmx_segment_access_rights(struct kvm_segment *var);
1305 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
1306 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu);
1307 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked);
1308 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
1309                                             u16 error_code);
1310 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu);
1311 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
1312                                                           u32 msr, int type);
1313
1314 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
1315 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
1316 /*
1317  * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
1318  * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
1319  */
1320 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
1321
1322 /*
1323  * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
1324  * can find which vCPU should be waken up.
1325  */
1326 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
1327 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
1328
1329 enum {
1330         VMX_VMREAD_BITMAP,
1331         VMX_VMWRITE_BITMAP,
1332         VMX_BITMAP_NR
1333 };
1334
1335 static unsigned long *vmx_bitmap[VMX_BITMAP_NR];
1336
1337 #define vmx_vmread_bitmap                    (vmx_bitmap[VMX_VMREAD_BITMAP])
1338 #define vmx_vmwrite_bitmap                   (vmx_bitmap[VMX_VMWRITE_BITMAP])
1339
1340 static bool cpu_has_load_ia32_efer;
1341 static bool cpu_has_load_perf_global_ctrl;
1342
1343 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
1344 static DEFINE_SPINLOCK(vmx_vpid_lock);
1345
1346 static struct vmcs_config {
1347         int size;
1348         int order;
1349         u32 basic_cap;
1350         u32 revision_id;
1351         u32 pin_based_exec_ctrl;
1352         u32 cpu_based_exec_ctrl;
1353         u32 cpu_based_2nd_exec_ctrl;
1354         u32 vmexit_ctrl;
1355         u32 vmentry_ctrl;
1356         struct nested_vmx_msrs nested;
1357 } vmcs_config;
1358
1359 static struct vmx_capability {
1360         u32 ept;
1361         u32 vpid;
1362 } vmx_capability;
1363
1364 #define VMX_SEGMENT_FIELD(seg)                                  \
1365         [VCPU_SREG_##seg] = {                                   \
1366                 .selector = GUEST_##seg##_SELECTOR,             \
1367                 .base = GUEST_##seg##_BASE,                     \
1368                 .limit = GUEST_##seg##_LIMIT,                   \
1369                 .ar_bytes = GUEST_##seg##_AR_BYTES,             \
1370         }
1371
1372 static const struct kvm_vmx_segment_field {
1373         unsigned selector;
1374         unsigned base;
1375         unsigned limit;
1376         unsigned ar_bytes;
1377 } kvm_vmx_segment_fields[] = {
1378         VMX_SEGMENT_FIELD(CS),
1379         VMX_SEGMENT_FIELD(DS),
1380         VMX_SEGMENT_FIELD(ES),
1381         VMX_SEGMENT_FIELD(FS),
1382         VMX_SEGMENT_FIELD(GS),
1383         VMX_SEGMENT_FIELD(SS),
1384         VMX_SEGMENT_FIELD(TR),
1385         VMX_SEGMENT_FIELD(LDTR),
1386 };
1387
1388 static u64 host_efer;
1389
1390 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
1391
1392 /*
1393  * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
1394  * away by decrementing the array size.
1395  */
1396 static const u32 vmx_msr_index[] = {
1397 #ifdef CONFIG_X86_64
1398         MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
1399 #endif
1400         MSR_EFER, MSR_TSC_AUX, MSR_STAR,
1401 };
1402
1403 DEFINE_STATIC_KEY_FALSE(enable_evmcs);
1404
1405 #define current_evmcs ((struct hv_enlightened_vmcs *)this_cpu_read(current_vmcs))
1406
1407 #define KVM_EVMCS_VERSION 1
1408
1409 /*
1410  * Enlightened VMCSv1 doesn't support these:
1411  *
1412  *      POSTED_INTR_NV                  = 0x00000002,
1413  *      GUEST_INTR_STATUS               = 0x00000810,
1414  *      APIC_ACCESS_ADDR                = 0x00002014,
1415  *      POSTED_INTR_DESC_ADDR           = 0x00002016,
1416  *      EOI_EXIT_BITMAP0                = 0x0000201c,
1417  *      EOI_EXIT_BITMAP1                = 0x0000201e,
1418  *      EOI_EXIT_BITMAP2                = 0x00002020,
1419  *      EOI_EXIT_BITMAP3                = 0x00002022,
1420  *      GUEST_PML_INDEX                 = 0x00000812,
1421  *      PML_ADDRESS                     = 0x0000200e,
1422  *      VM_FUNCTION_CONTROL             = 0x00002018,
1423  *      EPTP_LIST_ADDRESS               = 0x00002024,
1424  *      VMREAD_BITMAP                   = 0x00002026,
1425  *      VMWRITE_BITMAP                  = 0x00002028,
1426  *
1427  *      TSC_MULTIPLIER                  = 0x00002032,
1428  *      PLE_GAP                         = 0x00004020,
1429  *      PLE_WINDOW                      = 0x00004022,
1430  *      VMX_PREEMPTION_TIMER_VALUE      = 0x0000482E,
1431  *      GUEST_IA32_PERF_GLOBAL_CTRL     = 0x00002808,
1432  *      HOST_IA32_PERF_GLOBAL_CTRL      = 0x00002c04,
1433  *
1434  * Currently unsupported in KVM:
1435  *      GUEST_IA32_RTIT_CTL             = 0x00002814,
1436  */
1437 #define EVMCS1_UNSUPPORTED_PINCTRL (PIN_BASED_POSTED_INTR | \
1438                                     PIN_BASED_VMX_PREEMPTION_TIMER)
1439 #define EVMCS1_UNSUPPORTED_2NDEXEC                                      \
1440         (SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |                         \
1441          SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |                      \
1442          SECONDARY_EXEC_APIC_REGISTER_VIRT |                            \
1443          SECONDARY_EXEC_ENABLE_PML |                                    \
1444          SECONDARY_EXEC_ENABLE_VMFUNC |                                 \
1445          SECONDARY_EXEC_SHADOW_VMCS |                                   \
1446          SECONDARY_EXEC_TSC_SCALING |                                   \
1447          SECONDARY_EXEC_PAUSE_LOOP_EXITING)
1448 #define EVMCS1_UNSUPPORTED_VMEXIT_CTRL (VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
1449 #define EVMCS1_UNSUPPORTED_VMENTRY_CTRL (VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
1450 #define EVMCS1_UNSUPPORTED_VMFUNC (VMX_VMFUNC_EPTP_SWITCHING)
1451
1452 #if IS_ENABLED(CONFIG_HYPERV)
1453 static bool __read_mostly enlightened_vmcs = true;
1454 module_param(enlightened_vmcs, bool, 0444);
1455
1456 static inline void evmcs_write64(unsigned long field, u64 value)
1457 {
1458         u16 clean_field;
1459         int offset = get_evmcs_offset(field, &clean_field);
1460
1461         if (offset < 0)
1462                 return;
1463
1464         *(u64 *)((char *)current_evmcs + offset) = value;
1465
1466         current_evmcs->hv_clean_fields &= ~clean_field;
1467 }
1468
1469 static inline void evmcs_write32(unsigned long field, u32 value)
1470 {
1471         u16 clean_field;
1472         int offset = get_evmcs_offset(field, &clean_field);
1473
1474         if (offset < 0)
1475                 return;
1476
1477         *(u32 *)((char *)current_evmcs + offset) = value;
1478         current_evmcs->hv_clean_fields &= ~clean_field;
1479 }
1480
1481 static inline void evmcs_write16(unsigned long field, u16 value)
1482 {
1483         u16 clean_field;
1484         int offset = get_evmcs_offset(field, &clean_field);
1485
1486         if (offset < 0)
1487                 return;
1488
1489         *(u16 *)((char *)current_evmcs + offset) = value;
1490         current_evmcs->hv_clean_fields &= ~clean_field;
1491 }
1492
1493 static inline u64 evmcs_read64(unsigned long field)
1494 {
1495         int offset = get_evmcs_offset(field, NULL);
1496
1497         if (offset < 0)
1498                 return 0;
1499
1500         return *(u64 *)((char *)current_evmcs + offset);
1501 }
1502
1503 static inline u32 evmcs_read32(unsigned long field)
1504 {
1505         int offset = get_evmcs_offset(field, NULL);
1506
1507         if (offset < 0)
1508                 return 0;
1509
1510         return *(u32 *)((char *)current_evmcs + offset);
1511 }
1512
1513 static inline u16 evmcs_read16(unsigned long field)
1514 {
1515         int offset = get_evmcs_offset(field, NULL);
1516
1517         if (offset < 0)
1518                 return 0;
1519
1520         return *(u16 *)((char *)current_evmcs + offset);
1521 }
1522
1523 static inline void evmcs_touch_msr_bitmap(void)
1524 {
1525         if (unlikely(!current_evmcs))
1526                 return;
1527
1528         if (current_evmcs->hv_enlightenments_control.msr_bitmap)
1529                 current_evmcs->hv_clean_fields &=
1530                         ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP;
1531 }
1532
1533 static void evmcs_load(u64 phys_addr)
1534 {
1535         struct hv_vp_assist_page *vp_ap =
1536                 hv_get_vp_assist_page(smp_processor_id());
1537
1538         vp_ap->current_nested_vmcs = phys_addr;
1539         vp_ap->enlighten_vmentry = 1;
1540 }
1541
1542 static void evmcs_sanitize_exec_ctrls(struct vmcs_config *vmcs_conf)
1543 {
1544         vmcs_conf->pin_based_exec_ctrl &= ~EVMCS1_UNSUPPORTED_PINCTRL;
1545         vmcs_conf->cpu_based_2nd_exec_ctrl &= ~EVMCS1_UNSUPPORTED_2NDEXEC;
1546
1547         vmcs_conf->vmexit_ctrl &= ~EVMCS1_UNSUPPORTED_VMEXIT_CTRL;
1548         vmcs_conf->vmentry_ctrl &= ~EVMCS1_UNSUPPORTED_VMENTRY_CTRL;
1549
1550 }
1551
1552 /* check_ept_pointer() should be under protection of ept_pointer_lock. */
1553 static void check_ept_pointer_match(struct kvm *kvm)
1554 {
1555         struct kvm_vcpu *vcpu;
1556         u64 tmp_eptp = INVALID_PAGE;
1557         int i;
1558
1559         kvm_for_each_vcpu(i, vcpu, kvm) {
1560                 if (!VALID_PAGE(tmp_eptp)) {
1561                         tmp_eptp = to_vmx(vcpu)->ept_pointer;
1562                 } else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
1563                         to_kvm_vmx(kvm)->ept_pointers_match
1564                                 = EPT_POINTERS_MISMATCH;
1565                         return;
1566                 }
1567         }
1568
1569         to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
1570 }
1571
1572 static int vmx_hv_remote_flush_tlb(struct kvm *kvm)
1573 {
1574         struct kvm_vcpu *vcpu;
1575         int ret = -ENOTSUPP, i;
1576
1577         spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
1578
1579         if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
1580                 check_ept_pointer_match(kvm);
1581
1582         /*
1583          * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs the address of the
1584          * base of EPT PML4 table, strip off EPT configuration information.
1585          */
1586         if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
1587                 kvm_for_each_vcpu(i, vcpu, kvm)
1588                         ret |= hyperv_flush_guest_mapping(
1589                                 to_vmx(kvm_get_vcpu(kvm, i))->ept_pointer & PAGE_MASK);
1590         } else {
1591                 ret = hyperv_flush_guest_mapping(
1592                                 to_vmx(kvm_get_vcpu(kvm, 0))->ept_pointer & PAGE_MASK);
1593         }
1594
1595         spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
1596         return ret;
1597 }
1598 #else /* !IS_ENABLED(CONFIG_HYPERV) */
1599 static inline void evmcs_write64(unsigned long field, u64 value) {}
1600 static inline void evmcs_write32(unsigned long field, u32 value) {}
1601 static inline void evmcs_write16(unsigned long field, u16 value) {}
1602 static inline u64 evmcs_read64(unsigned long field) { return 0; }
1603 static inline u32 evmcs_read32(unsigned long field) { return 0; }
1604 static inline u16 evmcs_read16(unsigned long field) { return 0; }
1605 static inline void evmcs_load(u64 phys_addr) {}
1606 static inline void evmcs_sanitize_exec_ctrls(struct vmcs_config *vmcs_conf) {}
1607 static inline void evmcs_touch_msr_bitmap(void) {}
1608 #endif /* IS_ENABLED(CONFIG_HYPERV) */
1609
1610 static int nested_enable_evmcs(struct kvm_vcpu *vcpu,
1611                                uint16_t *vmcs_version)
1612 {
1613         struct vcpu_vmx *vmx = to_vmx(vcpu);
1614
1615         /*
1616          * vmcs_version represents the range of supported Enlightened VMCS
1617          * versions: lower 8 bits is the minimal version, higher 8 bits is the
1618          * maximum supported version. KVM supports versions from 1 to
1619          * KVM_EVMCS_VERSION.
1620          */
1621         if (vmcs_version)
1622                 *vmcs_version = (KVM_EVMCS_VERSION << 8) | 1;
1623
1624         /* We don't support disabling the feature for simplicity. */
1625         if (vmx->nested.enlightened_vmcs_enabled)
1626                 return 0;
1627
1628         vmx->nested.enlightened_vmcs_enabled = true;
1629
1630         vmx->nested.msrs.pinbased_ctls_high &= ~EVMCS1_UNSUPPORTED_PINCTRL;
1631         vmx->nested.msrs.entry_ctls_high &= ~EVMCS1_UNSUPPORTED_VMENTRY_CTRL;
1632         vmx->nested.msrs.exit_ctls_high &= ~EVMCS1_UNSUPPORTED_VMEXIT_CTRL;
1633         vmx->nested.msrs.secondary_ctls_high &= ~EVMCS1_UNSUPPORTED_2NDEXEC;
1634         vmx->nested.msrs.vmfunc_controls &= ~EVMCS1_UNSUPPORTED_VMFUNC;
1635
1636         return 0;
1637 }
1638
1639 static inline bool is_exception_n(u32 intr_info, u8 vector)
1640 {
1641         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1642                              INTR_INFO_VALID_MASK)) ==
1643                 (INTR_TYPE_HARD_EXCEPTION | vector | INTR_INFO_VALID_MASK);
1644 }
1645
1646 static inline bool is_debug(u32 intr_info)
1647 {
1648         return is_exception_n(intr_info, DB_VECTOR);
1649 }
1650
1651 static inline bool is_breakpoint(u32 intr_info)
1652 {
1653         return is_exception_n(intr_info, BP_VECTOR);
1654 }
1655
1656 static inline bool is_page_fault(u32 intr_info)
1657 {
1658         return is_exception_n(intr_info, PF_VECTOR);
1659 }
1660
1661 static inline bool is_invalid_opcode(u32 intr_info)
1662 {
1663         return is_exception_n(intr_info, UD_VECTOR);
1664 }
1665
1666 static inline bool is_gp_fault(u32 intr_info)
1667 {
1668         return is_exception_n(intr_info, GP_VECTOR);
1669 }
1670
1671 static inline bool is_machine_check(u32 intr_info)
1672 {
1673         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1674                              INTR_INFO_VALID_MASK)) ==
1675                 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
1676 }
1677
1678 /* Undocumented: icebp/int1 */
1679 static inline bool is_icebp(u32 intr_info)
1680 {
1681         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1682                 == (INTR_TYPE_PRIV_SW_EXCEPTION | INTR_INFO_VALID_MASK);
1683 }
1684
1685 static inline bool cpu_has_vmx_msr_bitmap(void)
1686 {
1687         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
1688 }
1689
1690 static inline bool cpu_has_vmx_tpr_shadow(void)
1691 {
1692         return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
1693 }
1694
1695 static inline bool cpu_need_tpr_shadow(struct kvm_vcpu *vcpu)
1696 {
1697         return cpu_has_vmx_tpr_shadow() && lapic_in_kernel(vcpu);
1698 }
1699
1700 static inline bool cpu_has_secondary_exec_ctrls(void)
1701 {
1702         return vmcs_config.cpu_based_exec_ctrl &
1703                 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1704 }
1705
1706 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
1707 {
1708         return vmcs_config.cpu_based_2nd_exec_ctrl &
1709                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1710 }
1711
1712 static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
1713 {
1714         return vmcs_config.cpu_based_2nd_exec_ctrl &
1715                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
1716 }
1717
1718 static inline bool cpu_has_vmx_apic_register_virt(void)
1719 {
1720         return vmcs_config.cpu_based_2nd_exec_ctrl &
1721                 SECONDARY_EXEC_APIC_REGISTER_VIRT;
1722 }
1723
1724 static inline bool cpu_has_vmx_virtual_intr_delivery(void)
1725 {
1726         return vmcs_config.cpu_based_2nd_exec_ctrl &
1727                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1728 }
1729
1730 static inline bool cpu_has_vmx_encls_vmexit(void)
1731 {
1732         return vmcs_config.cpu_based_2nd_exec_ctrl &
1733                 SECONDARY_EXEC_ENCLS_EXITING;
1734 }
1735
1736 /*
1737  * Comment's format: document - errata name - stepping - processor name.
1738  * Refer from
1739  * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
1740  */
1741 static u32 vmx_preemption_cpu_tfms[] = {
1742 /* 323344.pdf - BA86   - D0 - Xeon 7500 Series */
1743 0x000206E6,
1744 /* 323056.pdf - AAX65  - C2 - Xeon L3406 */
1745 /* 322814.pdf - AAT59  - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
1746 /* 322911.pdf - AAU65  - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
1747 0x00020652,
1748 /* 322911.pdf - AAU65  - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
1749 0x00020655,
1750 /* 322373.pdf - AAO95  - B1 - Xeon 3400 Series */
1751 /* 322166.pdf - AAN92  - B1 - i7-800 and i5-700 Desktop */
1752 /*
1753  * 320767.pdf - AAP86  - B1 -
1754  * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
1755  */
1756 0x000106E5,
1757 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
1758 0x000106A0,
1759 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
1760 0x000106A1,
1761 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
1762 0x000106A4,
1763  /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
1764  /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
1765  /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
1766 0x000106A5,
1767 };
1768
1769 static inline bool cpu_has_broken_vmx_preemption_timer(void)
1770 {
1771         u32 eax = cpuid_eax(0x00000001), i;
1772
1773         /* Clear the reserved bits */
1774         eax &= ~(0x3U << 14 | 0xfU << 28);
1775         for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
1776                 if (eax == vmx_preemption_cpu_tfms[i])
1777                         return true;
1778
1779         return false;
1780 }
1781
1782 static inline bool cpu_has_vmx_preemption_timer(void)
1783 {
1784         return vmcs_config.pin_based_exec_ctrl &
1785                 PIN_BASED_VMX_PREEMPTION_TIMER;
1786 }
1787
1788 static inline bool cpu_has_vmx_posted_intr(void)
1789 {
1790         return IS_ENABLED(CONFIG_X86_LOCAL_APIC) &&
1791                 vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
1792 }
1793
1794 static inline bool cpu_has_vmx_apicv(void)
1795 {
1796         return cpu_has_vmx_apic_register_virt() &&
1797                 cpu_has_vmx_virtual_intr_delivery() &&
1798                 cpu_has_vmx_posted_intr();
1799 }
1800
1801 static inline bool cpu_has_vmx_flexpriority(void)
1802 {
1803         return cpu_has_vmx_tpr_shadow() &&
1804                 cpu_has_vmx_virtualize_apic_accesses();
1805 }
1806
1807 static inline bool cpu_has_vmx_ept_execute_only(void)
1808 {
1809         return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
1810 }
1811
1812 static inline bool cpu_has_vmx_ept_2m_page(void)
1813 {
1814         return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
1815 }
1816
1817 static inline bool cpu_has_vmx_ept_1g_page(void)
1818 {
1819         return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
1820 }
1821
1822 static inline bool cpu_has_vmx_ept_4levels(void)
1823 {
1824         return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
1825 }
1826
1827 static inline bool cpu_has_vmx_ept_mt_wb(void)
1828 {
1829         return vmx_capability.ept & VMX_EPTP_WB_BIT;
1830 }
1831
1832 static inline bool cpu_has_vmx_ept_5levels(void)
1833 {
1834         return vmx_capability.ept & VMX_EPT_PAGE_WALK_5_BIT;
1835 }
1836
1837 static inline bool cpu_has_vmx_ept_ad_bits(void)
1838 {
1839         return vmx_capability.ept & VMX_EPT_AD_BIT;
1840 }
1841
1842 static inline bool cpu_has_vmx_invept_context(void)
1843 {
1844         return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
1845 }
1846
1847 static inline bool cpu_has_vmx_invept_global(void)
1848 {
1849         return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
1850 }
1851
1852 static inline bool cpu_has_vmx_invvpid_individual_addr(void)
1853 {
1854         return vmx_capability.vpid & VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT;
1855 }
1856
1857 static inline bool cpu_has_vmx_invvpid_single(void)
1858 {
1859         return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
1860 }
1861
1862 static inline bool cpu_has_vmx_invvpid_global(void)
1863 {
1864         return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
1865 }
1866
1867 static inline bool cpu_has_vmx_invvpid(void)
1868 {
1869         return vmx_capability.vpid & VMX_VPID_INVVPID_BIT;
1870 }
1871
1872 static inline bool cpu_has_vmx_ept(void)
1873 {
1874         return vmcs_config.cpu_based_2nd_exec_ctrl &
1875                 SECONDARY_EXEC_ENABLE_EPT;
1876 }
1877
1878 static inline bool cpu_has_vmx_unrestricted_guest(void)
1879 {
1880         return vmcs_config.cpu_based_2nd_exec_ctrl &
1881                 SECONDARY_EXEC_UNRESTRICTED_GUEST;
1882 }
1883
1884 static inline bool cpu_has_vmx_ple(void)
1885 {
1886         return vmcs_config.cpu_based_2nd_exec_ctrl &
1887                 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1888 }
1889
1890 static inline bool cpu_has_vmx_basic_inout(void)
1891 {
1892         return  (((u64)vmcs_config.basic_cap << 32) & VMX_BASIC_INOUT);
1893 }
1894
1895 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
1896 {
1897         return flexpriority_enabled && lapic_in_kernel(vcpu);
1898 }
1899
1900 static inline bool cpu_has_vmx_vpid(void)
1901 {
1902         return vmcs_config.cpu_based_2nd_exec_ctrl &
1903                 SECONDARY_EXEC_ENABLE_VPID;
1904 }
1905
1906 static inline bool cpu_has_vmx_rdtscp(void)
1907 {
1908         return vmcs_config.cpu_based_2nd_exec_ctrl &
1909                 SECONDARY_EXEC_RDTSCP;
1910 }
1911
1912 static inline bool cpu_has_vmx_invpcid(void)
1913 {
1914         return vmcs_config.cpu_based_2nd_exec_ctrl &
1915                 SECONDARY_EXEC_ENABLE_INVPCID;
1916 }
1917
1918 static inline bool cpu_has_virtual_nmis(void)
1919 {
1920         return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1921 }
1922
1923 static inline bool cpu_has_vmx_wbinvd_exit(void)
1924 {
1925         return vmcs_config.cpu_based_2nd_exec_ctrl &
1926                 SECONDARY_EXEC_WBINVD_EXITING;
1927 }
1928
1929 static inline bool cpu_has_vmx_shadow_vmcs(void)
1930 {
1931         u64 vmx_msr;
1932         rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1933         /* check if the cpu supports writing r/o exit information fields */
1934         if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1935                 return false;
1936
1937         return vmcs_config.cpu_based_2nd_exec_ctrl &
1938                 SECONDARY_EXEC_SHADOW_VMCS;
1939 }
1940
1941 static inline bool cpu_has_vmx_pml(void)
1942 {
1943         return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_PML;
1944 }
1945
1946 static inline bool cpu_has_vmx_tsc_scaling(void)
1947 {
1948         return vmcs_config.cpu_based_2nd_exec_ctrl &
1949                 SECONDARY_EXEC_TSC_SCALING;
1950 }
1951
1952 static inline bool cpu_has_vmx_vmfunc(void)
1953 {
1954         return vmcs_config.cpu_based_2nd_exec_ctrl &
1955                 SECONDARY_EXEC_ENABLE_VMFUNC;
1956 }
1957
1958 static bool vmx_umip_emulated(void)
1959 {
1960         return vmcs_config.cpu_based_2nd_exec_ctrl &
1961                 SECONDARY_EXEC_DESC;
1962 }
1963
1964 static inline bool report_flexpriority(void)
1965 {
1966         return flexpriority_enabled;
1967 }
1968
1969 static inline unsigned nested_cpu_vmx_misc_cr3_count(struct kvm_vcpu *vcpu)
1970 {
1971         return vmx_misc_cr3_count(to_vmx(vcpu)->nested.msrs.misc_low);
1972 }
1973
1974 /*
1975  * Do the virtual VMX capability MSRs specify that L1 can use VMWRITE
1976  * to modify any valid field of the VMCS, or are the VM-exit
1977  * information fields read-only?
1978  */
1979 static inline bool nested_cpu_has_vmwrite_any_field(struct kvm_vcpu *vcpu)
1980 {
1981         return to_vmx(vcpu)->nested.msrs.misc_low &
1982                 MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS;
1983 }
1984
1985 static inline bool nested_cpu_has_zero_length_injection(struct kvm_vcpu *vcpu)
1986 {
1987         return to_vmx(vcpu)->nested.msrs.misc_low & VMX_MISC_ZERO_LEN_INS;
1988 }
1989
1990 static inline bool nested_cpu_supports_monitor_trap_flag(struct kvm_vcpu *vcpu)
1991 {
1992         return to_vmx(vcpu)->nested.msrs.procbased_ctls_high &
1993                         CPU_BASED_MONITOR_TRAP_FLAG;
1994 }
1995
1996 static inline bool nested_cpu_has_vmx_shadow_vmcs(struct kvm_vcpu *vcpu)
1997 {
1998         return to_vmx(vcpu)->nested.msrs.secondary_ctls_high &
1999                 SECONDARY_EXEC_SHADOW_VMCS;
2000 }
2001
2002 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
2003 {
2004         return vmcs12->cpu_based_vm_exec_control & bit;
2005 }
2006
2007 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
2008 {
2009         return (vmcs12->cpu_based_vm_exec_control &
2010                         CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
2011                 (vmcs12->secondary_vm_exec_control & bit);
2012 }
2013
2014 static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
2015 {
2016         return vmcs12->pin_based_vm_exec_control &
2017                 PIN_BASED_VMX_PREEMPTION_TIMER;
2018 }
2019
2020 static inline bool nested_cpu_has_nmi_exiting(struct vmcs12 *vmcs12)
2021 {
2022         return vmcs12->pin_based_vm_exec_control & PIN_BASED_NMI_EXITING;
2023 }
2024
2025 static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12)
2026 {
2027         return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
2028 }
2029
2030 static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
2031 {
2032         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
2033 }
2034
2035 static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
2036 {
2037         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
2038 }
2039
2040 static inline bool nested_cpu_has_pml(struct vmcs12 *vmcs12)
2041 {
2042         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML);
2043 }
2044
2045 static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
2046 {
2047         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
2048 }
2049
2050 static inline bool nested_cpu_has_vpid(struct vmcs12 *vmcs12)
2051 {
2052         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VPID);
2053 }
2054
2055 static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
2056 {
2057         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
2058 }
2059
2060 static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
2061 {
2062         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2063 }
2064
2065 static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
2066 {
2067         return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
2068 }
2069
2070 static inline bool nested_cpu_has_vmfunc(struct vmcs12 *vmcs12)
2071 {
2072         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VMFUNC);
2073 }
2074
2075 static inline bool nested_cpu_has_eptp_switching(struct vmcs12 *vmcs12)
2076 {
2077         return nested_cpu_has_vmfunc(vmcs12) &&
2078                 (vmcs12->vm_function_control &
2079                  VMX_VMFUNC_EPTP_SWITCHING);
2080 }
2081
2082 static inline bool nested_cpu_has_shadow_vmcs(struct vmcs12 *vmcs12)
2083 {
2084         return nested_cpu_has2(vmcs12, SECONDARY_EXEC_SHADOW_VMCS);
2085 }
2086
2087 static inline bool is_nmi(u32 intr_info)
2088 {
2089         return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
2090                 == (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK);
2091 }
2092
2093 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
2094                               u32 exit_intr_info,
2095                               unsigned long exit_qualification);
2096
2097 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
2098 {
2099         int i;
2100
2101         for (i = 0; i < vmx->nmsrs; ++i)
2102                 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
2103                         return i;
2104         return -1;
2105 }
2106
2107 static inline void __invvpid(unsigned long ext, u16 vpid, gva_t gva)
2108 {
2109     struct {
2110         u64 vpid : 16;
2111         u64 rsvd : 48;
2112         u64 gva;
2113     } operand = { vpid, 0, gva };
2114     bool error;
2115
2116     asm volatile (__ex("invvpid %2, %1") CC_SET(na)
2117                   : CC_OUT(na) (error) : "r"(ext), "m"(operand));
2118     BUG_ON(error);
2119 }
2120
2121 static inline void __invept(unsigned long ext, u64 eptp, gpa_t gpa)
2122 {
2123         struct {
2124                 u64 eptp, gpa;
2125         } operand = {eptp, gpa};
2126         bool error;
2127
2128         asm volatile (__ex("invept %2, %1") CC_SET(na)
2129                       : CC_OUT(na) (error) : "r"(ext), "m"(operand));
2130         BUG_ON(error);
2131 }
2132
2133 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
2134 {
2135         int i;
2136
2137         i = __find_msr_index(vmx, msr);
2138         if (i >= 0)
2139                 return &vmx->guest_msrs[i];
2140         return NULL;
2141 }
2142
2143 static void vmcs_clear(struct vmcs *vmcs)
2144 {
2145         u64 phys_addr = __pa(vmcs);
2146         bool error;
2147
2148         asm volatile (__ex("vmclear %1") CC_SET(na)
2149                       : CC_OUT(na) (error) : "m"(phys_addr));
2150         if (unlikely(error))
2151                 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
2152                        vmcs, phys_addr);
2153 }
2154
2155 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
2156 {
2157         vmcs_clear(loaded_vmcs->vmcs);
2158         if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
2159                 vmcs_clear(loaded_vmcs->shadow_vmcs);
2160         loaded_vmcs->cpu = -1;
2161         loaded_vmcs->launched = 0;
2162 }
2163
2164 static void vmcs_load(struct vmcs *vmcs)
2165 {
2166         u64 phys_addr = __pa(vmcs);
2167         bool error;
2168
2169         if (static_branch_unlikely(&enable_evmcs))
2170                 return evmcs_load(phys_addr);
2171
2172         asm volatile (__ex("vmptrld %1") CC_SET(na)
2173                       : CC_OUT(na) (error) : "m"(phys_addr));
2174         if (unlikely(error))
2175                 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
2176                        vmcs, phys_addr);
2177 }
2178
2179 #ifdef CONFIG_KEXEC_CORE
2180 /*
2181  * This bitmap is used to indicate whether the vmclear
2182  * operation is enabled on all cpus. All disabled by
2183  * default.
2184  */
2185 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
2186
2187 static inline void crash_enable_local_vmclear(int cpu)
2188 {
2189         cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
2190 }
2191
2192 static inline void crash_disable_local_vmclear(int cpu)
2193 {
2194         cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
2195 }
2196
2197 static inline int crash_local_vmclear_enabled(int cpu)
2198 {
2199         return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
2200 }
2201
2202 static void crash_vmclear_local_loaded_vmcss(void)
2203 {
2204         int cpu = raw_smp_processor_id();
2205         struct loaded_vmcs *v;
2206
2207         if (!crash_local_vmclear_enabled(cpu))
2208                 return;
2209
2210         list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
2211                             loaded_vmcss_on_cpu_link)
2212                 vmcs_clear(v->vmcs);
2213 }
2214 #else
2215 static inline void crash_enable_local_vmclear(int cpu) { }
2216 static inline void crash_disable_local_vmclear(int cpu) { }
2217 #endif /* CONFIG_KEXEC_CORE */
2218
2219 static void __loaded_vmcs_clear(void *arg)
2220 {
2221         struct loaded_vmcs *loaded_vmcs = arg;
2222         int cpu = raw_smp_processor_id();
2223
2224         if (loaded_vmcs->cpu != cpu)
2225                 return; /* vcpu migration can race with cpu offline */
2226         if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
2227                 per_cpu(current_vmcs, cpu) = NULL;
2228         crash_disable_local_vmclear(cpu);
2229         list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
2230
2231         /*
2232          * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
2233          * is before setting loaded_vmcs->vcpu to -1 which is done in
2234          * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
2235          * then adds the vmcs into percpu list before it is deleted.
2236          */
2237         smp_wmb();
2238
2239         loaded_vmcs_init(loaded_vmcs);
2240         crash_enable_local_vmclear(cpu);
2241 }
2242
2243 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
2244 {
2245         int cpu = loaded_vmcs->cpu;
2246
2247         if (cpu != -1)
2248                 smp_call_function_single(cpu,
2249                          __loaded_vmcs_clear, loaded_vmcs, 1);
2250 }
2251
2252 static inline bool vpid_sync_vcpu_addr(int vpid, gva_t addr)
2253 {
2254         if (vpid == 0)
2255                 return true;
2256
2257         if (cpu_has_vmx_invvpid_individual_addr()) {
2258                 __invvpid(VMX_VPID_EXTENT_INDIVIDUAL_ADDR, vpid, addr);
2259                 return true;
2260         }
2261
2262         return false;
2263 }
2264
2265 static inline void vpid_sync_vcpu_single(int vpid)
2266 {
2267         if (vpid == 0)
2268                 return;
2269
2270         if (cpu_has_vmx_invvpid_single())
2271                 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vpid, 0);
2272 }
2273
2274 static inline void vpid_sync_vcpu_global(void)
2275 {
2276         if (cpu_has_vmx_invvpid_global())
2277                 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
2278 }
2279
2280 static inline void vpid_sync_context(int vpid)
2281 {
2282         if (cpu_has_vmx_invvpid_single())
2283                 vpid_sync_vcpu_single(vpid);
2284         else
2285                 vpid_sync_vcpu_global();
2286 }
2287
2288 static inline void ept_sync_global(void)
2289 {
2290         __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
2291 }
2292
2293 static inline void ept_sync_context(u64 eptp)
2294 {
2295         if (cpu_has_vmx_invept_context())
2296                 __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
2297         else
2298                 ept_sync_global();
2299 }
2300
2301 static __always_inline void vmcs_check16(unsigned long field)
2302 {
2303         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
2304                          "16-bit accessor invalid for 64-bit field");
2305         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2306                          "16-bit accessor invalid for 64-bit high field");
2307         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2308                          "16-bit accessor invalid for 32-bit high field");
2309         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2310                          "16-bit accessor invalid for natural width field");
2311 }
2312
2313 static __always_inline void vmcs_check32(unsigned long field)
2314 {
2315         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2316                          "32-bit accessor invalid for 16-bit field");
2317         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2318                          "32-bit accessor invalid for natural width field");
2319 }
2320
2321 static __always_inline void vmcs_check64(unsigned long field)
2322 {
2323         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2324                          "64-bit accessor invalid for 16-bit field");
2325         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2326                          "64-bit accessor invalid for 64-bit high field");
2327         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2328                          "64-bit accessor invalid for 32-bit field");
2329         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2330                          "64-bit accessor invalid for natural width field");
2331 }
2332
2333 static __always_inline void vmcs_checkl(unsigned long field)
2334 {
2335         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2336                          "Natural width accessor invalid for 16-bit field");
2337         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
2338                          "Natural width accessor invalid for 64-bit field");
2339         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2340                          "Natural width accessor invalid for 64-bit high field");
2341         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2342                          "Natural width accessor invalid for 32-bit field");
2343 }
2344
2345 static __always_inline unsigned long __vmcs_readl(unsigned long field)
2346 {
2347         unsigned long value;
2348
2349         asm volatile (__ex_clear("vmread %1, %0", "%k0")
2350                       : "=r"(value) : "r"(field));
2351         return value;
2352 }
2353
2354 static __always_inline u16 vmcs_read16(unsigned long field)
2355 {
2356         vmcs_check16(field);
2357         if (static_branch_unlikely(&enable_evmcs))
2358                 return evmcs_read16(field);
2359         return __vmcs_readl(field);
2360 }
2361
2362 static __always_inline u32 vmcs_read32(unsigned long field)
2363 {
2364         vmcs_check32(field);
2365         if (static_branch_unlikely(&enable_evmcs))
2366                 return evmcs_read32(field);
2367         return __vmcs_readl(field);
2368 }
2369
2370 static __always_inline u64 vmcs_read64(unsigned long field)
2371 {
2372         vmcs_check64(field);
2373         if (static_branch_unlikely(&enable_evmcs))
2374                 return evmcs_read64(field);
2375 #ifdef CONFIG_X86_64
2376         return __vmcs_readl(field);
2377 #else
2378         return __vmcs_readl(field) | ((u64)__vmcs_readl(field+1) << 32);
2379 #endif
2380 }
2381
2382 static __always_inline unsigned long vmcs_readl(unsigned long field)
2383 {
2384         vmcs_checkl(field);
2385         if (static_branch_unlikely(&enable_evmcs))
2386                 return evmcs_read64(field);
2387         return __vmcs_readl(field);
2388 }
2389
2390 static noinline void vmwrite_error(unsigned long field, unsigned long value)
2391 {
2392         printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
2393                field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
2394         dump_stack();
2395 }
2396
2397 static __always_inline void __vmcs_writel(unsigned long field, unsigned long value)
2398 {
2399         bool error;
2400
2401         asm volatile (__ex("vmwrite %2, %1") CC_SET(na)
2402                       : CC_OUT(na) (error) : "r"(field), "rm"(value));
2403         if (unlikely(error))
2404                 vmwrite_error(field, value);
2405 }
2406
2407 static __always_inline void vmcs_write16(unsigned long field, u16 value)
2408 {
2409         vmcs_check16(field);
2410         if (static_branch_unlikely(&enable_evmcs))
2411                 return evmcs_write16(field, value);
2412
2413         __vmcs_writel(field, value);
2414 }
2415
2416 static __always_inline void vmcs_write32(unsigned long field, u32 value)
2417 {
2418         vmcs_check32(field);
2419         if (static_branch_unlikely(&enable_evmcs))
2420                 return evmcs_write32(field, value);
2421
2422         __vmcs_writel(field, value);
2423 }
2424
2425 static __always_inline void vmcs_write64(unsigned long field, u64 value)
2426 {
2427         vmcs_check64(field);
2428         if (static_branch_unlikely(&enable_evmcs))
2429                 return evmcs_write64(field, value);
2430
2431         __vmcs_writel(field, value);
2432 #ifndef CONFIG_X86_64
2433         asm volatile ("");
2434         __vmcs_writel(field+1, value >> 32);
2435 #endif
2436 }
2437
2438 static __always_inline void vmcs_writel(unsigned long field, unsigned long value)
2439 {
2440         vmcs_checkl(field);
2441         if (static_branch_unlikely(&enable_evmcs))
2442                 return evmcs_write64(field, value);
2443
2444         __vmcs_writel(field, value);
2445 }
2446
2447 static __always_inline void vmcs_clear_bits(unsigned long field, u32 mask)
2448 {
2449         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
2450                          "vmcs_clear_bits does not support 64-bit fields");
2451         if (static_branch_unlikely(&enable_evmcs))
2452                 return evmcs_write32(field, evmcs_read32(field) & ~mask);
2453
2454         __vmcs_writel(field, __vmcs_readl(field) & ~mask);
2455 }
2456
2457 static __always_inline void vmcs_set_bits(unsigned long field, u32 mask)
2458 {
2459         BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
2460                          "vmcs_set_bits does not support 64-bit fields");
2461         if (static_branch_unlikely(&enable_evmcs))
2462                 return evmcs_write32(field, evmcs_read32(field) | mask);
2463
2464         __vmcs_writel(field, __vmcs_readl(field) | mask);
2465 }
2466
2467 static inline void vm_entry_controls_reset_shadow(struct vcpu_vmx *vmx)
2468 {
2469         vmx->vm_entry_controls_shadow = vmcs_read32(VM_ENTRY_CONTROLS);
2470 }
2471
2472 static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
2473 {
2474         vmcs_write32(VM_ENTRY_CONTROLS, val);
2475         vmx->vm_entry_controls_shadow = val;
2476 }
2477
2478 static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
2479 {
2480         if (vmx->vm_entry_controls_shadow != val)
2481                 vm_entry_controls_init(vmx, val);
2482 }
2483
2484 static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
2485 {
2486         return vmx->vm_entry_controls_shadow;
2487 }
2488
2489
2490 static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
2491 {
2492         vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
2493 }
2494
2495 static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
2496 {
2497         vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
2498 }
2499
2500 static inline void vm_exit_controls_reset_shadow(struct vcpu_vmx *vmx)
2501 {
2502         vmx->vm_exit_controls_shadow = vmcs_read32(VM_EXIT_CONTROLS);
2503 }
2504
2505 static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
2506 {
2507         vmcs_write32(VM_EXIT_CONTROLS, val);
2508         vmx->vm_exit_controls_shadow = val;
2509 }
2510
2511 static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
2512 {
2513         if (vmx->vm_exit_controls_shadow != val)
2514                 vm_exit_controls_init(vmx, val);
2515 }
2516
2517 static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
2518 {
2519         return vmx->vm_exit_controls_shadow;
2520 }
2521
2522
2523 static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
2524 {
2525         vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
2526 }
2527
2528 static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
2529 {
2530         vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
2531 }
2532
2533 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
2534 {
2535         vmx->segment_cache.bitmask = 0;
2536 }
2537
2538 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
2539                                        unsigned field)
2540 {
2541         bool ret;
2542         u32 mask = 1 << (seg * SEG_FIELD_NR + field);
2543
2544         if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
2545                 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
2546                 vmx->segment_cache.bitmask = 0;
2547         }
2548         ret = vmx->segment_cache.bitmask & mask;
2549         vmx->segment_cache.bitmask |= mask;
2550         return ret;
2551 }
2552
2553 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
2554 {
2555         u16 *p = &vmx->segment_cache.seg[seg].selector;
2556
2557         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
2558                 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
2559         return *p;
2560 }
2561
2562 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
2563 {
2564         ulong *p = &vmx->segment_cache.seg[seg].base;
2565
2566         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
2567                 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
2568         return *p;
2569 }
2570
2571 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
2572 {
2573         u32 *p = &vmx->segment_cache.seg[seg].limit;
2574
2575         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
2576                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
2577         return *p;
2578 }
2579
2580 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
2581 {
2582         u32 *p = &vmx->segment_cache.seg[seg].ar;
2583
2584         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
2585                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
2586         return *p;
2587 }
2588
2589 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
2590 {
2591         u32 eb;
2592
2593         eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
2594              (1u << DB_VECTOR) | (1u << AC_VECTOR);
2595         /*
2596          * Guest access to VMware backdoor ports could legitimately
2597          * trigger #GP because of TSS I/O permission bitmap.
2598          * We intercept those #GP and allow access to them anyway
2599          * as VMware does.
2600          */
2601         if (enable_vmware_backdoor)
2602                 eb |= (1u << GP_VECTOR);
2603         if ((vcpu->guest_debug &
2604              (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
2605             (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
2606                 eb |= 1u << BP_VECTOR;
2607         if (to_vmx(vcpu)->rmode.vm86_active)
2608                 eb = ~0;
2609         if (enable_ept)
2610                 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
2611
2612         /* When we are running a nested L2 guest and L1 specified for it a
2613          * certain exception bitmap, we must trap the same exceptions and pass
2614          * them to L1. When running L2, we will only handle the exceptions
2615          * specified above if L1 did not want them.
2616          */
2617         if (is_guest_mode(vcpu))
2618                 eb |= get_vmcs12(vcpu)->exception_bitmap;
2619
2620         vmcs_write32(EXCEPTION_BITMAP, eb);
2621 }
2622
2623 /*
2624  * Check if MSR is intercepted for currently loaded MSR bitmap.
2625  */
2626 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
2627 {
2628         unsigned long *msr_bitmap;
2629         int f = sizeof(unsigned long);
2630
2631         if (!cpu_has_vmx_msr_bitmap())
2632                 return true;
2633
2634         msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
2635
2636         if (msr <= 0x1fff) {
2637                 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2638         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2639                 msr &= 0x1fff;
2640                 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2641         }
2642
2643         return true;
2644 }
2645
2646 /*
2647  * Check if MSR is intercepted for L01 MSR bitmap.
2648  */
2649 static bool msr_write_intercepted_l01(struct kvm_vcpu *vcpu, u32 msr)
2650 {
2651         unsigned long *msr_bitmap;
2652         int f = sizeof(unsigned long);
2653
2654         if (!cpu_has_vmx_msr_bitmap())
2655                 return true;
2656
2657         msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
2658
2659         if (msr <= 0x1fff) {
2660                 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2661         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2662                 msr &= 0x1fff;
2663                 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2664         }
2665
2666         return true;
2667 }
2668
2669 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2670                 unsigned long entry, unsigned long exit)
2671 {
2672         vm_entry_controls_clearbit(vmx, entry);
2673         vm_exit_controls_clearbit(vmx, exit);
2674 }
2675
2676 static int find_msr(struct vmx_msrs *m, unsigned int msr)
2677 {
2678         unsigned int i;
2679
2680         for (i = 0; i < m->nr; ++i) {
2681                 if (m->val[i].index == msr)
2682                         return i;
2683         }
2684         return -ENOENT;
2685 }
2686
2687 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
2688 {
2689         int i;
2690         struct msr_autoload *m = &vmx->msr_autoload;
2691
2692         switch (msr) {
2693         case MSR_EFER:
2694                 if (cpu_has_load_ia32_efer) {
2695                         clear_atomic_switch_msr_special(vmx,
2696                                         VM_ENTRY_LOAD_IA32_EFER,
2697                                         VM_EXIT_LOAD_IA32_EFER);
2698                         return;
2699                 }
2700                 break;
2701         case MSR_CORE_PERF_GLOBAL_CTRL:
2702                 if (cpu_has_load_perf_global_ctrl) {
2703                         clear_atomic_switch_msr_special(vmx,
2704                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2705                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
2706                         return;
2707                 }
2708                 break;
2709         }
2710         i = find_msr(&m->guest, msr);
2711         if (i < 0)
2712                 goto skip_guest;
2713         --m->guest.nr;
2714         m->guest.val[i] = m->guest.val[m->guest.nr];
2715         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2716
2717 skip_guest:
2718         i = find_msr(&m->host, msr);
2719         if (i < 0)
2720                 return;
2721
2722         --m->host.nr;
2723         m->host.val[i] = m->host.val[m->host.nr];
2724         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2725 }
2726
2727 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2728                 unsigned long entry, unsigned long exit,
2729                 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
2730                 u64 guest_val, u64 host_val)
2731 {
2732         vmcs_write64(guest_val_vmcs, guest_val);
2733         if (host_val_vmcs != HOST_IA32_EFER)
2734                 vmcs_write64(host_val_vmcs, host_val);
2735         vm_entry_controls_setbit(vmx, entry);
2736         vm_exit_controls_setbit(vmx, exit);
2737 }
2738
2739 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
2740                                   u64 guest_val, u64 host_val, bool entry_only)
2741 {
2742         int i, j = 0;
2743         struct msr_autoload *m = &vmx->msr_autoload;
2744
2745         switch (msr) {
2746         case MSR_EFER:
2747                 if (cpu_has_load_ia32_efer) {
2748                         add_atomic_switch_msr_special(vmx,
2749                                         VM_ENTRY_LOAD_IA32_EFER,
2750                                         VM_EXIT_LOAD_IA32_EFER,
2751                                         GUEST_IA32_EFER,
2752                                         HOST_IA32_EFER,
2753                                         guest_val, host_val);
2754                         return;
2755                 }
2756                 break;
2757         case MSR_CORE_PERF_GLOBAL_CTRL:
2758                 if (cpu_has_load_perf_global_ctrl) {
2759                         add_atomic_switch_msr_special(vmx,
2760                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2761                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
2762                                         GUEST_IA32_PERF_GLOBAL_CTRL,
2763                                         HOST_IA32_PERF_GLOBAL_CTRL,
2764                                         guest_val, host_val);
2765                         return;
2766                 }
2767                 break;
2768         case MSR_IA32_PEBS_ENABLE:
2769                 /* PEBS needs a quiescent period after being disabled (to write
2770                  * a record).  Disabling PEBS through VMX MSR swapping doesn't
2771                  * provide that period, so a CPU could write host's record into
2772                  * guest's memory.
2773                  */
2774                 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
2775         }
2776
2777         i = find_msr(&m->guest, msr);
2778         if (!entry_only)
2779                 j = find_msr(&m->host, msr);
2780
2781         if (i == NR_AUTOLOAD_MSRS || j == NR_AUTOLOAD_MSRS) {
2782                 printk_once(KERN_WARNING "Not enough msr switch entries. "
2783                                 "Can't add msr %x\n", msr);
2784                 return;
2785         }
2786         if (i < 0) {
2787                 i = m->guest.nr++;
2788                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2789         }
2790         m->guest.val[i].index = msr;
2791         m->guest.val[i].value = guest_val;
2792
2793         if (entry_only)
2794                 return;
2795
2796         if (j < 0) {
2797                 j = m->host.nr++;
2798                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2799         }
2800         m->host.val[j].index = msr;
2801         m->host.val[j].value = host_val;
2802 }
2803
2804 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
2805 {
2806         u64 guest_efer = vmx->vcpu.arch.efer;
2807         u64 ignore_bits = 0;
2808
2809         if (!enable_ept) {
2810                 /*
2811                  * NX is needed to handle CR0.WP=1, CR4.SMEP=1.  Testing
2812                  * host CPUID is more efficient than testing guest CPUID
2813                  * or CR4.  Host SMEP is anyway a requirement for guest SMEP.
2814                  */
2815                 if (boot_cpu_has(X86_FEATURE_SMEP))
2816                         guest_efer |= EFER_NX;
2817                 else if (!(guest_efer & EFER_NX))
2818                         ignore_bits |= EFER_NX;
2819         }
2820
2821         /*
2822          * LMA and LME handled by hardware; SCE meaningless outside long mode.
2823          */
2824         ignore_bits |= EFER_SCE;
2825 #ifdef CONFIG_X86_64
2826         ignore_bits |= EFER_LMA | EFER_LME;
2827         /* SCE is meaningful only in long mode on Intel */
2828         if (guest_efer & EFER_LMA)
2829                 ignore_bits &= ~(u64)EFER_SCE;
2830 #endif
2831
2832         /*
2833          * On EPT, we can't emulate NX, so we must switch EFER atomically.
2834          * On CPUs that support "load IA32_EFER", always switch EFER
2835          * atomically, since it's faster than switching it manually.
2836          */
2837         if (cpu_has_load_ia32_efer ||
2838             (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
2839                 if (!(guest_efer & EFER_LMA))
2840                         guest_efer &= ~EFER_LME;
2841                 if (guest_efer != host_efer)
2842                         add_atomic_switch_msr(vmx, MSR_EFER,
2843                                               guest_efer, host_efer, false);
2844                 else
2845                         clear_atomic_switch_msr(vmx, MSR_EFER);
2846                 return false;
2847         } else {
2848                 clear_atomic_switch_msr(vmx, MSR_EFER);
2849
2850                 guest_efer &= ~ignore_bits;
2851                 guest_efer |= host_efer & ignore_bits;
2852
2853                 vmx->guest_msrs[efer_offset].data = guest_efer;
2854                 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
2855
2856                 return true;
2857         }
2858 }
2859
2860 #ifdef CONFIG_X86_32
2861 /*
2862  * On 32-bit kernels, VM exits still load the FS and GS bases from the
2863  * VMCS rather than the segment table.  KVM uses this helper to figure
2864  * out the current bases to poke them into the VMCS before entry.
2865  */
2866 static unsigned long segment_base(u16 selector)
2867 {
2868         struct desc_struct *table;
2869         unsigned long v;
2870
2871         if (!(selector & ~SEGMENT_RPL_MASK))
2872                 return 0;
2873
2874         table = get_current_gdt_ro();
2875
2876         if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
2877                 u16 ldt_selector = kvm_read_ldt();
2878
2879                 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
2880                         return 0;
2881
2882                 table = (struct desc_struct *)segment_base(ldt_selector);
2883         }
2884         v = get_desc_base(&table[selector >> 3]);
2885         return v;
2886 }
2887 #endif
2888
2889 static void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
2890 {
2891         struct vcpu_vmx *vmx = to_vmx(vcpu);
2892         struct vmcs_host_state *host_state;
2893 #ifdef CONFIG_X86_64
2894         int cpu = raw_smp_processor_id();
2895 #endif
2896         unsigned long fs_base, gs_base;
2897         u16 fs_sel, gs_sel;
2898         int i;
2899
2900         vmx->req_immediate_exit = false;
2901
2902         /*
2903          * Note that guest MSRs to be saved/restored can also be changed
2904          * when guest state is loaded. This happens when guest transitions
2905          * to/from long-mode by setting MSR_EFER.LMA.
2906          */
2907         if (!vmx->loaded_cpu_state || vmx->guest_msrs_dirty) {
2908                 vmx->guest_msrs_dirty = false;
2909                 for (i = 0; i < vmx->save_nmsrs; ++i)
2910                         kvm_set_shared_msr(vmx->guest_msrs[i].index,
2911                                            vmx->guest_msrs[i].data,
2912                                            vmx->guest_msrs[i].mask);
2913
2914         }
2915
2916         if (vmx->loaded_cpu_state)
2917                 return;
2918
2919         vmx->loaded_cpu_state = vmx->loaded_vmcs;
2920         host_state = &vmx->loaded_cpu_state->host_state;
2921
2922         /*
2923          * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
2924          * allow segment selectors with cpl > 0 or ti == 1.
2925          */
2926         host_state->ldt_sel = kvm_read_ldt();
2927
2928 #ifdef CONFIG_X86_64
2929         savesegment(ds, host_state->ds_sel);
2930         savesegment(es, host_state->es_sel);
2931
2932         gs_base = cpu_kernelmode_gs_base(cpu);
2933         if (likely(is_64bit_mm(current->mm))) {
2934                 save_fsgs_for_kvm();
2935                 fs_sel = current->thread.fsindex;
2936                 gs_sel = current->thread.gsindex;
2937                 fs_base = current->thread.fsbase;
2938                 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
2939         } else {
2940                 savesegment(fs, fs_sel);
2941                 savesegment(gs, gs_sel);
2942                 fs_base = read_msr(MSR_FS_BASE);
2943                 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
2944         }
2945
2946         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2947 #else
2948         savesegment(fs, fs_sel);
2949         savesegment(gs, gs_sel);
2950         fs_base = segment_base(fs_sel);
2951         gs_base = segment_base(gs_sel);
2952 #endif
2953
2954         if (unlikely(fs_sel != host_state->fs_sel)) {
2955                 if (!(fs_sel & 7))
2956                         vmcs_write16(HOST_FS_SELECTOR, fs_sel);
2957                 else
2958                         vmcs_write16(HOST_FS_SELECTOR, 0);
2959                 host_state->fs_sel = fs_sel;
2960         }
2961         if (unlikely(gs_sel != host_state->gs_sel)) {
2962                 if (!(gs_sel & 7))
2963                         vmcs_write16(HOST_GS_SELECTOR, gs_sel);
2964                 else
2965                         vmcs_write16(HOST_GS_SELECTOR, 0);
2966                 host_state->gs_sel = gs_sel;
2967         }
2968         if (unlikely(fs_base != host_state->fs_base)) {
2969                 vmcs_writel(HOST_FS_BASE, fs_base);
2970                 host_state->fs_base = fs_base;
2971         }
2972         if (unlikely(gs_base != host_state->gs_base)) {
2973                 vmcs_writel(HOST_GS_BASE, gs_base);
2974                 host_state->gs_base = gs_base;
2975         }
2976 }
2977
2978 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
2979 {
2980         struct vmcs_host_state *host_state;
2981
2982         if (!vmx->loaded_cpu_state)
2983                 return;
2984
2985         WARN_ON_ONCE(vmx->loaded_cpu_state != vmx->loaded_vmcs);
2986         host_state = &vmx->loaded_cpu_state->host_state;
2987
2988         ++vmx->vcpu.stat.host_state_reload;
2989         vmx->loaded_cpu_state = NULL;
2990
2991 #ifdef CONFIG_X86_64
2992         rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2993 #endif
2994         if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
2995                 kvm_load_ldt(host_state->ldt_sel);
2996 #ifdef CONFIG_X86_64
2997                 load_gs_index(host_state->gs_sel);
2998 #else
2999                 loadsegment(gs, host_state->gs_sel);
3000 #endif
3001         }
3002         if (host_state->fs_sel & 7)
3003                 loadsegment(fs, host_state->fs_sel);
3004 #ifdef CONFIG_X86_64
3005         if (unlikely(host_state->ds_sel | host_state->es_sel)) {
3006                 loadsegment(ds, host_state->ds_sel);
3007                 loadsegment(es, host_state->es_sel);
3008         }
3009 #endif
3010         invalidate_tss_limit();
3011 #ifdef CONFIG_X86_64
3012         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
3013 #endif
3014         load_fixmap_gdt(raw_smp_processor_id());
3015 }
3016
3017 #ifdef CONFIG_X86_64
3018 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
3019 {
3020         preempt_disable();
3021         if (vmx->loaded_cpu_state)
3022                 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
3023         preempt_enable();
3024         return vmx->msr_guest_kernel_gs_base;
3025 }
3026
3027 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
3028 {
3029         preempt_disable();
3030         if (vmx->loaded_cpu_state)
3031                 wrmsrl(MSR_KERNEL_GS_BASE, data);
3032         preempt_enable();
3033         vmx->msr_guest_kernel_gs_base = data;
3034 }
3035 #endif
3036
3037 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
3038 {
3039         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
3040         struct pi_desc old, new;
3041         unsigned int dest;
3042
3043         /*
3044          * In case of hot-plug or hot-unplug, we may have to undo
3045          * vmx_vcpu_pi_put even if there is no assigned device.  And we
3046          * always keep PI.NDST up to date for simplicity: it makes the
3047          * code easier, and CPU migration is not a fast path.
3048          */
3049         if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
3050                 return;
3051
3052         /*
3053          * First handle the simple case where no cmpxchg is necessary; just
3054          * allow posting non-urgent interrupts.
3055          *
3056          * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
3057          * PI.NDST: pi_post_block will do it for us and the wakeup_handler
3058          * expects the VCPU to be on the blocked_vcpu_list that matches
3059          * PI.NDST.
3060          */
3061         if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR ||
3062             vcpu->cpu == cpu) {
3063                 pi_clear_sn(pi_desc);
3064                 return;
3065         }
3066
3067         /* The full case.  */
3068         do {
3069                 old.control = new.control = pi_desc->control;
3070
3071                 dest = cpu_physical_id(cpu);
3072
3073                 if (x2apic_enabled())
3074                         new.ndst = dest;
3075                 else
3076                         new.ndst = (dest << 8) & 0xFF00;
3077
3078                 new.sn = 0;
3079         } while (cmpxchg64(&pi_desc->control, old.control,
3080                            new.control) != old.control);
3081 }
3082
3083 static void decache_tsc_multiplier(struct vcpu_vmx *vmx)
3084 {
3085         vmx->current_tsc_ratio = vmx->vcpu.arch.tsc_scaling_ratio;
3086         vmcs_write64(TSC_MULTIPLIER, vmx->current_tsc_ratio);
3087 }
3088
3089 /*
3090  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
3091  * vcpu mutex is already taken.
3092  */
3093 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3094 {
3095         struct vcpu_vmx *vmx = to_vmx(vcpu);
3096         bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
3097
3098         if (!already_loaded) {
3099                 loaded_vmcs_clear(vmx->loaded_vmcs);
3100                 local_irq_disable();
3101                 crash_disable_local_vmclear(cpu);
3102
3103                 /*
3104                  * Read loaded_vmcs->cpu should be before fetching
3105                  * loaded_vmcs->loaded_vmcss_on_cpu_link.
3106                  * See the comments in __loaded_vmcs_clear().
3107                  */
3108                 smp_rmb();
3109
3110                 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
3111                          &per_cpu(loaded_vmcss_on_cpu, cpu));
3112                 crash_enable_local_vmclear(cpu);
3113                 local_irq_enable();
3114         }
3115
3116         if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
3117                 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
3118                 vmcs_load(vmx->loaded_vmcs->vmcs);
3119                 indirect_branch_prediction_barrier();
3120         }
3121
3122         if (!already_loaded) {
3123                 void *gdt = get_current_gdt_ro();
3124                 unsigned long sysenter_esp;
3125
3126                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3127
3128                 /*
3129                  * Linux uses per-cpu TSS and GDT, so set these when switching
3130                  * processors.  See 22.2.4.
3131                  */
3132                 vmcs_writel(HOST_TR_BASE,
3133                             (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
3134                 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt);   /* 22.2.4 */
3135
3136                 /*
3137                  * VM exits change the host TR limit to 0x67 after a VM
3138                  * exit.  This is okay, since 0x67 covers everything except
3139                  * the IO bitmap and have have code to handle the IO bitmap
3140                  * being lost after a VM exit.
3141                  */
3142                 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
3143
3144                 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
3145                 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
3146
3147                 vmx->loaded_vmcs->cpu = cpu;
3148         }
3149
3150         /* Setup TSC multiplier */
3151         if (kvm_has_tsc_control &&
3152             vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
3153                 decache_tsc_multiplier(vmx);
3154
3155         vmx_vcpu_pi_load(vcpu, cpu);
3156         vmx->host_pkru = read_pkru();
3157         vmx->host_debugctlmsr = get_debugctlmsr();
3158 }
3159
3160 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
3161 {
3162         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
3163
3164         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
3165                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
3166                 !kvm_vcpu_apicv_active(vcpu))
3167                 return;
3168
3169         /* Set SN when the vCPU is preempted */
3170         if (vcpu->preempted)
3171                 pi_set_sn(pi_desc);
3172 }
3173
3174 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
3175 {
3176         vmx_vcpu_pi_put(vcpu);
3177
3178         vmx_prepare_switch_to_host(to_vmx(vcpu));
3179 }
3180
3181 static bool emulation_required(struct kvm_vcpu *vcpu)
3182 {
3183         return emulate_invalid_guest_state && !guest_state_valid(vcpu);
3184 }
3185
3186 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
3187
3188 /*
3189  * Return the cr0 value that a nested guest would read. This is a combination
3190  * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
3191  * its hypervisor (cr0_read_shadow).
3192  */
3193 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
3194 {
3195         return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
3196                 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
3197 }
3198 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
3199 {
3200         return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
3201                 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
3202 }
3203
3204 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
3205 {
3206         unsigned long rflags, save_rflags;
3207
3208         if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
3209                 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
3210                 rflags = vmcs_readl(GUEST_RFLAGS);
3211                 if (to_vmx(vcpu)->rmode.vm86_active) {
3212                         rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
3213                         save_rflags = to_vmx(vcpu)->rmode.save_rflags;
3214                         rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
3215                 }
3216                 to_vmx(vcpu)->rflags = rflags;
3217         }
3218         return to_vmx(vcpu)->rflags;
3219 }
3220
3221 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
3222 {
3223         unsigned long old_rflags = vmx_get_rflags(vcpu);
3224
3225         __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
3226         to_vmx(vcpu)->rflags = rflags;
3227         if (to_vmx(vcpu)->rmode.vm86_active) {
3228                 to_vmx(vcpu)->rmode.save_rflags = rflags;
3229                 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
3230         }
3231         vmcs_writel(GUEST_RFLAGS, rflags);
3232
3233         if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
3234                 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
3235 }
3236
3237 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
3238 {
3239         u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
3240         int ret = 0;
3241
3242         if (interruptibility & GUEST_INTR_STATE_STI)
3243                 ret |= KVM_X86_SHADOW_INT_STI;
3244         if (interruptibility & GUEST_INTR_STATE_MOV_SS)
3245                 ret |= KVM_X86_SHADOW_INT_MOV_SS;
3246
3247         return ret;
3248 }
3249
3250 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
3251 {
3252         u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
3253         u32 interruptibility = interruptibility_old;
3254
3255         interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
3256
3257         if (mask & KVM_X86_SHADOW_INT_MOV_SS)
3258                 interruptibility |= GUEST_INTR_STATE_MOV_SS;
3259         else if (mask & KVM_X86_SHADOW_INT_STI)
3260                 interruptibility |= GUEST_INTR_STATE_STI;
3261
3262         if ((interruptibility != interruptibility_old))
3263                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
3264 }
3265
3266 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
3267 {
3268         unsigned long rip;
3269
3270         rip = kvm_rip_read(vcpu);
3271         rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
3272         kvm_rip_write(vcpu, rip);
3273
3274         /* skipping an emulated instruction also counts */
3275         vmx_set_interrupt_shadow(vcpu, 0);
3276 }
3277
3278 static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
3279                                                unsigned long exit_qual)
3280 {
3281         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3282         unsigned int nr = vcpu->arch.exception.nr;
3283         u32 intr_info = nr | INTR_INFO_VALID_MASK;
3284
3285         if (vcpu->arch.exception.has_error_code) {
3286                 vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code;
3287                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
3288         }
3289
3290         if (kvm_exception_is_soft(nr))
3291                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
3292         else
3293                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
3294
3295         if (!(vmcs12->idt_vectoring_info_field & VECTORING_INFO_VALID_MASK) &&
3296             vmx_get_nmi_mask(vcpu))
3297                 intr_info |= INTR_INFO_UNBLOCK_NMI;
3298
3299         nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI, intr_info, exit_qual);
3300 }
3301
3302 /*
3303  * KVM wants to inject page-faults which it got to the guest. This function
3304  * checks whether in a nested guest, we need to inject them to L1 or L2.
3305  */
3306 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned long *exit_qual)
3307 {
3308         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3309         unsigned int nr = vcpu->arch.exception.nr;
3310         bool has_payload = vcpu->arch.exception.has_payload;
3311         unsigned long payload = vcpu->arch.exception.payload;
3312
3313         if (nr == PF_VECTOR) {
3314                 if (vcpu->arch.exception.nested_apf) {
3315                         *exit_qual = vcpu->arch.apf.nested_apf_token;
3316                         return 1;
3317                 }
3318                 if (nested_vmx_is_page_fault_vmexit(vmcs12,
3319                                                     vcpu->arch.exception.error_code)) {
3320                         *exit_qual = has_payload ? payload : vcpu->arch.cr2;
3321                         return 1;
3322                 }
3323         } else if (vmcs12->exception_bitmap & (1u << nr)) {
3324                 if (nr == DB_VECTOR) {
3325                         if (!has_payload) {
3326                                 payload = vcpu->arch.dr6;
3327                                 payload &= ~(DR6_FIXED_1 | DR6_BT);
3328                                 payload ^= DR6_RTM;
3329                         }
3330                         *exit_qual = payload;
3331                 } else
3332                         *exit_qual = 0;
3333                 return 1;
3334         }
3335
3336         return 0;
3337 }
3338
3339 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
3340 {
3341         /*
3342          * Ensure that we clear the HLT state in the VMCS.  We don't need to
3343          * explicitly skip the instruction because if the HLT state is set,
3344          * then the instruction is already executing and RIP has already been
3345          * advanced.
3346          */
3347         if (kvm_hlt_in_guest(vcpu->kvm) &&
3348                         vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
3349                 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
3350 }
3351
3352 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
3353 {
3354         struct vcpu_vmx *vmx = to_vmx(vcpu);
3355         unsigned nr = vcpu->arch.exception.nr;
3356         bool has_error_code = vcpu->arch.exception.has_error_code;
3357         u32 error_code = vcpu->arch.exception.error_code;
3358         u32 intr_info = nr | INTR_INFO_VALID_MASK;
3359
3360         kvm_deliver_exception_payload(vcpu);
3361
3362         if (has_error_code) {
3363                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
3364                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
3365         }
3366
3367         if (vmx->rmode.vm86_active) {
3368                 int inc_eip = 0;
3369                 if (kvm_exception_is_soft(nr))
3370                         inc_eip = vcpu->arch.event_exit_inst_len;
3371                 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
3372                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3373                 return;
3374         }
3375
3376         WARN_ON_ONCE(vmx->emulation_required);
3377
3378         if (kvm_exception_is_soft(nr)) {
3379                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
3380                              vmx->vcpu.arch.event_exit_inst_len);
3381                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
3382         } else
3383                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
3384
3385         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
3386
3387         vmx_clear_hlt(vcpu);
3388 }
3389
3390 static bool vmx_rdtscp_supported(void)
3391 {
3392         return cpu_has_vmx_rdtscp();
3393 }
3394
3395 static bool vmx_invpcid_supported(void)
3396 {
3397         return cpu_has_vmx_invpcid();
3398 }
3399
3400 /*
3401  * Swap MSR entry in host/guest MSR entry array.
3402  */
3403 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
3404 {
3405         struct shared_msr_entry tmp;
3406
3407         tmp = vmx->guest_msrs[to];
3408         vmx->guest_msrs[to] = vmx->guest_msrs[from];
3409         vmx->guest_msrs[from] = tmp;
3410 }
3411
3412 /*
3413  * Set up the vmcs to automatically save and restore system
3414  * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
3415  * mode, as fiddling with msrs is very expensive.
3416  */
3417 static void setup_msrs(struct vcpu_vmx *vmx)
3418 {
3419         int save_nmsrs, index;
3420
3421         save_nmsrs = 0;
3422 #ifdef CONFIG_X86_64
3423         if (is_long_mode(&vmx->vcpu)) {
3424                 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
3425                 if (index >= 0)
3426                         move_msr_up(vmx, index, save_nmsrs++);
3427                 index = __find_msr_index(vmx, MSR_LSTAR);
3428                 if (index >= 0)
3429                         move_msr_up(vmx, index, save_nmsrs++);
3430                 index = __find_msr_index(vmx, MSR_CSTAR);
3431                 if (index >= 0)
3432                         move_msr_up(vmx, index, save_nmsrs++);
3433                 index = __find_msr_index(vmx, MSR_TSC_AUX);
3434                 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
3435                         move_msr_up(vmx, index, save_nmsrs++);
3436                 /*
3437                  * MSR_STAR is only needed on long mode guests, and only
3438                  * if efer.sce is enabled.
3439                  */
3440                 index = __find_msr_index(vmx, MSR_STAR);
3441                 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
3442                         move_msr_up(vmx, index, save_nmsrs++);
3443         }
3444 #endif
3445         index = __find_msr_index(vmx, MSR_EFER);
3446         if (index >= 0 && update_transition_efer(vmx, index))
3447                 move_msr_up(vmx, index, save_nmsrs++);
3448
3449         vmx->save_nmsrs = save_nmsrs;
3450         vmx->guest_msrs_dirty = true;
3451
3452         if (cpu_has_vmx_msr_bitmap())
3453                 vmx_update_msr_bitmap(&vmx->vcpu);
3454 }
3455
3456 static u64 vmx_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
3457 {
3458         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3459
3460         if (is_guest_mode(vcpu) &&
3461             (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
3462                 return vcpu->arch.tsc_offset - vmcs12->tsc_offset;
3463
3464         return vcpu->arch.tsc_offset;
3465 }
3466
3467 static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
3468 {
3469         u64 active_offset = offset;
3470         if (is_guest_mode(vcpu)) {
3471                 /*
3472                  * We're here if L1 chose not to trap WRMSR to TSC. According
3473                  * to the spec, this should set L1's TSC; The offset that L1
3474                  * set for L2 remains unchanged, and still needs to be added
3475                  * to the newly set TSC to get L2's TSC.
3476                  */
3477                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3478                 if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING))
3479                         active_offset += vmcs12->tsc_offset;
3480         } else {
3481                 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
3482                                            vmcs_read64(TSC_OFFSET), offset);
3483         }
3484
3485         vmcs_write64(TSC_OFFSET, active_offset);
3486         return active_offset;
3487 }
3488
3489 /*
3490  * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
3491  * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
3492  * all guests if the "nested" module option is off, and can also be disabled
3493  * for a single guest by disabling its VMX cpuid bit.
3494  */
3495 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
3496 {
3497         return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
3498 }
3499
3500 /*
3501  * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
3502  * returned for the various VMX controls MSRs when nested VMX is enabled.
3503  * The same values should also be used to verify that vmcs12 control fields are
3504  * valid during nested entry from L1 to L2.
3505  * Each of these control msrs has a low and high 32-bit half: A low bit is on
3506  * if the corresponding bit in the (32-bit) control field *must* be on, and a
3507  * bit in the high half is on if the corresponding bit in the control field
3508  * may be on. See also vmx_control_verify().
3509  */
3510 static void nested_vmx_setup_ctls_msrs(struct nested_vmx_msrs *msrs, bool apicv)
3511 {
3512         if (!nested) {
3513                 memset(msrs, 0, sizeof(*msrs));
3514                 return;
3515         }
3516
3517         /*
3518          * Note that as a general rule, the high half of the MSRs (bits in
3519          * the control fields which may be 1) should be initialized by the
3520          * intersection of the underlying hardware's MSR (i.e., features which
3521          * can be supported) and the list of features we want to expose -
3522          * because they are known to be properly supported in our code.
3523          * Also, usually, the low half of the MSRs (bits which must be 1) can
3524          * be set to 0, meaning that L1 may turn off any of these bits. The
3525          * reason is that if one of these bits is necessary, it will appear
3526          * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
3527          * fields of vmcs01 and vmcs02, will turn these bits off - and
3528          * nested_vmx_exit_reflected() will not pass related exits to L1.
3529          * These rules have exceptions below.
3530          */
3531
3532         /* pin-based controls */
3533         rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
3534                 msrs->pinbased_ctls_low,
3535                 msrs->pinbased_ctls_high);
3536         msrs->pinbased_ctls_low |=
3537                 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3538         msrs->pinbased_ctls_high &=
3539                 PIN_BASED_EXT_INTR_MASK |
3540                 PIN_BASED_NMI_EXITING |
3541                 PIN_BASED_VIRTUAL_NMIS |
3542                 (apicv ? PIN_BASED_POSTED_INTR : 0);
3543         msrs->pinbased_ctls_high |=
3544                 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
3545                 PIN_BASED_VMX_PREEMPTION_TIMER;
3546
3547         /* exit controls */
3548         rdmsr(MSR_IA32_VMX_EXIT_CTLS,
3549                 msrs->exit_ctls_low,
3550                 msrs->exit_ctls_high);
3551         msrs->exit_ctls_low =
3552                 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
3553
3554         msrs->exit_ctls_high &=
3555 #ifdef CONFIG_X86_64
3556                 VM_EXIT_HOST_ADDR_SPACE_SIZE |
3557 #endif
3558                 VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
3559         msrs->exit_ctls_high |=
3560                 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
3561                 VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
3562                 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
3563
3564         /* We support free control of debug control saving. */
3565         msrs->exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
3566
3567         /* entry controls */
3568         rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
3569                 msrs->entry_ctls_low,
3570                 msrs->entry_ctls_high);
3571         msrs->entry_ctls_low =
3572                 VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
3573         msrs->entry_ctls_high &=
3574 #ifdef CONFIG_X86_64
3575                 VM_ENTRY_IA32E_MODE |
3576 #endif
3577                 VM_ENTRY_LOAD_IA32_PAT;
3578         msrs->entry_ctls_high |=
3579                 (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
3580
3581         /* We support free control of debug control loading. */
3582         msrs->entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
3583
3584         /* cpu-based controls */
3585         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
3586                 msrs->procbased_ctls_low,
3587                 msrs->procbased_ctls_high);
3588         msrs->procbased_ctls_low =
3589                 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3590         msrs->procbased_ctls_high &=
3591                 CPU_BASED_VIRTUAL_INTR_PENDING |
3592                 CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
3593                 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
3594                 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
3595                 CPU_BASED_CR3_STORE_EXITING |
3596 #ifdef CONFIG_X86_64
3597                 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
3598 #endif
3599                 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
3600                 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
3601                 CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
3602                 CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
3603                 CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
3604         /*
3605          * We can allow some features even when not supported by the
3606          * hardware. For example, L1 can specify an MSR bitmap - and we
3607          * can use it to avoid exits to L1 - even when L0 runs L2
3608          * without MSR bitmaps.
3609          */
3610         msrs->procbased_ctls_high |=
3611                 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
3612                 CPU_BASED_USE_MSR_BITMAPS;
3613
3614         /* We support free control of CR3 access interception. */
3615         msrs->procbased_ctls_low &=
3616                 ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
3617
3618         /*
3619          * secondary cpu-based controls.  Do not include those that
3620          * depend on CPUID bits, they are added later by vmx_cpuid_update.
3621          */
3622         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
3623                 msrs->secondary_ctls_low,
3624                 msrs->secondary_ctls_high);
3625         msrs->secondary_ctls_low = 0;
3626         msrs->secondary_ctls_high &=
3627                 SECONDARY_EXEC_DESC |
3628                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3629                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3630                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
3631                 SECONDARY_EXEC_WBINVD_EXITING;
3632
3633         /*
3634          * We can emulate "VMCS shadowing," even if the hardware
3635          * doesn't support it.
3636          */
3637         msrs->secondary_ctls_high |=
3638                 SECONDARY_EXEC_SHADOW_VMCS;
3639
3640         if (enable_ept) {
3641                 /* nested EPT: emulate EPT also to L1 */
3642                 msrs->secondary_ctls_high |=
3643                         SECONDARY_EXEC_ENABLE_EPT;
3644                 msrs->ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
3645                          VMX_EPTP_WB_BIT | VMX_EPT_INVEPT_BIT;
3646                 if (cpu_has_vmx_ept_execute_only())
3647                         msrs->ept_caps |=
3648                                 VMX_EPT_EXECUTE_ONLY_BIT;
3649                 msrs->ept_caps &= vmx_capability.ept;
3650                 msrs->ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
3651                         VMX_EPT_EXTENT_CONTEXT_BIT | VMX_EPT_2MB_PAGE_BIT |
3652                         VMX_EPT_1GB_PAGE_BIT;
3653                 if (enable_ept_ad_bits) {
3654                         msrs->secondary_ctls_high |=
3655                                 SECONDARY_EXEC_ENABLE_PML;
3656                         msrs->ept_caps |= VMX_EPT_AD_BIT;
3657                 }
3658         }
3659
3660         if (cpu_has_vmx_vmfunc()) {
3661                 msrs->secondary_ctls_high |=
3662                         SECONDARY_EXEC_ENABLE_VMFUNC;
3663                 /*
3664                  * Advertise EPTP switching unconditionally
3665                  * since we emulate it
3666                  */
3667                 if (enable_ept)
3668                         msrs->vmfunc_controls =
3669                                 VMX_VMFUNC_EPTP_SWITCHING;
3670         }
3671
3672         /*
3673          * Old versions of KVM use the single-context version without
3674          * checking for support, so declare that it is supported even
3675          * though it is treated as global context.  The alternative is
3676          * not failing the single-context invvpid, and it is worse.
3677          */
3678         if (enable_vpid) {
3679                 msrs->secondary_ctls_high |=
3680                         SECONDARY_EXEC_ENABLE_VPID;
3681                 msrs->vpid_caps = VMX_VPID_INVVPID_BIT |
3682                         VMX_VPID_EXTENT_SUPPORTED_MASK;
3683         }
3684
3685         if (enable_unrestricted_guest)
3686                 msrs->secondary_ctls_high |=
3687                         SECONDARY_EXEC_UNRESTRICTED_GUEST;
3688
3689         if (flexpriority_enabled)
3690                 msrs->secondary_ctls_high |=
3691                         SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
3692
3693         /* miscellaneous data */
3694         rdmsr(MSR_IA32_VMX_MISC,
3695                 msrs->misc_low,
3696                 msrs->misc_high);
3697         msrs->misc_low &= VMX_MISC_SAVE_EFER_LMA;
3698         msrs->misc_low |=
3699                 MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS |
3700                 VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
3701                 VMX_MISC_ACTIVITY_HLT;
3702         msrs->misc_high = 0;
3703
3704         /*
3705          * This MSR reports some information about VMX support. We
3706          * should return information about the VMX we emulate for the
3707          * guest, and the VMCS structure we give it - not about the
3708          * VMX support of the underlying hardware.
3709          */
3710         msrs->basic =
3711                 VMCS12_REVISION |
3712                 VMX_BASIC_TRUE_CTLS |
3713                 ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
3714                 (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
3715
3716         if (cpu_has_vmx_basic_inout())
3717                 msrs->basic |= VMX_BASIC_INOUT;
3718
3719         /*
3720          * These MSRs specify bits which the guest must keep fixed on
3721          * while L1 is in VMXON mode (in L1's root mode, or running an L2).
3722          * We picked the standard core2 setting.
3723          */
3724 #define VMXON_CR0_ALWAYSON     (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
3725 #define VMXON_CR4_ALWAYSON     X86_CR4_VMXE
3726         msrs->cr0_fixed0 = VMXON_CR0_ALWAYSON;
3727         msrs->cr4_fixed0 = VMXON_CR4_ALWAYSON;
3728
3729         /* These MSRs specify bits which the guest must keep fixed off. */
3730         rdmsrl(MSR_IA32_VMX_CR0_FIXED1, msrs->cr0_fixed1);
3731         rdmsrl(MSR_IA32_VMX_CR4_FIXED1, msrs->cr4_fixed1);
3732
3733         /* highest index: VMX_PREEMPTION_TIMER_VALUE */
3734         msrs->vmcs_enum = VMCS12_MAX_FIELD_INDEX << 1;
3735 }
3736
3737 /*
3738  * if fixed0[i] == 1: val[i] must be 1
3739  * if fixed1[i] == 0: val[i] must be 0
3740  */
3741 static inline bool fixed_bits_valid(u64 val, u64 fixed0, u64 fixed1)
3742 {
3743         return ((val & fixed1) | fixed0) == val;
3744 }
3745
3746 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
3747 {
3748         return fixed_bits_valid(control, low, high);
3749 }
3750
3751 static inline u64 vmx_control_msr(u32 low, u32 high)
3752 {
3753         return low | ((u64)high << 32);
3754 }
3755
3756 static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
3757 {
3758         superset &= mask;
3759         subset &= mask;
3760
3761         return (superset | subset) == superset;
3762 }
3763
3764 static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
3765 {
3766         const u64 feature_and_reserved =
3767                 /* feature (except bit 48; see below) */
3768                 BIT_ULL(49) | BIT_ULL(54) | BIT_ULL(55) |
3769                 /* reserved */
3770                 BIT_ULL(31) | GENMASK_ULL(47, 45) | GENMASK_ULL(63, 56);
3771         u64 vmx_basic = vmx->nested.msrs.basic;
3772
3773         if (!is_bitwise_subset(vmx_basic, data, feature_and_reserved))
3774                 return -EINVAL;
3775
3776         /*
3777          * KVM does not emulate a version of VMX that constrains physical
3778          * addresses of VMX structures (e.g. VMCS) to 32-bits.
3779          */
3780         if (data & BIT_ULL(48))
3781                 return -EINVAL;
3782
3783         if (vmx_basic_vmcs_revision_id(vmx_basic) !=
3784             vmx_basic_vmcs_revision_id(data))
3785                 return -EINVAL;
3786
3787         if (vmx_basic_vmcs_size(vmx_basic) > vmx_basic_vmcs_size(data))
3788                 return -EINVAL;
3789
3790         vmx->nested.msrs.basic = data;
3791         return 0;
3792 }
3793
3794 static int
3795 vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3796 {
3797         u64 supported;
3798         u32 *lowp, *highp;
3799
3800         switch (msr_index) {
3801         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3802                 lowp = &vmx->nested.msrs.pinbased_ctls_low;
3803                 highp = &vmx->nested.msrs.pinbased_ctls_high;
3804                 break;
3805         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3806                 lowp = &vmx->nested.msrs.procbased_ctls_low;
3807                 highp = &vmx->nested.msrs.procbased_ctls_high;
3808                 break;
3809         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3810                 lowp = &vmx->nested.msrs.exit_ctls_low;
3811                 highp = &vmx->nested.msrs.exit_ctls_high;
3812                 break;
3813         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3814                 lowp = &vmx->nested.msrs.entry_ctls_low;
3815                 highp = &vmx->nested.msrs.entry_ctls_high;
3816                 break;
3817         case MSR_IA32_VMX_PROCBASED_CTLS2:
3818                 lowp = &vmx->nested.msrs.secondary_ctls_low;
3819                 highp = &vmx->nested.msrs.secondary_ctls_high;
3820                 break;
3821         default:
3822                 BUG();
3823         }
3824
3825         supported = vmx_control_msr(*lowp, *highp);
3826
3827         /* Check must-be-1 bits are still 1. */
3828         if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0)))
3829                 return -EINVAL;
3830
3831         /* Check must-be-0 bits are still 0. */
3832         if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32)))
3833                 return -EINVAL;
3834
3835         *lowp = data;
3836         *highp = data >> 32;
3837         return 0;
3838 }
3839
3840 static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
3841 {
3842         const u64 feature_and_reserved_bits =
3843                 /* feature */
3844                 BIT_ULL(5) | GENMASK_ULL(8, 6) | BIT_ULL(14) | BIT_ULL(15) |
3845                 BIT_ULL(28) | BIT_ULL(29) | BIT_ULL(30) |
3846                 /* reserved */
3847                 GENMASK_ULL(13, 9) | BIT_ULL(31);
3848         u64 vmx_misc;
3849
3850         vmx_misc = vmx_control_msr(vmx->nested.msrs.misc_low,
3851                                    vmx->nested.msrs.misc_high);
3852
3853         if (!is_bitwise_subset(vmx_misc, data, feature_and_reserved_bits))
3854                 return -EINVAL;
3855
3856         if ((vmx->nested.msrs.pinbased_ctls_high &
3857              PIN_BASED_VMX_PREEMPTION_TIMER) &&
3858             vmx_misc_preemption_timer_rate(data) !=
3859             vmx_misc_preemption_timer_rate(vmx_misc))
3860                 return -EINVAL;
3861
3862         if (vmx_misc_cr3_count(data) > vmx_misc_cr3_count(vmx_misc))
3863                 return -EINVAL;
3864
3865         if (vmx_misc_max_msr(data) > vmx_misc_max_msr(vmx_misc))
3866                 return -EINVAL;
3867
3868         if (vmx_misc_mseg_revid(data) != vmx_misc_mseg_revid(vmx_misc))
3869                 return -EINVAL;
3870
3871         vmx->nested.msrs.misc_low = data;
3872         vmx->nested.msrs.misc_high = data >> 32;
3873
3874         /*
3875          * If L1 has read-only VM-exit information fields, use the
3876          * less permissive vmx_vmwrite_bitmap to specify write
3877          * permissions for the shadow VMCS.
3878          */
3879         if (enable_shadow_vmcs && !nested_cpu_has_vmwrite_any_field(&vmx->vcpu))
3880                 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
3881
3882         return 0;
3883 }
3884
3885 static int vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx *vmx, u64 data)
3886 {
3887         u64 vmx_ept_vpid_cap;
3888
3889         vmx_ept_vpid_cap = vmx_control_msr(vmx->nested.msrs.ept_caps,
3890                                            vmx->nested.msrs.vpid_caps);
3891
3892         /* Every bit is either reserved or a feature bit. */
3893         if (!is_bitwise_subset(vmx_ept_vpid_cap, data, -1ULL))
3894                 return -EINVAL;
3895
3896         vmx->nested.msrs.ept_caps = data;
3897         vmx->nested.msrs.vpid_caps = data >> 32;
3898         return 0;
3899 }
3900
3901 static int vmx_restore_fixed0_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3902 {
3903         u64 *msr;
3904
3905         switch (msr_index) {
3906         case MSR_IA32_VMX_CR0_FIXED0:
3907                 msr = &vmx->nested.msrs.cr0_fixed0;
3908                 break;
3909         case MSR_IA32_VMX_CR4_FIXED0:
3910                 msr = &vmx->nested.msrs.cr4_fixed0;
3911                 break;
3912         default:
3913                 BUG();
3914         }
3915
3916         /*
3917          * 1 bits (which indicates bits which "must-be-1" during VMX operation)
3918          * must be 1 in the restored value.
3919          */
3920         if (!is_bitwise_subset(data, *msr, -1ULL))
3921                 return -EINVAL;
3922
3923         *msr = data;
3924         return 0;
3925 }
3926
3927 /*
3928  * Called when userspace is restoring VMX MSRs.
3929  *
3930  * Returns 0 on success, non-0 otherwise.
3931  */
3932 static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
3933 {
3934         struct vcpu_vmx *vmx = to_vmx(vcpu);
3935
3936         /*
3937          * Don't allow changes to the VMX capability MSRs while the vCPU
3938          * is in VMX operation.
3939          */
3940         if (vmx->nested.vmxon)
3941                 return -EBUSY;
3942
3943         switch (msr_index) {
3944         case MSR_IA32_VMX_BASIC:
3945                 return vmx_restore_vmx_basic(vmx, data);
3946         case MSR_IA32_VMX_PINBASED_CTLS:
3947         case MSR_IA32_VMX_PROCBASED_CTLS:
3948         case MSR_IA32_VMX_EXIT_CTLS:
3949         case MSR_IA32_VMX_ENTRY_CTLS:
3950                 /*
3951                  * The "non-true" VMX capability MSRs are generated from the
3952                  * "true" MSRs, so we do not support restoring them directly.
3953                  *
3954                  * If userspace wants to emulate VMX_BASIC[55]=0, userspace
3955                  * should restore the "true" MSRs with the must-be-1 bits
3956                  * set according to the SDM Vol 3. A.2 "RESERVED CONTROLS AND
3957                  * DEFAULT SETTINGS".
3958                  */
3959                 return -EINVAL;
3960         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3961         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3962         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3963         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3964         case MSR_IA32_VMX_PROCBASED_CTLS2:
3965                 return vmx_restore_control_msr(vmx, msr_index, data);
3966         case MSR_IA32_VMX_MISC:
3967                 return vmx_restore_vmx_misc(vmx, data);
3968         case MSR_IA32_VMX_CR0_FIXED0:
3969         case MSR_IA32_VMX_CR4_FIXED0:
3970                 return vmx_restore_fixed0_msr(vmx, msr_index, data);
3971         case MSR_IA32_VMX_CR0_FIXED1:
3972         case MSR_IA32_VMX_CR4_FIXED1:
3973                 /*
3974                  * These MSRs are generated based on the vCPU's CPUID, so we
3975                  * do not support restoring them directly.
3976                  */
3977                 return -EINVAL;
3978         case MSR_IA32_VMX_EPT_VPID_CAP:
3979                 return vmx_restore_vmx_ept_vpid_cap(vmx, data);
3980         case MSR_IA32_VMX_VMCS_ENUM:
3981                 vmx->nested.msrs.vmcs_enum = data;
3982                 return 0;
3983         default:
3984                 /*
3985                  * The rest of the VMX capability MSRs do not support restore.
3986                  */
3987                 return -EINVAL;
3988         }
3989 }
3990
3991 /* Returns 0 on success, non-0 otherwise. */
3992 static int vmx_get_vmx_msr(struct nested_vmx_msrs *msrs, u32 msr_index, u64 *pdata)
3993 {
3994         switch (msr_index) {
3995         case MSR_IA32_VMX_BASIC:
3996                 *pdata = msrs->basic;
3997                 break;
3998         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3999         case MSR_IA32_VMX_PINBASED_CTLS:
4000                 *pdata = vmx_control_msr(
4001                         msrs->pinbased_ctls_low,
4002                         msrs->pinbased_ctls_high);
4003                 if (msr_index == MSR_IA32_VMX_PINBASED_CTLS)
4004                         *pdata |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
4005                 break;
4006         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
4007         case MSR_IA32_VMX_PROCBASED_CTLS:
4008                 *pdata = vmx_control_msr(
4009                         msrs->procbased_ctls_low,
4010                         msrs->procbased_ctls_high);
4011                 if (msr_index == MSR_IA32_VMX_PROCBASED_CTLS)
4012                         *pdata |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
4013                 break;
4014         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
4015         case MSR_IA32_VMX_EXIT_CTLS:
4016                 *pdata = vmx_control_msr(
4017                         msrs->exit_ctls_low,
4018                         msrs->exit_ctls_high);
4019                 if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
4020                         *pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
4021                 break;
4022         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
4023         case MSR_IA32_VMX_ENTRY_CTLS:
4024                 *pdata = vmx_control_msr(
4025                         msrs->entry_ctls_low,
4026                         msrs->entry_ctls_high);
4027                 if (msr_index == MSR_IA32_VMX_ENTRY_CTLS)
4028                         *pdata |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
4029                 break;
4030         case MSR_IA32_VMX_MISC:
4031                 *pdata = vmx_control_msr(
4032                         msrs->misc_low,
4033                         msrs->misc_high);
4034                 break;
4035         case MSR_IA32_VMX_CR0_FIXED0:
4036                 *pdata = msrs->cr0_fixed0;
4037                 break;
4038         case MSR_IA32_VMX_CR0_FIXED1:
4039                 *pdata = msrs->cr0_fixed1;
4040                 break;
4041         case MSR_IA32_VMX_CR4_FIXED0:
4042                 *pdata = msrs->cr4_fixed0;
4043                 break;
4044         case MSR_IA32_VMX_CR4_FIXED1:
4045                 *pdata = msrs->cr4_fixed1;
4046                 break;
4047         case MSR_IA32_VMX_VMCS_ENUM:
4048                 *pdata = msrs->vmcs_enum;
4049                 break;
4050         case MSR_IA32_VMX_PROCBASED_CTLS2:
4051                 *pdata = vmx_control_msr(
4052                         msrs->secondary_ctls_low,
4053                         msrs->secondary_ctls_high);
4054                 break;
4055         case MSR_IA32_VMX_EPT_VPID_CAP:
4056                 *pdata = msrs->ept_caps |
4057                         ((u64)msrs->vpid_caps << 32);
4058                 break;
4059         case MSR_IA32_VMX_VMFUNC:
4060                 *pdata = msrs->vmfunc_controls;
4061                 break;
4062         default:
4063                 return 1;
4064         }
4065
4066         return 0;
4067 }
4068
4069 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
4070                                                  uint64_t val)
4071 {
4072         uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
4073
4074         return !(val & ~valid_bits);
4075 }
4076
4077 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
4078 {
4079         switch (msr->index) {
4080         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4081                 if (!nested)
4082                         return 1;
4083                 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
4084         default:
4085                 return 1;
4086         }
4087
4088         return 0;
4089 }
4090
4091 /*
4092  * Reads an msr value (of 'msr_index') into 'pdata'.
4093  * Returns 0 on success, non-0 otherwise.
4094  * Assumes vcpu_load() was already called.
4095  */
4096 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4097 {
4098         struct vcpu_vmx *vmx = to_vmx(vcpu);
4099         struct shared_msr_entry *msr;
4100
4101         switch (msr_info->index) {
4102 #ifdef CONFIG_X86_64
4103         case MSR_FS_BASE:
4104                 msr_info->data = vmcs_readl(GUEST_FS_BASE);
4105                 break;
4106         case MSR_GS_BASE:
4107                 msr_info->data = vmcs_readl(GUEST_GS_BASE);
4108                 break;
4109         case MSR_KERNEL_GS_BASE:
4110                 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
4111                 break;
4112 #endif
4113         case MSR_EFER:
4114                 return kvm_get_msr_common(vcpu, msr_info);
4115         case MSR_IA32_SPEC_CTRL:
4116                 if (!msr_info->host_initiated &&
4117                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
4118                         return 1;
4119
4120                 msr_info->data = to_vmx(vcpu)->spec_ctrl;
4121                 break;
4122         case MSR_IA32_ARCH_CAPABILITIES:
4123                 if (!msr_info->host_initiated &&
4124                     !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
4125                         return 1;
4126                 msr_info->data = to_vmx(vcpu)->arch_capabilities;
4127                 break;
4128         case MSR_IA32_SYSENTER_CS:
4129                 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
4130                 break;
4131         case MSR_IA32_SYSENTER_EIP:
4132                 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
4133                 break;
4134         case MSR_IA32_SYSENTER_ESP:
4135                 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
4136                 break;
4137         case MSR_IA32_BNDCFGS:
4138                 if (!kvm_mpx_supported() ||
4139                     (!msr_info->host_initiated &&
4140                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
4141                         return 1;
4142                 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
4143                 break;
4144         case MSR_IA32_MCG_EXT_CTL:
4145                 if (!msr_info->host_initiated &&
4146                     !(vmx->msr_ia32_feature_control &
4147                       FEATURE_CONTROL_LMCE))
4148                         return 1;
4149                 msr_info->data = vcpu->arch.mcg_ext_ctl;
4150                 break;
4151         case MSR_IA32_FEATURE_CONTROL:
4152                 msr_info->data = vmx->msr_ia32_feature_control;
4153                 break;
4154         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4155                 if (!nested_vmx_allowed(vcpu))
4156                         return 1;
4157                 return vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
4158                                        &msr_info->data);
4159         case MSR_IA32_XSS:
4160                 if (!vmx_xsaves_supported())
4161                         return 1;
4162                 msr_info->data = vcpu->arch.ia32_xss;
4163                 break;
4164         case MSR_TSC_AUX:
4165                 if (!msr_info->host_initiated &&
4166                     !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
4167                         return 1;
4168                 /* Otherwise falls through */
4169         default:
4170                 msr = find_msr_entry(vmx, msr_info->index);
4171                 if (msr) {
4172                         msr_info->data = msr->data;
4173                         break;
4174                 }
4175                 return kvm_get_msr_common(vcpu, msr_info);
4176         }
4177
4178         return 0;
4179 }
4180
4181 static void vmx_leave_nested(struct kvm_vcpu *vcpu);
4182
4183 /*
4184  * Writes msr value into into the appropriate "register".
4185  * Returns 0 on success, non-0 otherwise.
4186  * Assumes vcpu_load() was already called.
4187  */
4188 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4189 {
4190         struct vcpu_vmx *vmx = to_vmx(vcpu);
4191         struct shared_msr_entry *msr;
4192         int ret = 0;
4193         u32 msr_index = msr_info->index;
4194         u64 data = msr_info->data;
4195
4196         switch (msr_index) {
4197         case MSR_EFER:
4198                 ret = kvm_set_msr_common(vcpu, msr_info);
4199                 break;
4200 #ifdef CONFIG_X86_64
4201         case MSR_FS_BASE:
4202                 vmx_segment_cache_clear(vmx);
4203                 vmcs_writel(GUEST_FS_BASE, data);
4204                 break;
4205         case MSR_GS_BASE:
4206                 vmx_segment_cache_clear(vmx);
4207                 vmcs_writel(GUEST_GS_BASE, data);
4208                 break;
4209         case MSR_KERNEL_GS_BASE:
4210                 vmx_write_guest_kernel_gs_base(vmx, data);
4211                 break;
4212 #endif
4213         case MSR_IA32_SYSENTER_CS:
4214                 vmcs_write32(GUEST_SYSENTER_CS, data);
4215                 break;
4216         case MSR_IA32_SYSENTER_EIP:
4217                 vmcs_writel(GUEST_SYSENTER_EIP, data);
4218                 break;
4219         case MSR_IA32_SYSENTER_ESP:
4220                 vmcs_writel(GUEST_SYSENTER_ESP, data);
4221                 break;
4222         case MSR_IA32_BNDCFGS:
4223                 if (!kvm_mpx_supported() ||
4224                     (!msr_info->host_initiated &&
4225                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
4226                         return 1;
4227                 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
4228                     (data & MSR_IA32_BNDCFGS_RSVD))
4229                         return 1;
4230                 vmcs_write64(GUEST_BNDCFGS, data);
4231                 break;
4232         case MSR_IA32_SPEC_CTRL:
4233                 if (!msr_info->host_initiated &&
4234                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
4235                         return 1;
4236
4237                 /* The STIBP bit doesn't fault even if it's not advertised */
4238                 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
4239                         return 1;
4240
4241                 vmx->spec_ctrl = data;
4242
4243                 if (!data)
4244                         break;
4245
4246                 /*
4247                  * For non-nested:
4248                  * When it's written (to non-zero) for the first time, pass
4249                  * it through.
4250                  *
4251                  * For nested:
4252                  * The handling of the MSR bitmap for L2 guests is done in
4253                  * nested_vmx_merge_msr_bitmap. We should not touch the
4254                  * vmcs02.msr_bitmap here since it gets completely overwritten
4255                  * in the merging. We update the vmcs01 here for L1 as well
4256                  * since it will end up touching the MSR anyway now.
4257                  */
4258                 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
4259                                               MSR_IA32_SPEC_CTRL,
4260                                               MSR_TYPE_RW);
4261                 break;
4262         case MSR_IA32_PRED_CMD:
4263                 if (!msr_info->host_initiated &&
4264                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
4265                         return 1;
4266
4267                 if (data & ~PRED_CMD_IBPB)
4268                         return 1;
4269
4270                 if (!data)
4271                         break;
4272
4273                 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
4274
4275                 /*
4276                  * For non-nested:
4277                  * When it's written (to non-zero) for the first time, pass
4278                  * it through.
4279                  *
4280                  * For nested:
4281                  * The handling of the MSR bitmap for L2 guests is done in
4282                  * nested_vmx_merge_msr_bitmap. We should not touch the
4283                  * vmcs02.msr_bitmap here since it gets completely overwritten
4284                  * in the merging.
4285                  */
4286                 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
4287                                               MSR_TYPE_W);
4288                 break;
4289         case MSR_IA32_ARCH_CAPABILITIES:
4290                 if (!msr_info->host_initiated)
4291                         return 1;
4292                 vmx->arch_capabilities = data;
4293                 break;
4294         case MSR_IA32_CR_PAT:
4295                 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
4296                         if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
4297                                 return 1;
4298                         vmcs_write64(GUEST_IA32_PAT, data);
4299                         vcpu->arch.pat = data;
4300                         break;
4301                 }
4302                 ret = kvm_set_msr_common(vcpu, msr_info);
4303                 break;
4304         case MSR_IA32_TSC_ADJUST:
4305                 ret = kvm_set_msr_common(vcpu, msr_info);
4306                 break;
4307         case MSR_IA32_MCG_EXT_CTL:
4308                 if ((!msr_info->host_initiated &&
4309                      !(to_vmx(vcpu)->msr_ia32_feature_control &
4310                        FEATURE_CONTROL_LMCE)) ||
4311                     (data & ~MCG_EXT_CTL_LMCE_EN))
4312                         return 1;
4313                 vcpu->arch.mcg_ext_ctl = data;
4314                 break;
4315         case MSR_IA32_FEATURE_CONTROL:
4316                 if (!vmx_feature_control_msr_valid(vcpu, data) ||
4317                     (to_vmx(vcpu)->msr_ia32_feature_control &
4318                      FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
4319                         return 1;
4320                 vmx->msr_ia32_feature_control = data;
4321                 if (msr_info->host_initiated && data == 0)
4322                         vmx_leave_nested(vcpu);
4323                 break;
4324         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4325                 if (!msr_info->host_initiated)
4326                         return 1; /* they are read-only */
4327                 if (!nested_vmx_allowed(vcpu))
4328                         return 1;
4329                 return vmx_set_vmx_msr(vcpu, msr_index, data);
4330         case MSR_IA32_XSS:
4331                 if (!vmx_xsaves_supported())
4332                         return 1;
4333                 /*
4334                  * The only supported bit as of Skylake is bit 8, but
4335                  * it is not supported on KVM.
4336                  */
4337                 if (data != 0)
4338                         return 1;
4339                 vcpu->arch.ia32_xss = data;
4340                 if (vcpu->arch.ia32_xss != host_xss)
4341                         add_atomic_switch_msr(vmx, MSR_IA32_XSS,
4342                                 vcpu->arch.ia32_xss, host_xss, false);
4343                 else
4344                         clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
4345                 break;
4346         case MSR_TSC_AUX:
4347                 if (!msr_info->host_initiated &&
4348                     !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
4349                         return 1;
4350                 /* Check reserved bit, higher 32 bits should be zero */
4351                 if ((data >> 32) != 0)
4352                         return 1;
4353                 /* Otherwise falls through */
4354         default:
4355                 msr = find_msr_entry(vmx, msr_index);
4356                 if (msr) {
4357                         u64 old_msr_data = msr->data;
4358                         msr->data = data;
4359                         if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
4360                                 preempt_disable();
4361                                 ret = kvm_set_shared_msr(msr->index, msr->data,
4362                                                          msr->mask);
4363                                 preempt_enable();
4364                                 if (ret)
4365                                         msr->data = old_msr_data;
4366                         }
4367                         break;
4368                 }
4369                 ret = kvm_set_msr_common(vcpu, msr_info);
4370         }
4371
4372         return ret;
4373 }
4374
4375 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
4376 {
4377         __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
4378         switch (reg) {
4379         case VCPU_REGS_RSP:
4380                 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
4381                 break;
4382         case VCPU_REGS_RIP:
4383                 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
4384                 break;
4385         case VCPU_EXREG_PDPTR:
4386                 if (enable_ept)
4387                         ept_save_pdptrs(vcpu);
4388                 break;
4389         default:
4390                 break;
4391         }
4392 }
4393
4394 static __init int cpu_has_kvm_support(void)
4395 {
4396         return cpu_has_vmx();
4397 }
4398
4399 static __init int vmx_disabled_by_bios(void)
4400 {
4401         u64 msr;
4402
4403         rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
4404         if (msr & FEATURE_CONTROL_LOCKED) {
4405                 /* launched w/ TXT and VMX disabled */
4406                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
4407                         && tboot_enabled())
4408                         return 1;
4409                 /* launched w/o TXT and VMX only enabled w/ TXT */
4410                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
4411                         && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
4412                         && !tboot_enabled()) {
4413                         printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
4414                                 "activate TXT before enabling KVM\n");
4415                         return 1;
4416                 }
4417                 /* launched w/o TXT and VMX disabled */
4418                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
4419                         && !tboot_enabled())
4420                         return 1;
4421         }
4422
4423         return 0;
4424 }
4425
4426 static void kvm_cpu_vmxon(u64 addr)
4427 {
4428         cr4_set_bits(X86_CR4_VMXE);
4429         intel_pt_handle_vmx(1);
4430
4431         asm volatile ("vmxon %0" : : "m"(addr));
4432 }
4433
4434 static int hardware_enable(void)
4435 {
4436         int cpu = raw_smp_processor_id();
4437         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
4438         u64 old, test_bits;
4439
4440         if (cr4_read_shadow() & X86_CR4_VMXE)
4441                 return -EBUSY;
4442
4443         /*
4444          * This can happen if we hot-added a CPU but failed to allocate
4445          * VP assist page for it.
4446          */
4447         if (static_branch_unlikely(&enable_evmcs) &&
4448             !hv_get_vp_assist_page(cpu))
4449                 return -EFAULT;
4450
4451         INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
4452         INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
4453         spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
4454
4455         /*
4456          * Now we can enable the vmclear operation in kdump
4457          * since the loaded_vmcss_on_cpu list on this cpu
4458          * has been initialized.
4459          *
4460          * Though the cpu is not in VMX operation now, there
4461          * is no problem to enable the vmclear operation
4462          * for the loaded_vmcss_on_cpu list is empty!
4463          */
4464         crash_enable_local_vmclear(cpu);
4465
4466         rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
4467
4468         test_bits = FEATURE_CONTROL_LOCKED;
4469         test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
4470         if (tboot_enabled())
4471                 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
4472
4473         if ((old & test_bits) != test_bits) {
4474                 /* enable and lock */
4475                 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
4476         }
4477         kvm_cpu_vmxon(phys_addr);
4478         if (enable_ept)
4479                 ept_sync_global();
4480
4481         return 0;
4482 }
4483
4484 static void vmclear_local_loaded_vmcss(void)
4485 {
4486         int cpu = raw_smp_processor_id();
4487         struct loaded_vmcs *v, *n;
4488
4489         list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
4490                                  loaded_vmcss_on_cpu_link)
4491                 __loaded_vmcs_clear(v);
4492 }
4493
4494
4495 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
4496  * tricks.
4497  */
4498 static void kvm_cpu_vmxoff(void)
4499 {
4500         asm volatile (__ex("vmxoff"));
4501
4502         intel_pt_handle_vmx(0);
4503         cr4_clear_bits(X86_CR4_VMXE);
4504 }
4505
4506 static void hardware_disable(void)
4507 {
4508         vmclear_local_loaded_vmcss();
4509         kvm_cpu_vmxoff();
4510 }
4511
4512 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
4513                                       u32 msr, u32 *result)
4514 {
4515         u32 vmx_msr_low, vmx_msr_high;
4516         u32 ctl = ctl_min | ctl_opt;
4517
4518         rdmsr(msr, vmx_msr_low, vmx_msr_high);
4519
4520         ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
4521         ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
4522
4523         /* Ensure minimum (required) set of control bits are supported. */
4524         if (ctl_min & ~ctl)
4525                 return -EIO;
4526
4527         *result = ctl;
4528         return 0;
4529 }
4530
4531 static __init bool allow_1_setting(u32 msr, u32 ctl)
4532 {
4533         u32 vmx_msr_low, vmx_msr_high;
4534
4535         rdmsr(msr, vmx_msr_low, vmx_msr_high);
4536         return vmx_msr_high & ctl;
4537 }
4538
4539 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
4540 {
4541         u32 vmx_msr_low, vmx_msr_high;
4542         u32 min, opt, min2, opt2;
4543         u32 _pin_based_exec_control = 0;
4544         u32 _cpu_based_exec_control = 0;
4545         u32 _cpu_based_2nd_exec_control = 0;
4546         u32 _vmexit_control = 0;
4547         u32 _vmentry_control = 0;
4548
4549         memset(vmcs_conf, 0, sizeof(*vmcs_conf));
4550         min = CPU_BASED_HLT_EXITING |
4551 #ifdef CONFIG_X86_64
4552               CPU_BASED_CR8_LOAD_EXITING |
4553               CPU_BASED_CR8_STORE_EXITING |
4554 #endif
4555               CPU_BASED_CR3_LOAD_EXITING |
4556               CPU_BASED_CR3_STORE_EXITING |
4557               CPU_BASED_UNCOND_IO_EXITING |
4558               CPU_BASED_MOV_DR_EXITING |
4559               CPU_BASED_USE_TSC_OFFSETING |
4560               CPU_BASED_MWAIT_EXITING |
4561               CPU_BASED_MONITOR_EXITING |
4562               CPU_BASED_INVLPG_EXITING |
4563               CPU_BASED_RDPMC_EXITING;
4564
4565         opt = CPU_BASED_TPR_SHADOW |
4566               CPU_BASED_USE_MSR_BITMAPS |
4567               CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
4568         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
4569                                 &_cpu_based_exec_control) < 0)
4570                 return -EIO;
4571 #ifdef CONFIG_X86_64
4572         if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
4573                 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
4574                                            ~CPU_BASED_CR8_STORE_EXITING;
4575 #endif
4576         if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
4577                 min2 = 0;
4578                 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
4579                         SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
4580                         SECONDARY_EXEC_WBINVD_EXITING |
4581                         SECONDARY_EXEC_ENABLE_VPID |
4582                         SECONDARY_EXEC_ENABLE_EPT |
4583                         SECONDARY_EXEC_UNRESTRICTED_GUEST |
4584                         SECONDARY_EXEC_PAUSE_LOOP_EXITING |
4585                         SECONDARY_EXEC_DESC |
4586                         SECONDARY_EXEC_RDTSCP |
4587                         SECONDARY_EXEC_ENABLE_INVPCID |
4588                         SECONDARY_EXEC_APIC_REGISTER_VIRT |
4589                         SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
4590                         SECONDARY_EXEC_SHADOW_VMCS |
4591                         SECONDARY_EXEC_XSAVES |
4592                         SECONDARY_EXEC_RDSEED_EXITING |
4593                         SECONDARY_EXEC_RDRAND_EXITING |
4594                         SECONDARY_EXEC_ENABLE_PML |
4595                         SECONDARY_EXEC_TSC_SCALING |
4596                         SECONDARY_EXEC_ENABLE_VMFUNC |
4597                         SECONDARY_EXEC_ENCLS_EXITING;
4598                 if (adjust_vmx_controls(min2, opt2,
4599                                         MSR_IA32_VMX_PROCBASED_CTLS2,
4600                                         &_cpu_based_2nd_exec_control) < 0)
4601                         return -EIO;
4602         }
4603 #ifndef CONFIG_X86_64
4604         if (!(_cpu_based_2nd_exec_control &
4605                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
4606                 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
4607 #endif
4608
4609         if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
4610                 _cpu_based_2nd_exec_control &= ~(
4611                                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4612                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
4613                                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4614
4615         rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
4616                 &vmx_capability.ept, &vmx_capability.vpid);
4617
4618         if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
4619                 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
4620                    enabled */
4621                 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
4622                                              CPU_BASED_CR3_STORE_EXITING |
4623                                              CPU_BASED_INVLPG_EXITING);
4624         } else if (vmx_capability.ept) {
4625                 vmx_capability.ept = 0;
4626                 pr_warn_once("EPT CAP should not exist if not support "
4627                                 "1-setting enable EPT VM-execution control\n");
4628         }
4629         if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
4630                 vmx_capability.vpid) {
4631                 vmx_capability.vpid = 0;
4632                 pr_warn_once("VPID CAP should not exist if not support "
4633                                 "1-setting enable VPID VM-execution control\n");
4634         }
4635
4636         min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
4637 #ifdef CONFIG_X86_64
4638         min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
4639 #endif
4640         opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
4641                 VM_EXIT_CLEAR_BNDCFGS;
4642         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
4643                                 &_vmexit_control) < 0)
4644                 return -EIO;
4645
4646         min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
4647         opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
4648                  PIN_BASED_VMX_PREEMPTION_TIMER;
4649         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
4650                                 &_pin_based_exec_control) < 0)
4651                 return -EIO;
4652
4653         if (cpu_has_broken_vmx_preemption_timer())
4654                 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4655         if (!(_cpu_based_2nd_exec_control &
4656                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
4657                 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
4658
4659         min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
4660         opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
4661         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
4662                                 &_vmentry_control) < 0)
4663                 return -EIO;
4664
4665         rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
4666
4667         /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
4668         if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
4669                 return -EIO;
4670
4671 #ifdef CONFIG_X86_64
4672         /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
4673         if (vmx_msr_high & (1u<<16))
4674                 return -EIO;
4675 #endif
4676
4677         /* Require Write-Back (WB) memory type for VMCS accesses. */
4678         if (((vmx_msr_high >> 18) & 15) != 6)
4679                 return -EIO;
4680
4681         vmcs_conf->size = vmx_msr_high & 0x1fff;
4682         vmcs_conf->order = get_order(vmcs_conf->size);
4683         vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
4684
4685         vmcs_conf->revision_id = vmx_msr_low;
4686
4687         vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
4688         vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
4689         vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
4690         vmcs_conf->vmexit_ctrl         = _vmexit_control;
4691         vmcs_conf->vmentry_ctrl        = _vmentry_control;
4692
4693         if (static_branch_unlikely(&enable_evmcs))
4694                 evmcs_sanitize_exec_ctrls(vmcs_conf);
4695
4696         cpu_has_load_ia32_efer =
4697                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
4698                                 VM_ENTRY_LOAD_IA32_EFER)
4699                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
4700                                    VM_EXIT_LOAD_IA32_EFER);
4701
4702         cpu_has_load_perf_global_ctrl =
4703                 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
4704                                 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
4705                 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
4706                                    VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
4707
4708         /*
4709          * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
4710          * but due to errata below it can't be used. Workaround is to use
4711          * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
4712          *
4713          * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
4714          *
4715          * AAK155             (model 26)
4716          * AAP115             (model 30)
4717          * AAT100             (model 37)
4718          * BC86,AAY89,BD102   (model 44)
4719          * BA97               (model 46)
4720          *
4721          */
4722         if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
4723                 switch (boot_cpu_data.x86_model) {
4724                 case 26:
4725                 case 30:
4726                 case 37:
4727                 case 44:
4728                 case 46:
4729                         cpu_has_load_perf_global_ctrl = false;
4730                         printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
4731                                         "does not work properly. Using workaround\n");
4732                         break;
4733                 default:
4734                         break;
4735                 }
4736         }
4737
4738         if (boot_cpu_has(X86_FEATURE_XSAVES))
4739                 rdmsrl(MSR_IA32_XSS, host_xss);
4740
4741         return 0;
4742 }
4743
4744 static struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu)
4745 {
4746         int node = cpu_to_node(cpu);
4747         struct page *pages;
4748         struct vmcs *vmcs;
4749
4750         pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
4751         if (!pages)
4752                 return NULL;
4753         vmcs = page_address(pages);
4754         memset(vmcs, 0, vmcs_config.size);
4755
4756         /* KVM supports Enlightened VMCS v1 only */
4757         if (static_branch_unlikely(&enable_evmcs))
4758                 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
4759         else
4760                 vmcs->hdr.revision_id = vmcs_config.revision_id;
4761
4762         if (shadow)
4763                 vmcs->hdr.shadow_vmcs = 1;
4764         return vmcs;
4765 }
4766
4767 static void free_vmcs(struct vmcs *vmcs)
4768 {
4769         free_pages((unsigned long)vmcs, vmcs_config.order);
4770 }
4771
4772 /*
4773  * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
4774  */
4775 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
4776 {
4777         if (!loaded_vmcs->vmcs)
4778                 return;
4779         loaded_vmcs_clear(loaded_vmcs);
4780         free_vmcs(loaded_vmcs->vmcs);
4781         loaded_vmcs->vmcs = NULL;
4782         if (loaded_vmcs->msr_bitmap)
4783                 free_page((unsigned long)loaded_vmcs->msr_bitmap);
4784         WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
4785 }
4786
4787 static struct vmcs *alloc_vmcs(bool shadow)
4788 {
4789         return alloc_vmcs_cpu(shadow, raw_smp_processor_id());
4790 }
4791
4792 static int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
4793 {
4794         loaded_vmcs->vmcs = alloc_vmcs(false);
4795         if (!loaded_vmcs->vmcs)
4796                 return -ENOMEM;
4797
4798         loaded_vmcs->shadow_vmcs = NULL;
4799         loaded_vmcs_init(loaded_vmcs);
4800
4801         if (cpu_has_vmx_msr_bitmap()) {
4802                 loaded_vmcs->msr_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
4803                 if (!loaded_vmcs->msr_bitmap)
4804                         goto out_vmcs;
4805                 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
4806
4807                 if (IS_ENABLED(CONFIG_HYPERV) &&
4808                     static_branch_unlikely(&enable_evmcs) &&
4809                     (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
4810                         struct hv_enlightened_vmcs *evmcs =
4811                                 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
4812
4813                         evmcs->hv_enlightenments_control.msr_bitmap = 1;
4814                 }
4815         }
4816
4817         memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
4818
4819         return 0;
4820
4821 out_vmcs:
4822         free_loaded_vmcs(loaded_vmcs);
4823         return -ENOMEM;
4824 }
4825
4826 static void free_kvm_area(void)
4827 {
4828         int cpu;
4829
4830         for_each_possible_cpu(cpu) {
4831                 free_vmcs(per_cpu(vmxarea, cpu));
4832                 per_cpu(vmxarea, cpu) = NULL;
4833         }
4834 }
4835
4836 enum vmcs_field_width {
4837         VMCS_FIELD_WIDTH_U16 = 0,
4838         VMCS_FIELD_WIDTH_U64 = 1,
4839         VMCS_FIELD_WIDTH_U32 = 2,
4840         VMCS_FIELD_WIDTH_NATURAL_WIDTH = 3
4841 };
4842
4843 static inline int vmcs_field_width(unsigned long field)
4844 {
4845         if (0x1 & field)        /* the *_HIGH fields are all 32 bit */
4846                 return VMCS_FIELD_WIDTH_U32;
4847         return (field >> 13) & 0x3 ;
4848 }
4849
4850 static inline int vmcs_field_readonly(unsigned long field)
4851 {
4852         return (((field >> 10) & 0x3) == 1);
4853 }
4854
4855 static void init_vmcs_shadow_fields(void)
4856 {
4857         int i, j;
4858
4859         for (i = j = 0; i < max_shadow_read_only_fields; i++) {
4860                 u16 field = shadow_read_only_fields[i];
4861                 if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
4862                     (i + 1 == max_shadow_read_only_fields ||
4863                      shadow_read_only_fields[i + 1] != field + 1))
4864                         pr_err("Missing field from shadow_read_only_field %x\n",
4865                                field + 1);
4866
4867                 clear_bit(field, vmx_vmread_bitmap);
4868 #ifdef CONFIG_X86_64
4869                 if (field & 1)
4870                         continue;
4871 #endif
4872                 if (j < i)
4873                         shadow_read_only_fields[j] = field;
4874                 j++;
4875         }
4876         max_shadow_read_only_fields = j;
4877
4878         for (i = j = 0; i < max_shadow_read_write_fields; i++) {
4879                 u16 field = shadow_read_write_fields[i];
4880                 if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
4881                     (i + 1 == max_shadow_read_write_fields ||
4882                      shadow_read_write_fields[i + 1] != field + 1))
4883                         pr_err("Missing field from shadow_read_write_field %x\n",
4884                                field + 1);
4885
4886                 /*
4887                  * PML and the preemption timer can be emulated, but the
4888                  * processor cannot vmwrite to fields that don't exist
4889                  * on bare metal.
4890                  */
4891                 switch (field) {
4892                 case GUEST_PML_INDEX:
4893                         if (!cpu_has_vmx_pml())
4894                                 continue;
4895                         break;
4896                 case VMX_PREEMPTION_TIMER_VALUE:
4897                         if (!cpu_has_vmx_preemption_timer())
4898                                 continue;
4899                         break;
4900                 case GUEST_INTR_STATUS:
4901                         if (!cpu_has_vmx_apicv())
4902                                 continue;
4903                         break;
4904                 default:
4905                         break;
4906                 }
4907
4908                 clear_bit(field, vmx_vmwrite_bitmap);
4909                 clear_bit(field, vmx_vmread_bitmap);
4910 #ifdef CONFIG_X86_64
4911                 if (field & 1)
4912                         continue;
4913 #endif
4914                 if (j < i)
4915                         shadow_read_write_fields[j] = field;
4916                 j++;
4917         }
4918         max_shadow_read_write_fields = j;
4919 }
4920
4921 static __init int alloc_kvm_area(void)
4922 {
4923         int cpu;
4924
4925         for_each_possible_cpu(cpu) {
4926                 struct vmcs *vmcs;
4927
4928                 vmcs = alloc_vmcs_cpu(false, cpu);
4929                 if (!vmcs) {
4930                         free_kvm_area();
4931                         return -ENOMEM;
4932                 }
4933
4934                 /*
4935                  * When eVMCS is enabled, alloc_vmcs_cpu() sets
4936                  * vmcs->revision_id to KVM_EVMCS_VERSION instead of
4937                  * revision_id reported by MSR_IA32_VMX_BASIC.
4938                  *
4939                  * However, even though not explictly documented by
4940                  * TLFS, VMXArea passed as VMXON argument should
4941                  * still be marked with revision_id reported by
4942                  * physical CPU.
4943                  */
4944                 if (static_branch_unlikely(&enable_evmcs))
4945                         vmcs->hdr.revision_id = vmcs_config.revision_id;
4946
4947                 per_cpu(vmxarea, cpu) = vmcs;
4948         }
4949         return 0;
4950 }
4951
4952 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
4953                 struct kvm_segment *save)
4954 {
4955         if (!emulate_invalid_guest_state) {
4956                 /*
4957                  * CS and SS RPL should be equal during guest entry according
4958                  * to VMX spec, but in reality it is not always so. Since vcpu
4959                  * is in the middle of the transition from real mode to
4960                  * protected mode it is safe to assume that RPL 0 is a good
4961                  * default value.
4962                  */
4963                 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
4964                         save->selector &= ~SEGMENT_RPL_MASK;
4965                 save->dpl = save->selector & SEGMENT_RPL_MASK;
4966                 save->s = 1;
4967         }
4968         vmx_set_segment(vcpu, save, seg);
4969 }
4970
4971 static void enter_pmode(struct kvm_vcpu *vcpu)
4972 {
4973         unsigned long flags;
4974         struct vcpu_vmx *vmx = to_vmx(vcpu);
4975
4976         /*
4977          * Update real mode segment cache. It may be not up-to-date if sement
4978          * register was written while vcpu was in a guest mode.
4979          */
4980         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4981         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4982         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4983         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4984         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4985         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4986
4987         vmx->rmode.vm86_active = 0;
4988
4989         vmx_segment_cache_clear(vmx);
4990
4991         vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4992
4993         flags = vmcs_readl(GUEST_RFLAGS);
4994         flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
4995         flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
4996         vmcs_writel(GUEST_RFLAGS, flags);
4997
4998         vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
4999                         (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
5000
5001         update_exception_bitmap(vcpu);
5002
5003         fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
5004         fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
5005         fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
5006         fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
5007         fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
5008         fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
5009 }
5010
5011 static void fix_rmode_seg(int seg, struct kvm_segment *save)
5012 {
5013         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
5014         struct kvm_segment var = *save;
5015
5016         var.dpl = 0x3;
5017         if (seg == VCPU_SREG_CS)
5018                 var.type = 0x3;
5019
5020         if (!emulate_invalid_guest_state) {
5021                 var.selector = var.base >> 4;
5022                 var.base = var.base & 0xffff0;
5023                 var.limit = 0xffff;
5024                 var.g = 0;
5025                 var.db = 0;
5026                 var.present = 1;
5027                 var.s = 1;
5028                 var.l = 0;
5029                 var.unusable = 0;
5030                 var.type = 0x3;
5031                 var.avl = 0;
5032                 if (save->base & 0xf)
5033                         printk_once(KERN_WARNING "kvm: segment base is not "
5034                                         "paragraph aligned when entering "
5035                                         "protected mode (seg=%d)", seg);
5036         }
5037
5038         vmcs_write16(sf->selector, var.selector);
5039         vmcs_writel(sf->base, var.base);
5040         vmcs_write32(sf->limit, var.limit);
5041         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
5042 }
5043
5044 static void enter_rmode(struct kvm_vcpu *vcpu)
5045 {
5046         unsigned long flags;
5047         struct vcpu_vmx *vmx = to_vmx(vcpu);
5048         struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
5049
5050         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
5051         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
5052         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
5053         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
5054         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
5055         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
5056         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
5057
5058         vmx->rmode.vm86_active = 1;
5059
5060         /*
5061          * Very old userspace does not call KVM_SET_TSS_ADDR before entering
5062          * vcpu. Warn the user that an update is overdue.
5063          */
5064         if (!kvm_vmx->tss_addr)
5065                 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
5066                              "called before entering vcpu\n");
5067
5068         vmx_segment_cache_clear(vmx);
5069
5070         vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
5071         vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
5072         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
5073
5074         flags = vmcs_readl(GUEST_RFLAGS);
5075         vmx->rmode.save_rflags = flags;
5076
5077         flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
5078
5079         vmcs_writel(GUEST_RFLAGS, flags);
5080         vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
5081         update_exception_bitmap(vcpu);
5082
5083         fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
5084         fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
5085         fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
5086         fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
5087         fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
5088         fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
5089
5090         kvm_mmu_reset_context(vcpu);
5091 }
5092
5093 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
5094 {
5095         struct vcpu_vmx *vmx = to_vmx(vcpu);
5096         struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
5097
5098         if (!msr)
5099                 return;
5100
5101         vcpu->arch.efer = efer;
5102         if (efer & EFER_LMA) {
5103                 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
5104                 msr->data = efer;
5105         } else {
5106                 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
5107
5108                 msr->data = efer & ~EFER_LME;
5109         }
5110         setup_msrs(vmx);
5111 }
5112
5113 #ifdef CONFIG_X86_64
5114
5115 static void enter_lmode(struct kvm_vcpu *vcpu)
5116 {
5117         u32 guest_tr_ar;
5118
5119         vmx_segment_cache_clear(to_vmx(vcpu));
5120
5121         guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
5122         if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
5123                 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
5124                                      __func__);
5125                 vmcs_write32(GUEST_TR_AR_BYTES,
5126                              (guest_tr_ar & ~VMX_AR_TYPE_MASK)
5127                              | VMX_AR_TYPE_BUSY_64_TSS);
5128         }
5129         vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
5130 }
5131
5132 static void exit_lmode(struct kvm_vcpu *vcpu)
5133 {
5134         vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
5135         vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
5136 }
5137
5138 #endif
5139
5140 static inline void __vmx_flush_tlb(struct kvm_vcpu *vcpu, int vpid,
5141                                 bool invalidate_gpa)
5142 {
5143         if (enable_ept && (invalidate_gpa || !enable_vpid)) {
5144                 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
5145                         return;
5146                 ept_sync_context(construct_eptp(vcpu,
5147                                                 vcpu->arch.mmu->root_hpa));
5148         } else {
5149                 vpid_sync_context(vpid);
5150         }
5151 }
5152
5153 static void vmx_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
5154 {
5155         __vmx_flush_tlb(vcpu, to_vmx(vcpu)->vpid, invalidate_gpa);
5156 }
5157
5158 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
5159 {
5160         int vpid = to_vmx(vcpu)->vpid;
5161
5162         if (!vpid_sync_vcpu_addr(vpid, addr))
5163                 vpid_sync_context(vpid);
5164
5165         /*
5166          * If VPIDs are not supported or enabled, then the above is a no-op.
5167          * But we don't really need a TLB flush in that case anyway, because
5168          * each VM entry/exit includes an implicit flush when VPID is 0.
5169          */
5170 }
5171
5172 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
5173 {
5174         ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
5175
5176         vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
5177         vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
5178 }
5179
5180 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
5181 {
5182         if (enable_unrestricted_guest || (enable_ept && is_paging(vcpu)))
5183                 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
5184         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
5185 }
5186
5187 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
5188 {
5189         ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
5190
5191         vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
5192         vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
5193 }
5194
5195 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
5196 {
5197         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
5198
5199         if (!test_bit(VCPU_EXREG_PDPTR,
5200                       (unsigned long *)&vcpu->arch.regs_dirty))
5201                 return;
5202
5203         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
5204                 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
5205                 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
5206                 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
5207                 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
5208         }
5209 }
5210
5211 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
5212 {
5213         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
5214
5215         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
5216                 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
5217                 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
5218                 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
5219                 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
5220         }
5221
5222         __set_bit(VCPU_EXREG_PDPTR,
5223                   (unsigned long *)&vcpu->arch.regs_avail);
5224         __set_bit(VCPU_EXREG_PDPTR,
5225                   (unsigned long *)&vcpu->arch.regs_dirty);
5226 }
5227
5228 static bool nested_guest_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
5229 {
5230         u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr0_fixed0;
5231         u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr0_fixed1;
5232         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5233
5234         if (to_vmx(vcpu)->nested.msrs.secondary_ctls_high &
5235                 SECONDARY_EXEC_UNRESTRICTED_GUEST &&
5236             nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
5237                 fixed0 &= ~(X86_CR0_PE | X86_CR0_PG);
5238
5239         return fixed_bits_valid(val, fixed0, fixed1);
5240 }
5241
5242 static bool nested_host_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
5243 {
5244         u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr0_fixed0;
5245         u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr0_fixed1;
5246
5247         return fixed_bits_valid(val, fixed0, fixed1);
5248 }
5249
5250 static bool nested_cr4_valid(struct kvm_vcpu *vcpu, unsigned long val)
5251 {
5252         u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr4_fixed0;
5253         u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr4_fixed1;
5254
5255         return fixed_bits_valid(val, fixed0, fixed1);
5256 }
5257
5258 /* No difference in the restrictions on guest and host CR4 in VMX operation. */
5259 #define nested_guest_cr4_valid  nested_cr4_valid
5260 #define nested_host_cr4_valid   nested_cr4_valid
5261
5262 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
5263
5264 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
5265                                         unsigned long cr0,
5266                                         struct kvm_vcpu *vcpu)
5267 {
5268         if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
5269                 vmx_decache_cr3(vcpu);
5270         if (!(cr0 & X86_CR0_PG)) {
5271                 /* From paging/starting to nonpaging */
5272                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
5273                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
5274                              (CPU_BASED_CR3_LOAD_EXITING |
5275                               CPU_BASED_CR3_STORE_EXITING));
5276                 vcpu->arch.cr0 = cr0;
5277                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
5278         } else if (!is_paging(vcpu)) {
5279                 /* From nonpaging to paging */
5280                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
5281                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
5282                              ~(CPU_BASED_CR3_LOAD_EXITING |
5283                                CPU_BASED_CR3_STORE_EXITING));
5284                 vcpu->arch.cr0 = cr0;
5285                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
5286         }
5287
5288         if (!(cr0 & X86_CR0_WP))
5289                 *hw_cr0 &= ~X86_CR0_WP;
5290 }
5291
5292 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
5293 {
5294         struct vcpu_vmx *vmx = to_vmx(vcpu);
5295         unsigned long hw_cr0;
5296
5297         hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
5298         if (enable_unrestricted_guest)
5299                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
5300         else {
5301                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
5302
5303                 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
5304                         enter_pmode(vcpu);
5305
5306                 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
5307                         enter_rmode(vcpu);
5308         }
5309
5310 #ifdef CONFIG_X86_64
5311         if (vcpu->arch.efer & EFER_LME) {
5312                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
5313                         enter_lmode(vcpu);
5314                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
5315                         exit_lmode(vcpu);
5316         }
5317 #endif
5318
5319         if (enable_ept && !enable_unrestricted_guest)
5320                 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
5321
5322         vmcs_writel(CR0_READ_SHADOW, cr0);
5323         vmcs_writel(GUEST_CR0, hw_cr0);
5324         vcpu->arch.cr0 = cr0;
5325
5326         /* depends on vcpu->arch.cr0 to be set to a new value */
5327         vmx->emulation_required = emulation_required(vcpu);
5328 }
5329
5330 static int get_ept_level(struct kvm_vcpu *vcpu)
5331 {
5332         if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
5333                 return 5;
5334         return 4;
5335 }
5336
5337 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
5338 {
5339         u64 eptp = VMX_EPTP_MT_WB;
5340
5341         eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
5342
5343         if (enable_ept_ad_bits &&
5344             (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
5345                 eptp |= VMX_EPTP_AD_ENABLE_BIT;
5346         eptp |= (root_hpa & PAGE_MASK);
5347
5348         return eptp;
5349 }
5350
5351 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
5352 {
5353         struct kvm *kvm = vcpu->kvm;
5354         unsigned long guest_cr3;
5355         u64 eptp;
5356
5357         guest_cr3 = cr3;
5358         if (enable_ept) {
5359                 eptp = construct_eptp(vcpu, cr3);
5360                 vmcs_write64(EPT_POINTER, eptp);
5361
5362                 if (kvm_x86_ops->tlb_remote_flush) {
5363                         spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
5364                         to_vmx(vcpu)->ept_pointer = eptp;
5365                         to_kvm_vmx(kvm)->ept_pointers_match
5366                                 = EPT_POINTERS_CHECK;
5367                         spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
5368                 }
5369
5370                 if (enable_unrestricted_guest || is_paging(vcpu) ||
5371                     is_guest_mode(vcpu))
5372                         guest_cr3 = kvm_read_cr3(vcpu);
5373                 else
5374                         guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
5375                 ept_load_pdptrs(vcpu);
5376         }
5377
5378         vmcs_writel(GUEST_CR3, guest_cr3);
5379 }
5380
5381 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
5382 {
5383         /*
5384          * Pass through host's Machine Check Enable value to hw_cr4, which
5385          * is in force while we are in guest mode.  Do not let guests control
5386          * this bit, even if host CR4.MCE == 0.
5387          */
5388         unsigned long hw_cr4;
5389
5390         hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
5391         if (enable_unrestricted_guest)
5392                 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
5393         else if (to_vmx(vcpu)->rmode.vm86_active)
5394                 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
5395         else
5396                 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
5397
5398         if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
5399                 if (cr4 & X86_CR4_UMIP) {
5400                         vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
5401                                 SECONDARY_EXEC_DESC);
5402                         hw_cr4 &= ~X86_CR4_UMIP;
5403                 } else if (!is_guest_mode(vcpu) ||
5404                         !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC))
5405                         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
5406                                         SECONDARY_EXEC_DESC);
5407         }
5408
5409         if (cr4 & X86_CR4_VMXE) {
5410                 /*
5411                  * To use VMXON (and later other VMX instructions), a guest
5412                  * must first be able to turn on cr4.VMXE (see handle_vmon()).
5413                  * So basically the check on whether to allow nested VMX
5414                  * is here.  We operate under the default treatment of SMM,
5415                  * so VMX cannot be enabled under SMM.
5416                  */
5417                 if (!nested_vmx_allowed(vcpu) || is_smm(vcpu))
5418                         return 1;
5419         }
5420
5421         if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
5422                 return 1;
5423
5424         vcpu->arch.cr4 = cr4;
5425
5426         if (!enable_unrestricted_guest) {
5427                 if (enable_ept) {
5428                         if (!is_paging(vcpu)) {
5429                                 hw_cr4 &= ~X86_CR4_PAE;
5430                                 hw_cr4 |= X86_CR4_PSE;
5431                         } else if (!(cr4 & X86_CR4_PAE)) {
5432                                 hw_cr4 &= ~X86_CR4_PAE;
5433                         }
5434                 }
5435
5436                 /*
5437                  * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
5438                  * hardware.  To emulate this behavior, SMEP/SMAP/PKU needs
5439                  * to be manually disabled when guest switches to non-paging
5440                  * mode.
5441                  *
5442                  * If !enable_unrestricted_guest, the CPU is always running
5443                  * with CR0.PG=1 and CR4 needs to be modified.
5444                  * If enable_unrestricted_guest, the CPU automatically
5445                  * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
5446                  */
5447                 if (!is_paging(vcpu))
5448                         hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
5449         }
5450
5451         vmcs_writel(CR4_READ_SHADOW, cr4);
5452         vmcs_writel(GUEST_CR4, hw_cr4);
5453         return 0;
5454 }
5455
5456 static void vmx_get_segment(struct kvm_vcpu *vcpu,
5457                             struct kvm_segment *var, int seg)
5458 {
5459         struct vcpu_vmx *vmx = to_vmx(vcpu);
5460         u32 ar;
5461
5462         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
5463                 *var = vmx->rmode.segs[seg];
5464                 if (seg == VCPU_SREG_TR
5465                     || var->selector == vmx_read_guest_seg_selector(vmx, seg))
5466                         return;
5467                 var->base = vmx_read_guest_seg_base(vmx, seg);
5468                 var->selector = vmx_read_guest_seg_selector(vmx, seg);
5469                 return;
5470         }
5471         var->base = vmx_read_guest_seg_base(vmx, seg);
5472         var->limit = vmx_read_guest_seg_limit(vmx, seg);
5473         var->selector = vmx_read_guest_seg_selector(vmx, seg);
5474         ar = vmx_read_guest_seg_ar(vmx, seg);
5475         var->unusable = (ar >> 16) & 1;
5476         var->type = ar & 15;
5477         var->s = (ar >> 4) & 1;
5478         var->dpl = (ar >> 5) & 3;
5479         /*
5480          * Some userspaces do not preserve unusable property. Since usable
5481          * segment has to be present according to VMX spec we can use present
5482          * property to amend userspace bug by making unusable segment always
5483          * nonpresent. vmx_segment_access_rights() already marks nonpresent
5484          * segment as unusable.
5485          */
5486         var->present = !var->unusable;
5487         var->avl = (ar >> 12) & 1;
5488         var->l = (ar >> 13) & 1;
5489         var->db = (ar >> 14) & 1;
5490         var->g = (ar >> 15) & 1;
5491 }
5492
5493 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
5494 {
5495         struct kvm_segment s;
5496
5497         if (to_vmx(vcpu)->rmode.vm86_active) {
5498                 vmx_get_segment(vcpu, &s, seg);
5499                 return s.base;
5500         }
5501         return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
5502 }
5503
5504 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
5505 {
5506         struct vcpu_vmx *vmx = to_vmx(vcpu);
5507
5508         if (unlikely(vmx->rmode.vm86_active))
5509                 return 0;
5510         else {
5511                 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
5512                 return VMX_AR_DPL(ar);
5513         }
5514 }
5515
5516 static u32 vmx_segment_access_rights(struct kvm_segment *var)
5517 {
5518         u32 ar;
5519
5520         if (var->unusable || !var->present)
5521                 ar = 1 << 16;
5522         else {
5523                 ar = var->type & 15;
5524                 ar |= (var->s & 1) << 4;
5525                 ar |= (var->dpl & 3) << 5;
5526                 ar |= (var->present & 1) << 7;
5527                 ar |= (var->avl & 1) << 12;
5528                 ar |= (var->l & 1) << 13;
5529                 ar |= (var->db & 1) << 14;
5530                 ar |= (var->g & 1) << 15;
5531         }
5532
5533         return ar;
5534 }
5535
5536 static void vmx_set_segment(struct kvm_vcpu *vcpu,
5537                             struct kvm_segment *var, int seg)
5538 {
5539         struct vcpu_vmx *vmx = to_vmx(vcpu);
5540         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
5541
5542         vmx_segment_cache_clear(vmx);
5543
5544         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
5545                 vmx->rmode.segs[seg] = *var;
5546                 if (seg == VCPU_SREG_TR)
5547                         vmcs_write16(sf->selector, var->selector);
5548                 else if (var->s)
5549                         fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
5550                 goto out;
5551         }
5552
5553         vmcs_writel(sf->base, var->base);
5554         vmcs_write32(sf->limit, var->limit);
5555         vmcs_write16(sf->selector, var->selector);
5556
5557         /*
5558          *   Fix the "Accessed" bit in AR field of segment registers for older
5559          * qemu binaries.
5560          *   IA32 arch specifies that at the time of processor reset the
5561          * "Accessed" bit in the AR field of segment registers is 1. And qemu
5562          * is setting it to 0 in the userland code. This causes invalid guest
5563          * state vmexit when "unrestricted guest" mode is turned on.
5564          *    Fix for this setup issue in cpu_reset is being pushed in the qemu
5565          * tree. Newer qemu binaries with that qemu fix would not need this
5566          * kvm hack.
5567          */
5568         if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
5569                 var->type |= 0x1; /* Accessed */
5570
5571         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
5572
5573 out:
5574         vmx->emulation_required = emulation_required(vcpu);
5575 }
5576
5577 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
5578 {
5579         u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
5580
5581         *db = (ar >> 14) & 1;
5582         *l = (ar >> 13) & 1;
5583 }
5584
5585 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5586 {
5587         dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
5588         dt->address = vmcs_readl(GUEST_IDTR_BASE);
5589 }
5590
5591 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5592 {
5593         vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
5594         vmcs_writel(GUEST_IDTR_BASE, dt->address);
5595 }
5596
5597 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5598 {
5599         dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
5600         dt->address = vmcs_readl(GUEST_GDTR_BASE);
5601 }
5602
5603 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5604 {
5605         vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
5606         vmcs_writel(GUEST_GDTR_BASE, dt->address);
5607 }
5608
5609 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
5610 {
5611         struct kvm_segment var;
5612         u32 ar;
5613
5614         vmx_get_segment(vcpu, &var, seg);
5615         var.dpl = 0x3;
5616         if (seg == VCPU_SREG_CS)
5617                 var.type = 0x3;
5618         ar = vmx_segment_access_rights(&var);
5619
5620         if (var.base != (var.selector << 4))
5621                 return false;
5622         if (var.limit != 0xffff)
5623                 return false;
5624         if (ar != 0xf3)
5625                 return false;
5626
5627         return true;
5628 }
5629
5630 static bool code_segment_valid(struct kvm_vcpu *vcpu)
5631 {
5632         struct kvm_segment cs;
5633         unsigned int cs_rpl;
5634
5635         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5636         cs_rpl = cs.selector & SEGMENT_RPL_MASK;
5637
5638         if (cs.unusable)
5639                 return false;
5640         if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
5641                 return false;
5642         if (!cs.s)
5643                 return false;
5644         if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
5645                 if (cs.dpl > cs_rpl)
5646                         return false;
5647         } else {
5648                 if (cs.dpl != cs_rpl)
5649                         return false;
5650         }
5651         if (!cs.present)
5652                 return false;
5653
5654         /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
5655         return true;
5656 }
5657
5658 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
5659 {
5660         struct kvm_segment ss;
5661         unsigned int ss_rpl;
5662
5663         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
5664         ss_rpl = ss.selector & SEGMENT_RPL_MASK;
5665
5666         if (ss.unusable)
5667                 return true;
5668         if (ss.type != 3 && ss.type != 7)
5669                 return false;
5670         if (!ss.s)
5671                 return false;
5672         if (ss.dpl != ss_rpl) /* DPL != RPL */
5673                 return false;
5674         if (!ss.present)
5675                 return false;
5676
5677         return true;
5678 }
5679
5680 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
5681 {
5682         struct kvm_segment var;
5683         unsigned int rpl;
5684
5685         vmx_get_segment(vcpu, &var, seg);
5686         rpl = var.selector & SEGMENT_RPL_MASK;
5687
5688         if (var.unusable)
5689                 return true;
5690         if (!var.s)
5691                 return false;
5692         if (!var.present)
5693                 return false;
5694         if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
5695                 if (var.dpl < rpl) /* DPL < RPL */
5696                         return false;
5697         }
5698
5699         /* TODO: Add other members to kvm_segment_field to allow checking for other access
5700          * rights flags
5701          */
5702         return true;
5703 }
5704
5705 static bool tr_valid(struct kvm_vcpu *vcpu)
5706 {
5707         struct kvm_segment tr;
5708
5709         vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
5710
5711         if (tr.unusable)
5712                 return false;
5713         if (tr.selector & SEGMENT_TI_MASK)      /* TI = 1 */
5714                 return false;
5715         if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
5716                 return false;
5717         if (!tr.present)
5718                 return false;
5719
5720         return true;
5721 }
5722
5723 static bool ldtr_valid(struct kvm_vcpu *vcpu)
5724 {
5725         struct kvm_segment ldtr;
5726
5727         vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
5728
5729         if (ldtr.unusable)
5730                 return true;
5731         if (ldtr.selector & SEGMENT_TI_MASK)    /* TI = 1 */
5732                 return false;
5733         if (ldtr.type != 2)
5734                 return false;
5735         if (!ldtr.present)
5736                 return false;
5737
5738         return true;
5739 }
5740
5741 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
5742 {
5743         struct kvm_segment cs, ss;
5744
5745         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5746         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
5747
5748         return ((cs.selector & SEGMENT_RPL_MASK) ==
5749                  (ss.selector & SEGMENT_RPL_MASK));
5750 }
5751
5752 /*
5753  * Check if guest state is valid. Returns true if valid, false if
5754  * not.
5755  * We assume that registers are always usable
5756  */
5757 static bool guest_state_valid(struct kvm_vcpu *vcpu)
5758 {
5759         if (enable_unrestricted_guest)
5760                 return true;
5761
5762         /* real mode guest state checks */
5763         if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
5764                 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
5765                         return false;
5766                 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
5767                         return false;
5768                 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
5769                         return false;
5770                 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
5771                         return false;
5772                 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
5773                         return false;
5774                 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
5775                         return false;
5776         } else {
5777         /* protected mode guest state checks */
5778                 if (!cs_ss_rpl_check(vcpu))
5779                         return false;
5780                 if (!code_segment_valid(vcpu))
5781                         return false;
5782                 if (!stack_segment_valid(vcpu))
5783                         return false;
5784                 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
5785                         return false;
5786                 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
5787                         return false;
5788                 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
5789                         return false;
5790                 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
5791                         return false;
5792                 if (!tr_valid(vcpu))
5793                         return false;
5794                 if (!ldtr_valid(vcpu))
5795                         return false;
5796         }
5797         /* TODO:
5798          * - Add checks on RIP
5799          * - Add checks on RFLAGS
5800          */
5801
5802         return true;
5803 }
5804
5805 static bool page_address_valid(struct kvm_vcpu *vcpu, gpa_t gpa)
5806 {
5807         return PAGE_ALIGNED(gpa) && !(gpa >> cpuid_maxphyaddr(vcpu));
5808 }
5809
5810 static int init_rmode_tss(struct kvm *kvm)
5811 {
5812         gfn_t fn;
5813         u16 data = 0;
5814         int idx, r;
5815
5816         idx = srcu_read_lock(&kvm->srcu);
5817         fn = to_kvm_vmx(kvm)->tss_addr >> PAGE_SHIFT;
5818         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
5819         if (r < 0)
5820                 goto out;
5821         data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
5822         r = kvm_write_guest_page(kvm, fn++, &data,
5823                         TSS_IOPB_BASE_OFFSET, sizeof(u16));
5824         if (r < 0)
5825                 goto out;
5826         r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
5827         if (r < 0)
5828                 goto out;
5829         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
5830         if (r < 0)
5831                 goto out;
5832         data = ~0;
5833         r = kvm_write_guest_page(kvm, fn, &data,
5834                                  RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
5835                                  sizeof(u8));
5836 out:
5837         srcu_read_unlock(&kvm->srcu, idx);
5838         return r;
5839 }
5840
5841 static int init_rmode_identity_map(struct kvm *kvm)
5842 {
5843         struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
5844         int i, idx, r = 0;
5845         kvm_pfn_t identity_map_pfn;
5846         u32 tmp;
5847
5848         /* Protect kvm_vmx->ept_identity_pagetable_done. */
5849         mutex_lock(&kvm->slots_lock);
5850
5851         if (likely(kvm_vmx->ept_identity_pagetable_done))
5852                 goto out2;
5853
5854         if (!kvm_vmx->ept_identity_map_addr)
5855                 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
5856         identity_map_pfn = kvm_vmx->ept_identity_map_addr >> PAGE_SHIFT;
5857
5858         r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
5859                                     kvm_vmx->ept_identity_map_addr, PAGE_SIZE);
5860         if (r < 0)
5861                 goto out2;
5862
5863         idx = srcu_read_lock(&kvm->srcu);
5864         r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
5865         if (r < 0)
5866                 goto out;
5867         /* Set up identity-mapping pagetable for EPT in real mode */
5868         for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
5869                 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
5870                         _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
5871                 r = kvm_write_guest_page(kvm, identity_map_pfn,
5872                                 &tmp, i * sizeof(tmp), sizeof(tmp));
5873                 if (r < 0)
5874                         goto out;
5875         }
5876         kvm_vmx->ept_identity_pagetable_done = true;
5877
5878 out:
5879         srcu_read_unlock(&kvm->srcu, idx);
5880
5881 out2:
5882         mutex_unlock(&kvm->slots_lock);
5883         return r;
5884 }
5885
5886 static void seg_setup(int seg)
5887 {
5888         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
5889         unsigned int ar;
5890
5891         vmcs_write16(sf->selector, 0);
5892         vmcs_writel(sf->base, 0);
5893         vmcs_write32(sf->limit, 0xffff);
5894         ar = 0x93;
5895         if (seg == VCPU_SREG_CS)
5896                 ar |= 0x08; /* code segment */
5897
5898         vmcs_write32(sf->ar_bytes, ar);
5899 }
5900
5901 static int alloc_apic_access_page(struct kvm *kvm)
5902 {
5903         struct page *page;
5904         int r = 0;
5905
5906         mutex_lock(&kvm->slots_lock);
5907         if (kvm->arch.apic_access_page_done)
5908                 goto out;
5909         r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
5910                                     APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
5911         if (r)
5912                 goto out;
5913
5914         page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
5915         if (is_error_page(page)) {
5916                 r = -EFAULT;
5917                 goto out;
5918         }
5919
5920         /*
5921          * Do not pin the page in memory, so that memory hot-unplug
5922          * is able to migrate it.
5923          */
5924         put_page(page);
5925         kvm->arch.apic_access_page_done = true;
5926 out:
5927         mutex_unlock(&kvm->slots_lock);
5928         return r;
5929 }
5930
5931 static int allocate_vpid(void)
5932 {
5933         int vpid;
5934
5935         if (!enable_vpid)
5936                 return 0;
5937         spin_lock(&vmx_vpid_lock);
5938         vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
5939         if (vpid < VMX_NR_VPIDS)
5940                 __set_bit(vpid, vmx_vpid_bitmap);
5941         else
5942                 vpid = 0;
5943         spin_unlock(&vmx_vpid_lock);
5944         return vpid;
5945 }
5946
5947 static void free_vpid(int vpid)
5948 {
5949         if (!enable_vpid || vpid == 0)
5950                 return;
5951         spin_lock(&vmx_vpid_lock);
5952         __clear_bit(vpid, vmx_vpid_bitmap);
5953         spin_unlock(&vmx_vpid_lock);
5954 }
5955
5956 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
5957                                                           u32 msr, int type)
5958 {
5959         int f = sizeof(unsigned long);
5960
5961         if (!cpu_has_vmx_msr_bitmap())
5962                 return;
5963
5964         if (static_branch_unlikely(&enable_evmcs))
5965                 evmcs_touch_msr_bitmap();
5966
5967         /*
5968          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5969          * have the write-low and read-high bitmap offsets the wrong way round.
5970          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5971          */
5972         if (msr <= 0x1fff) {
5973                 if (type & MSR_TYPE_R)
5974                         /* read-low */
5975                         __clear_bit(msr, msr_bitmap + 0x000 / f);
5976
5977                 if (type & MSR_TYPE_W)
5978                         /* write-low */
5979                         __clear_bit(msr, msr_bitmap + 0x800 / f);
5980
5981         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5982                 msr &= 0x1fff;
5983                 if (type & MSR_TYPE_R)
5984                         /* read-high */
5985                         __clear_bit(msr, msr_bitmap + 0x400 / f);
5986
5987                 if (type & MSR_TYPE_W)
5988                         /* write-high */
5989                         __clear_bit(msr, msr_bitmap + 0xc00 / f);
5990
5991         }
5992 }
5993
5994 static __always_inline void vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
5995                                                          u32 msr, int type)
5996 {
5997         int f = sizeof(unsigned long);
5998
5999         if (!cpu_has_vmx_msr_bitmap())
6000                 return;
6001
6002         if (static_branch_unlikely(&enable_evmcs))
6003                 evmcs_touch_msr_bitmap();
6004
6005         /*
6006          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
6007          * have the write-low and read-high bitmap offsets the wrong way round.
6008          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
6009          */
6010         if (msr <= 0x1fff) {
6011                 if (type & MSR_TYPE_R)
6012                         /* read-low */
6013                         __set_bit(msr, msr_bitmap + 0x000 / f);
6014
6015                 if (type & MSR_TYPE_W)
6016                         /* write-low */
6017                         __set_bit(msr, msr_bitmap + 0x800 / f);
6018
6019         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
6020                 msr &= 0x1fff;
6021                 if (type & MSR_TYPE_R)
6022                         /* read-high */
6023                         __set_bit(msr, msr_bitmap + 0x400 / f);
6024
6025                 if (type & MSR_TYPE_W)
6026                         /* write-high */
6027                         __set_bit(msr, msr_bitmap + 0xc00 / f);
6028
6029         }
6030 }
6031
6032 static __always_inline void vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
6033                                                       u32 msr, int type, bool value)
6034 {
6035         if (value)
6036                 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
6037         else
6038                 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
6039 }
6040
6041 /*
6042  * If a msr is allowed by L0, we should check whether it is allowed by L1.
6043  * The corresponding bit will be cleared unless both of L0 and L1 allow it.
6044  */
6045 static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
6046                                                unsigned long *msr_bitmap_nested,
6047                                                u32 msr, int type)
6048 {
6049         int f = sizeof(unsigned long);
6050
6051         /*
6052          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
6053          * have the write-low and read-high bitmap offsets the wrong way round.
6054          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
6055          */
6056         if (msr <= 0x1fff) {
6057                 if (type & MSR_TYPE_R &&
6058                    !test_bit(msr, msr_bitmap_l1 + 0x000 / f))
6059                         /* read-low */
6060                         __clear_bit(msr, msr_bitmap_nested + 0x000 / f);
6061
6062                 if (type & MSR_TYPE_W &&
6063                    !test_bit(msr, msr_bitmap_l1 + 0x800 / f))
6064                         /* write-low */
6065                         __clear_bit(msr, msr_bitmap_nested + 0x800 / f);
6066
6067         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
6068                 msr &= 0x1fff;
6069                 if (type & MSR_TYPE_R &&
6070                    !test_bit(msr, msr_bitmap_l1 + 0x400 / f))
6071                         /* read-high */
6072                         __clear_bit(msr, msr_bitmap_nested + 0x400 / f);
6073
6074                 if (type & MSR_TYPE_W &&
6075                    !test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
6076                         /* write-high */
6077                         __clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
6078
6079         }
6080 }
6081
6082 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
6083 {
6084         u8 mode = 0;
6085
6086         if (cpu_has_secondary_exec_ctrls() &&
6087             (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
6088              SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
6089                 mode |= MSR_BITMAP_MODE_X2APIC;
6090                 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
6091                         mode |= MSR_BITMAP_MODE_X2APIC_APICV;
6092         }
6093
6094         return mode;
6095 }
6096
6097 #define X2APIC_MSR(r) (APIC_BASE_MSR + ((r) >> 4))
6098
6099 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
6100                                          u8 mode)
6101 {
6102         int msr;
6103
6104         for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
6105                 unsigned word = msr / BITS_PER_LONG;
6106                 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
6107                 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
6108         }
6109
6110         if (mode & MSR_BITMAP_MODE_X2APIC) {
6111                 /*
6112                  * TPR reads and writes can be virtualized even if virtual interrupt
6113                  * delivery is not in use.
6114                  */
6115                 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
6116                 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
6117                         vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
6118                         vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
6119                         vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
6120                 }
6121         }
6122 }
6123
6124 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
6125 {
6126         struct vcpu_vmx *vmx = to_vmx(vcpu);
6127         unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
6128         u8 mode = vmx_msr_bitmap_mode(vcpu);
6129         u8 changed = mode ^ vmx->msr_bitmap_mode;
6130
6131         if (!changed)
6132                 return;
6133
6134         if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
6135                 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
6136
6137         vmx->msr_bitmap_mode = mode;
6138 }
6139
6140 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
6141 {
6142         return enable_apicv;
6143 }
6144
6145 static void nested_mark_vmcs12_pages_dirty(struct kvm_vcpu *vcpu)
6146 {
6147         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6148         gfn_t gfn;
6149
6150         /*
6151          * Don't need to mark the APIC access page dirty; it is never
6152          * written to by the CPU during APIC virtualization.
6153          */
6154
6155         if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
6156                 gfn = vmcs12->virtual_apic_page_addr >> PAGE_SHIFT;
6157                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
6158         }
6159
6160         if (nested_cpu_has_posted_intr(vmcs12)) {
6161                 gfn = vmcs12->posted_intr_desc_addr >> PAGE_SHIFT;
6162                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
6163         }
6164 }
6165
6166
6167 static void vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
6168 {
6169         struct vcpu_vmx *vmx = to_vmx(vcpu);
6170         int max_irr;
6171         void *vapic_page;
6172         u16 status;
6173
6174         if (!vmx->nested.pi_desc || !vmx->nested.pi_pending)
6175                 return;
6176
6177         vmx->nested.pi_pending = false;
6178         if (!pi_test_and_clear_on(vmx->nested.pi_desc))
6179                 return;
6180
6181         max_irr = find_last_bit((unsigned long *)vmx->nested.pi_desc->pir, 256);
6182         if (max_irr != 256) {
6183                 vapic_page = kmap(vmx->nested.virtual_apic_page);
6184                 __kvm_apic_update_irr(vmx->nested.pi_desc->pir,
6185                         vapic_page, &max_irr);
6186                 kunmap(vmx->nested.virtual_apic_page);
6187
6188                 status = vmcs_read16(GUEST_INTR_STATUS);
6189                 if ((u8)max_irr > ((u8)status & 0xff)) {
6190                         status &= ~0xff;
6191                         status |= (u8)max_irr;
6192                         vmcs_write16(GUEST_INTR_STATUS, status);
6193                 }
6194         }
6195
6196         nested_mark_vmcs12_pages_dirty(vcpu);
6197 }
6198
6199 static u8 vmx_get_rvi(void)
6200 {
6201         return vmcs_read16(GUEST_INTR_STATUS) & 0xff;
6202 }
6203
6204 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
6205 {
6206         struct vcpu_vmx *vmx = to_vmx(vcpu);
6207         void *vapic_page;
6208         u32 vppr;
6209         int rvi;
6210
6211         if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
6212                 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
6213                 WARN_ON_ONCE(!vmx->nested.virtual_apic_page))
6214                 return false;
6215
6216         rvi = vmx_get_rvi();
6217
6218         vapic_page = kmap(vmx->nested.virtual_apic_page);
6219         vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
6220         kunmap(vmx->nested.virtual_apic_page);
6221
6222         return ((rvi & 0xf0) > (vppr & 0xf0));
6223 }
6224
6225 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
6226                                                      bool nested)
6227 {
6228 #ifdef CONFIG_SMP
6229         int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
6230
6231         if (vcpu->mode == IN_GUEST_MODE) {
6232                 /*
6233                  * The vector of interrupt to be delivered to vcpu had
6234                  * been set in PIR before this function.
6235                  *
6236                  * Following cases will be reached in this block, and
6237                  * we always send a notification event in all cases as
6238                  * explained below.
6239                  *
6240                  * Case 1: vcpu keeps in non-root mode. Sending a
6241                  * notification event posts the interrupt to vcpu.
6242                  *
6243                  * Case 2: vcpu exits to root mode and is still
6244                  * runnable. PIR will be synced to vIRR before the
6245                  * next vcpu entry. Sending a notification event in
6246                  * this case has no effect, as vcpu is not in root
6247                  * mode.
6248                  *
6249                  * Case 3: vcpu exits to root mode and is blocked.
6250                  * vcpu_block() has already synced PIR to vIRR and
6251                  * never blocks vcpu if vIRR is not cleared. Therefore,
6252                  * a blocked vcpu here does not wait for any requested
6253                  * interrupts in PIR, and sending a notification event
6254                  * which has no effect is safe here.
6255                  */
6256
6257                 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
6258                 return true;
6259         }
6260 #endif
6261         return false;
6262 }
6263
6264 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
6265                                                 int vector)
6266 {
6267         struct vcpu_vmx *vmx = to_vmx(vcpu);
6268
6269         if (is_guest_mode(vcpu) &&
6270             vector == vmx->nested.posted_intr_nv) {
6271                 /*
6272                  * If a posted intr is not recognized by hardware,
6273                  * we will accomplish it in the next vmentry.
6274                  */
6275                 vmx->nested.pi_pending = true;
6276                 kvm_make_request(KVM_REQ_EVENT, vcpu);
6277                 /* the PIR and ON have been set by L1. */
6278                 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
6279                         kvm_vcpu_kick(vcpu);
6280                 return 0;
6281         }
6282         return -1;
6283 }
6284 /*
6285  * Send interrupt to vcpu via posted interrupt way.
6286  * 1. If target vcpu is running(non-root mode), send posted interrupt
6287  * notification to vcpu and hardware will sync PIR to vIRR atomically.
6288  * 2. If target vcpu isn't running(root mode), kick it to pick up the
6289  * interrupt from PIR in next vmentry.
6290  */
6291 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
6292 {
6293         struct vcpu_vmx *vmx = to_vmx(vcpu);
6294         int r;
6295
6296         r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
6297         if (!r)
6298                 return;
6299
6300         if (pi_test_and_set_pir(vector, &vmx->pi_desc))
6301                 return;
6302
6303         /* If a previous notification has sent the IPI, nothing to do.  */
6304         if (pi_test_and_set_on(&vmx->pi_desc))
6305                 return;
6306
6307         if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
6308                 kvm_vcpu_kick(vcpu);
6309 }
6310
6311 /*
6312  * Set up the vmcs's constant host-state fields, i.e., host-state fields that
6313  * will not change in the lifetime of the guest.
6314  * Note that host-state that does change is set elsewhere. E.g., host-state
6315  * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
6316  */
6317 static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
6318 {
6319         u32 low32, high32;
6320         unsigned long tmpl;
6321         struct desc_ptr dt;
6322         unsigned long cr0, cr3, cr4;
6323
6324         cr0 = read_cr0();
6325         WARN_ON(cr0 & X86_CR0_TS);
6326         vmcs_writel(HOST_CR0, cr0);  /* 22.2.3 */
6327
6328         /*
6329          * Save the most likely value for this task's CR3 in the VMCS.
6330          * We can't use __get_current_cr3_fast() because we're not atomic.
6331          */
6332         cr3 = __read_cr3();
6333         vmcs_writel(HOST_CR3, cr3);             /* 22.2.3  FIXME: shadow tables */
6334         vmx->loaded_vmcs->host_state.cr3 = cr3;
6335
6336         /* Save the most likely value for this task's CR4 in the VMCS. */
6337         cr4 = cr4_read_shadow();
6338         vmcs_writel(HOST_CR4, cr4);                     /* 22.2.3, 22.2.5 */
6339         vmx->loaded_vmcs->host_state.cr4 = cr4;
6340
6341         vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
6342 #ifdef CONFIG_X86_64
6343         /*
6344          * Load null selectors, so we can avoid reloading them in
6345          * vmx_prepare_switch_to_host(), in case userspace uses
6346          * the null selectors too (the expected case).
6347          */
6348         vmcs_write16(HOST_DS_SELECTOR, 0);
6349         vmcs_write16(HOST_ES_SELECTOR, 0);
6350 #else
6351         vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
6352         vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
6353 #endif
6354         vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
6355         vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
6356
6357         store_idt(&dt);
6358         vmcs_writel(HOST_IDTR_BASE, dt.address);   /* 22.2.4 */
6359         vmx->host_idt_base = dt.address;
6360
6361         vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
6362
6363         rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
6364         vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
6365         rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
6366         vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl);   /* 22.2.3 */
6367
6368         if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
6369                 rdmsr(MSR_IA32_CR_PAT, low32, high32);
6370                 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
6371         }
6372
6373         if (cpu_has_load_ia32_efer)
6374                 vmcs_write64(HOST_IA32_EFER, host_efer);
6375 }
6376
6377 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
6378 {
6379         vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
6380         if (enable_ept)
6381                 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
6382         if (is_guest_mode(&vmx->vcpu))
6383                 vmx->vcpu.arch.cr4_guest_owned_bits &=
6384                         ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
6385         vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
6386 }
6387
6388 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
6389 {
6390         u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
6391
6392         if (!kvm_vcpu_apicv_active(&vmx->vcpu))
6393                 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
6394
6395         if (!enable_vnmi)
6396                 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
6397
6398         /* Enable the preemption timer dynamically */
6399         pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
6400         return pin_based_exec_ctrl;
6401 }
6402
6403 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
6404 {
6405         struct vcpu_vmx *vmx = to_vmx(vcpu);
6406
6407         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
6408         if (cpu_has_secondary_exec_ctrls()) {
6409                 if (kvm_vcpu_apicv_active(vcpu))
6410                         vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
6411                                       SECONDARY_EXEC_APIC_REGISTER_VIRT |
6412                                       SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6413                 else
6414                         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
6415                                         SECONDARY_EXEC_APIC_REGISTER_VIRT |
6416                                         SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6417         }
6418
6419         if (cpu_has_vmx_msr_bitmap())
6420                 vmx_update_msr_bitmap(vcpu);
6421 }
6422
6423 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
6424 {
6425         u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
6426
6427         if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
6428                 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
6429
6430         if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
6431                 exec_control &= ~CPU_BASED_TPR_SHADOW;
6432 #ifdef CONFIG_X86_64
6433                 exec_control |= CPU_BASED_CR8_STORE_EXITING |
6434                                 CPU_BASED_CR8_LOAD_EXITING;
6435 #endif
6436         }
6437         if (!enable_ept)
6438                 exec_control |= CPU_BASED_CR3_STORE_EXITING |
6439                                 CPU_BASED_CR3_LOAD_EXITING  |
6440                                 CPU_BASED_INVLPG_EXITING;
6441         if (kvm_mwait_in_guest(vmx->vcpu.kvm))
6442                 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
6443                                 CPU_BASED_MONITOR_EXITING);
6444         if (kvm_hlt_in_guest(vmx->vcpu.kvm))
6445                 exec_control &= ~CPU_BASED_HLT_EXITING;
6446         return exec_control;
6447 }
6448
6449 static bool vmx_rdrand_supported(void)
6450 {
6451         return vmcs_config.cpu_based_2nd_exec_ctrl &
6452                 SECONDARY_EXEC_RDRAND_EXITING;
6453 }
6454
6455 static bool vmx_rdseed_supported(void)
6456 {
6457         return vmcs_config.cpu_based_2nd_exec_ctrl &
6458                 SECONDARY_EXEC_RDSEED_EXITING;
6459 }
6460
6461 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
6462 {
6463         struct kvm_vcpu *vcpu = &vmx->vcpu;
6464
6465         u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
6466
6467         if (!cpu_need_virtualize_apic_accesses(vcpu))
6468                 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6469         if (vmx->vpid == 0)
6470                 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
6471         if (!enable_ept) {
6472                 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
6473                 enable_unrestricted_guest = 0;
6474         }
6475         if (!enable_unrestricted_guest)
6476                 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
6477         if (kvm_pause_in_guest(vmx->vcpu.kvm))
6478                 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
6479         if (!kvm_vcpu_apicv_active(vcpu))
6480                 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
6481                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6482         exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6483
6484         /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
6485          * in vmx_set_cr4.  */
6486         exec_control &= ~SECONDARY_EXEC_DESC;
6487
6488         /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
6489            (handle_vmptrld).
6490            We can NOT enable shadow_vmcs here because we don't have yet
6491            a current VMCS12
6492         */
6493         exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
6494
6495         if (!enable_pml)
6496                 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
6497
6498         if (vmx_xsaves_supported()) {
6499                 /* Exposing XSAVES only when XSAVE is exposed */
6500                 bool xsaves_enabled =
6501                         guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
6502                         guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
6503
6504                 if (!xsaves_enabled)
6505                         exec_control &= ~SECONDARY_EXEC_XSAVES;
6506
6507                 if (nested) {
6508                         if (xsaves_enabled)
6509                                 vmx->nested.msrs.secondary_ctls_high |=
6510                                         SECONDARY_EXEC_XSAVES;
6511                         else
6512                                 vmx->nested.msrs.secondary_ctls_high &=
6513                                         ~SECONDARY_EXEC_XSAVES;
6514                 }
6515         }
6516
6517         if (vmx_rdtscp_supported()) {
6518                 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
6519                 if (!rdtscp_enabled)
6520                         exec_control &= ~SECONDARY_EXEC_RDTSCP;
6521
6522                 if (nested) {
6523                         if (rdtscp_enabled)
6524                                 vmx->nested.msrs.secondary_ctls_high |=
6525                                         SECONDARY_EXEC_RDTSCP;
6526                         else
6527                                 vmx->nested.msrs.secondary_ctls_high &=
6528                                         ~SECONDARY_EXEC_RDTSCP;
6529                 }
6530         }
6531
6532         if (vmx_invpcid_supported()) {
6533                 /* Exposing INVPCID only when PCID is exposed */
6534                 bool invpcid_enabled =
6535                         guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
6536                         guest_cpuid_has(vcpu, X86_FEATURE_PCID);
6537
6538                 if (!invpcid_enabled) {
6539                         exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
6540                         guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
6541                 }
6542
6543                 if (nested) {
6544                         if (invpcid_enabled)
6545                                 vmx->nested.msrs.secondary_ctls_high |=
6546                                         SECONDARY_EXEC_ENABLE_INVPCID;
6547                         else
6548                                 vmx->nested.msrs.secondary_ctls_high &=
6549                                         ~SECONDARY_EXEC_ENABLE_INVPCID;
6550                 }
6551         }
6552
6553         if (vmx_rdrand_supported()) {
6554                 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
6555                 if (rdrand_enabled)
6556                         exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
6557
6558                 if (nested) {
6559                         if (rdrand_enabled)
6560                                 vmx->nested.msrs.secondary_ctls_high |=
6561                                         SECONDARY_EXEC_RDRAND_EXITING;
6562                         else
6563                                 vmx->nested.msrs.secondary_ctls_high &=
6564                                         ~SECONDARY_EXEC_RDRAND_EXITING;
6565                 }
6566         }
6567
6568         if (vmx_rdseed_supported()) {
6569                 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
6570                 if (rdseed_enabled)
6571                         exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
6572
6573                 if (nested) {
6574                         if (rdseed_enabled)
6575                                 vmx->nested.msrs.secondary_ctls_high |=
6576                                         SECONDARY_EXEC_RDSEED_EXITING;
6577                         else
6578                                 vmx->nested.msrs.secondary_ctls_high &=
6579                                         ~SECONDARY_EXEC_RDSEED_EXITING;
6580                 }
6581         }
6582
6583         vmx->secondary_exec_control = exec_control;
6584 }
6585
6586 static void ept_set_mmio_spte_mask(void)
6587 {
6588         /*
6589          * EPT Misconfigurations can be generated if the value of bits 2:0
6590          * of an EPT paging-structure entry is 110b (write/execute).
6591          */
6592         kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
6593                                    VMX_EPT_MISCONFIG_WX_VALUE);
6594 }
6595
6596 #define VMX_XSS_EXIT_BITMAP 0
6597 /*
6598  * Sets up the vmcs for emulated real mode.
6599  */
6600 static void vmx_vcpu_setup(struct vcpu_vmx *vmx)
6601 {
6602         int i;
6603
6604         if (enable_shadow_vmcs) {
6605                 /*
6606                  * At vCPU creation, "VMWRITE to any supported field
6607                  * in the VMCS" is supported, so use the more
6608                  * permissive vmx_vmread_bitmap to specify both read
6609                  * and write permissions for the shadow VMCS.
6610                  */
6611                 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
6612                 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmread_bitmap));
6613         }
6614         if (cpu_has_vmx_msr_bitmap())
6615                 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
6616
6617         vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
6618
6619         /* Control */
6620         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
6621         vmx->hv_deadline_tsc = -1;
6622
6623         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
6624
6625         if (cpu_has_secondary_exec_ctrls()) {
6626                 vmx_compute_secondary_exec_control(vmx);
6627                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
6628                              vmx->secondary_exec_control);
6629         }
6630
6631         if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
6632                 vmcs_write64(EOI_EXIT_BITMAP0, 0);
6633                 vmcs_write64(EOI_EXIT_BITMAP1, 0);
6634                 vmcs_write64(EOI_EXIT_BITMAP2, 0);
6635                 vmcs_write64(EOI_EXIT_BITMAP3, 0);
6636
6637                 vmcs_write16(GUEST_INTR_STATUS, 0);
6638
6639                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
6640                 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
6641         }
6642
6643         if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
6644                 vmcs_write32(PLE_GAP, ple_gap);
6645                 vmx->ple_window = ple_window;
6646                 vmx->ple_window_dirty = true;
6647         }
6648
6649         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
6650         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
6651         vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
6652
6653         vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
6654         vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
6655         vmx_set_constant_host_state(vmx);
6656         vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
6657         vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
6658
6659         if (cpu_has_vmx_vmfunc())
6660                 vmcs_write64(VM_FUNCTION_CONTROL, 0);
6661
6662         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
6663         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
6664         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
6665         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
6666         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
6667
6668         if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
6669                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
6670
6671         for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
6672                 u32 index = vmx_msr_index[i];
6673                 u32 data_low, data_high;
6674                 int j = vmx->nmsrs;
6675
6676                 if (rdmsr_safe(index, &data_low, &data_high) < 0)
6677                         continue;
6678                 if (wrmsr_safe(index, data_low, data_high) < 0)
6679                         continue;
6680                 vmx->guest_msrs[j].index = i;
6681                 vmx->guest_msrs[j].data = 0;
6682                 vmx->guest_msrs[j].mask = -1ull;
6683                 ++vmx->nmsrs;
6684         }
6685
6686         vmx->arch_capabilities = kvm_get_arch_capabilities();
6687
6688         vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
6689
6690         /* 22.2.1, 20.8.1 */
6691         vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
6692
6693         vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
6694         vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
6695
6696         set_cr4_guest_host_mask(vmx);
6697
6698         if (vmx_xsaves_supported())
6699                 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
6700
6701         if (enable_pml) {
6702                 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
6703                 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
6704         }
6705
6706         if (cpu_has_vmx_encls_vmexit())
6707                 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
6708 }
6709
6710 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
6711 {
6712         struct vcpu_vmx *vmx = to_vmx(vcpu);
6713         struct msr_data apic_base_msr;
6714         u64 cr0;
6715
6716         vmx->rmode.vm86_active = 0;
6717         vmx->spec_ctrl = 0;
6718
6719         vcpu->arch.microcode_version = 0x100000000ULL;
6720         vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
6721         kvm_set_cr8(vcpu, 0);
6722
6723         if (!init_event) {
6724                 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
6725                                      MSR_IA32_APICBASE_ENABLE;
6726                 if (kvm_vcpu_is_reset_bsp(vcpu))
6727                         apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
6728                 apic_base_msr.host_initiated = true;
6729                 kvm_set_apic_base(vcpu, &apic_base_msr);
6730         }
6731
6732         vmx_segment_cache_clear(vmx);
6733
6734         seg_setup(VCPU_SREG_CS);
6735         vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
6736         vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
6737
6738         seg_setup(VCPU_SREG_DS);
6739         seg_setup(VCPU_SREG_ES);
6740         seg_setup(VCPU_SREG_FS);
6741         seg_setup(VCPU_SREG_GS);
6742         seg_setup(VCPU_SREG_SS);
6743
6744         vmcs_write16(GUEST_TR_SELECTOR, 0);
6745         vmcs_writel(GUEST_TR_BASE, 0);
6746         vmcs_write32(GUEST_TR_LIMIT, 0xffff);
6747         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
6748
6749         vmcs_write16(GUEST_LDTR_SELECTOR, 0);
6750         vmcs_writel(GUEST_LDTR_BASE, 0);
6751         vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
6752         vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
6753
6754         if (!init_event) {
6755                 vmcs_write32(GUEST_SYSENTER_CS, 0);
6756                 vmcs_writel(GUEST_SYSENTER_ESP, 0);
6757                 vmcs_writel(GUEST_SYSENTER_EIP, 0);
6758                 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
6759         }
6760
6761         kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
6762         kvm_rip_write(vcpu, 0xfff0);
6763
6764         vmcs_writel(GUEST_GDTR_BASE, 0);
6765         vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
6766
6767         vmcs_writel(GUEST_IDTR_BASE, 0);
6768         vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
6769
6770         vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
6771         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
6772         vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
6773         if (kvm_mpx_supported())
6774                 vmcs_write64(GUEST_BNDCFGS, 0);
6775
6776         setup_msrs(vmx);
6777
6778         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
6779
6780         if (cpu_has_vmx_tpr_shadow() && !init_event) {
6781                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
6782                 if (cpu_need_tpr_shadow(vcpu))
6783                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
6784                                      __pa(vcpu->arch.apic->regs));
6785                 vmcs_write32(TPR_THRESHOLD, 0);
6786         }
6787
6788         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6789
6790         if (vmx->vpid != 0)
6791                 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
6792
6793         cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
6794         vmx->vcpu.arch.cr0 = cr0;
6795         vmx_set_cr0(vcpu, cr0); /* enter rmode */
6796         vmx_set_cr4(vcpu, 0);
6797         vmx_set_efer(vcpu, 0);
6798
6799         update_exception_bitmap(vcpu);
6800
6801         vpid_sync_context(vmx->vpid);
6802         if (init_event)
6803                 vmx_clear_hlt(vcpu);
6804 }
6805
6806 /*
6807  * In nested virtualization, check if L1 asked to exit on external interrupts.
6808  * For most existing hypervisors, this will always return true.
6809  */
6810 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
6811 {
6812         return get_vmcs12(vcpu)->pin_based_vm_exec_control &
6813                 PIN_BASED_EXT_INTR_MASK;
6814 }
6815
6816 /*
6817  * In nested virtualization, check if L1 has set
6818  * VM_EXIT_ACK_INTR_ON_EXIT
6819  */
6820 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
6821 {
6822         return get_vmcs12(vcpu)->vm_exit_controls &
6823                 VM_EXIT_ACK_INTR_ON_EXIT;
6824 }
6825
6826 static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
6827 {
6828         return nested_cpu_has_nmi_exiting(get_vmcs12(vcpu));
6829 }
6830
6831 static void enable_irq_window(struct kvm_vcpu *vcpu)
6832 {
6833         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
6834                       CPU_BASED_VIRTUAL_INTR_PENDING);
6835 }
6836
6837 static void enable_nmi_window(struct kvm_vcpu *vcpu)
6838 {
6839         if (!enable_vnmi ||
6840             vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
6841                 enable_irq_window(vcpu);
6842                 return;
6843         }
6844
6845         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
6846                       CPU_BASED_VIRTUAL_NMI_PENDING);
6847 }
6848
6849 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
6850 {
6851         struct vcpu_vmx *vmx = to_vmx(vcpu);
6852         uint32_t intr;
6853         int irq = vcpu->arch.interrupt.nr;
6854
6855         trace_kvm_inj_virq(irq);
6856
6857         ++vcpu->stat.irq_injections;
6858         if (vmx->rmode.vm86_active) {
6859                 int inc_eip = 0;
6860                 if (vcpu->arch.interrupt.soft)
6861                         inc_eip = vcpu->arch.event_exit_inst_len;
6862                 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
6863                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6864                 return;
6865         }
6866         intr = irq | INTR_INFO_VALID_MASK;
6867         if (vcpu->arch.interrupt.soft) {
6868                 intr |= INTR_TYPE_SOFT_INTR;
6869                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
6870                              vmx->vcpu.arch.event_exit_inst_len);
6871         } else
6872                 intr |= INTR_TYPE_EXT_INTR;
6873         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
6874
6875         vmx_clear_hlt(vcpu);
6876 }
6877
6878 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
6879 {
6880         struct vcpu_vmx *vmx = to_vmx(vcpu);
6881
6882         if (!enable_vnmi) {
6883                 /*
6884                  * Tracking the NMI-blocked state in software is built upon
6885                  * finding the next open IRQ window. This, in turn, depends on
6886                  * well-behaving guests: They have to keep IRQs disabled at
6887                  * least as long as the NMI handler runs. Otherwise we may
6888                  * cause NMI nesting, maybe breaking the guest. But as this is
6889                  * highly unlikely, we can live with the residual risk.
6890                  */
6891                 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
6892                 vmx->loaded_vmcs->vnmi_blocked_time = 0;
6893         }
6894
6895         ++vcpu->stat.nmi_injections;
6896         vmx->loaded_vmcs->nmi_known_unmasked = false;
6897
6898         if (vmx->rmode.vm86_active) {
6899                 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
6900                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6901                 return;
6902         }
6903
6904         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
6905                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
6906
6907         vmx_clear_hlt(vcpu);
6908 }
6909
6910 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
6911 {
6912         struct vcpu_vmx *vmx = to_vmx(vcpu);
6913         bool masked;
6914
6915         if (!enable_vnmi)
6916                 return vmx->loaded_vmcs->soft_vnmi_blocked;
6917         if (vmx->loaded_vmcs->nmi_known_unmasked)
6918                 return false;
6919         masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
6920         vmx->loaded_vmcs->nmi_known_unmasked = !masked;
6921         return masked;
6922 }
6923
6924 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
6925 {
6926         struct vcpu_vmx *vmx = to_vmx(vcpu);
6927
6928         if (!enable_vnmi) {
6929                 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
6930                         vmx->loaded_vmcs->soft_vnmi_blocked = masked;
6931                         vmx->loaded_vmcs->vnmi_blocked_time = 0;
6932                 }
6933         } else {
6934                 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
6935                 if (masked)
6936                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6937                                       GUEST_INTR_STATE_NMI);
6938                 else
6939                         vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
6940                                         GUEST_INTR_STATE_NMI);
6941         }
6942 }
6943
6944 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
6945 {
6946         if (to_vmx(vcpu)->nested.nested_run_pending)
6947                 return 0;
6948
6949         if (!enable_vnmi &&
6950             to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
6951                 return 0;
6952
6953         return  !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6954                   (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
6955                    | GUEST_INTR_STATE_NMI));
6956 }
6957
6958 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
6959 {
6960         return (!to_vmx(vcpu)->nested.nested_run_pending &&
6961                 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
6962                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6963                         (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
6964 }
6965
6966 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
6967 {
6968         int ret;
6969
6970         if (enable_unrestricted_guest)
6971                 return 0;
6972
6973         ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
6974                                     PAGE_SIZE * 3);
6975         if (ret)
6976                 return ret;
6977         to_kvm_vmx(kvm)->tss_addr = addr;
6978         return init_rmode_tss(kvm);
6979 }
6980
6981 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
6982 {
6983         to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
6984         return 0;
6985 }
6986
6987 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
6988 {
6989         switch (vec) {
6990         case BP_VECTOR:
6991                 /*
6992                  * Update instruction length as we may reinject the exception
6993                  * from user space while in guest debugging mode.
6994                  */
6995                 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
6996                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6997                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
6998                         return false;
6999                 /* fall through */
7000         case DB_VECTOR:
7001                 if (vcpu->guest_debug &
7002                         (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
7003                         return false;
7004                 /* fall through */
7005         case DE_VECTOR:
7006         case OF_VECTOR:
7007         case BR_VECTOR:
7008         case UD_VECTOR:
7009         case DF_VECTOR:
7010         case SS_VECTOR:
7011         case GP_VECTOR:
7012         case MF_VECTOR:
7013                 return true;
7014         break;
7015         }
7016         return false;
7017 }
7018
7019 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
7020                                   int vec, u32 err_code)
7021 {
7022         /*
7023          * Instruction with address size override prefix opcode 0x67
7024          * Cause the #SS fault with 0 error code in VM86 mode.
7025          */
7026         if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
7027                 if (kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE) {
7028                         if (vcpu->arch.halt_request) {
7029                                 vcpu->arch.halt_request = 0;
7030                                 return kvm_vcpu_halt(vcpu);
7031                         }
7032                         return 1;
7033                 }
7034                 return 0;
7035         }
7036
7037         /*
7038          * Forward all other exceptions that are valid in real mode.
7039          * FIXME: Breaks guest debugging in real mode, needs to be fixed with
7040          *        the required debugging infrastructure rework.
7041          */
7042         kvm_queue_exception(vcpu, vec);
7043         return 1;
7044 }
7045
7046 /*
7047  * Trigger machine check on the host. We assume all the MSRs are already set up
7048  * by the CPU and that we still run on the same CPU as the MCE occurred on.
7049  * We pass a fake environment to the machine check handler because we want
7050  * the guest to be always treated like user space, no matter what context
7051  * it used internally.
7052  */
7053 static void kvm_machine_check(void)
7054 {
7055 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
7056         struct pt_regs regs = {
7057                 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
7058                 .flags = X86_EFLAGS_IF,
7059         };
7060
7061         do_machine_check(&regs, 0);
7062 #endif
7063 }
7064
7065 static int handle_machine_check(struct kvm_vcpu *vcpu)
7066 {
7067         /* already handled by vcpu_run */
7068         return 1;
7069 }
7070
7071 static int handle_exception(struct kvm_vcpu *vcpu)
7072 {
7073         struct vcpu_vmx *vmx = to_vmx(vcpu);
7074         struct kvm_run *kvm_run = vcpu->run;
7075         u32 intr_info, ex_no, error_code;
7076         unsigned long cr2, rip, dr6;
7077         u32 vect_info;
7078         enum emulation_result er;
7079
7080         vect_info = vmx->idt_vectoring_info;
7081         intr_info = vmx->exit_intr_info;
7082
7083         if (is_machine_check(intr_info))
7084                 return handle_machine_check(vcpu);
7085
7086         if (is_nmi(intr_info))
7087                 return 1;  /* already handled by vmx_vcpu_run() */
7088
7089         if (is_invalid_opcode(intr_info))
7090                 return handle_ud(vcpu);
7091
7092         error_code = 0;
7093         if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
7094                 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
7095
7096         if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
7097                 WARN_ON_ONCE(!enable_vmware_backdoor);
7098                 er = kvm_emulate_instruction(vcpu,
7099                         EMULTYPE_VMWARE | EMULTYPE_NO_UD_ON_FAIL);
7100                 if (er == EMULATE_USER_EXIT)
7101                         return 0;
7102                 else if (er != EMULATE_DONE)
7103                         kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
7104                 return 1;
7105         }
7106
7107         /*
7108          * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
7109          * MMIO, it is better to report an internal error.
7110          * See the comments in vmx_handle_exit.
7111          */
7112         if ((vect_info & VECTORING_INFO_VALID_MASK) &&
7113             !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
7114                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7115                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
7116                 vcpu->run->internal.ndata = 3;
7117                 vcpu->run->internal.data[0] = vect_info;
7118                 vcpu->run->internal.data[1] = intr_info;
7119                 vcpu->run->internal.data[2] = error_code;
7120                 return 0;
7121         }
7122
7123         if (is_page_fault(intr_info)) {
7124                 cr2 = vmcs_readl(EXIT_QUALIFICATION);
7125                 /* EPT won't cause page fault directly */
7126                 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
7127                 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
7128         }
7129
7130         ex_no = intr_info & INTR_INFO_VECTOR_MASK;
7131
7132         if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
7133                 return handle_rmode_exception(vcpu, ex_no, error_code);
7134
7135         switch (ex_no) {
7136         case AC_VECTOR:
7137                 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
7138                 return 1;
7139         case DB_VECTOR:
7140                 dr6 = vmcs_readl(EXIT_QUALIFICATION);
7141                 if (!(vcpu->guest_debug &
7142                       (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
7143                         vcpu->arch.dr6 &= ~15;
7144                         vcpu->arch.dr6 |= dr6 | DR6_RTM;
7145                         if (is_icebp(intr_info))
7146                                 skip_emulated_instruction(vcpu);
7147
7148                         kvm_queue_exception(vcpu, DB_VECTOR);
7149                         return 1;
7150                 }
7151                 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
7152                 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
7153                 /* fall through */
7154         case BP_VECTOR:
7155                 /*
7156                  * Update instruction length as we may reinject #BP from
7157                  * user space while in guest debugging mode. Reading it for
7158                  * #DB as well causes no harm, it is not used in that case.
7159                  */
7160                 vmx->vcpu.arch.event_exit_inst_len =
7161                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
7162                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
7163                 rip = kvm_rip_read(vcpu);
7164                 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
7165                 kvm_run->debug.arch.exception = ex_no;
7166                 break;
7167         default:
7168                 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
7169                 kvm_run->ex.exception = ex_no;
7170                 kvm_run->ex.error_code = error_code;
7171                 break;
7172         }
7173         return 0;
7174 }
7175
7176 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
7177 {
7178         ++vcpu->stat.irq_exits;
7179         return 1;
7180 }
7181
7182 static int handle_triple_fault(struct kvm_vcpu *vcpu)
7183 {
7184         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
7185         vcpu->mmio_needed = 0;
7186         return 0;
7187 }
7188
7189 static int handle_io(struct kvm_vcpu *vcpu)
7190 {
7191         unsigned long exit_qualification;
7192         int size, in, string;
7193         unsigned port;
7194
7195         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7196         string = (exit_qualification & 16) != 0;
7197
7198         ++vcpu->stat.io_exits;
7199
7200         if (string)
7201                 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7202
7203         port = exit_qualification >> 16;
7204         size = (exit_qualification & 7) + 1;
7205         in = (exit_qualification & 8) != 0;
7206
7207         return kvm_fast_pio(vcpu, size, port, in);
7208 }
7209
7210 static void
7211 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
7212 {
7213         /*
7214          * Patch in the VMCALL instruction:
7215          */
7216         hypercall[0] = 0x0f;
7217         hypercall[1] = 0x01;
7218         hypercall[2] = 0xc1;
7219 }
7220
7221 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
7222 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
7223 {
7224         if (is_guest_mode(vcpu)) {
7225                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7226                 unsigned long orig_val = val;
7227
7228                 /*
7229                  * We get here when L2 changed cr0 in a way that did not change
7230                  * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
7231                  * but did change L0 shadowed bits. So we first calculate the
7232                  * effective cr0 value that L1 would like to write into the
7233                  * hardware. It consists of the L2-owned bits from the new
7234                  * value combined with the L1-owned bits from L1's guest_cr0.
7235                  */
7236                 val = (val & ~vmcs12->cr0_guest_host_mask) |
7237                         (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
7238
7239                 if (!nested_guest_cr0_valid(vcpu, val))
7240                         return 1;
7241
7242                 if (kvm_set_cr0(vcpu, val))
7243                         return 1;
7244                 vmcs_writel(CR0_READ_SHADOW, orig_val);
7245                 return 0;
7246         } else {
7247                 if (to_vmx(vcpu)->nested.vmxon &&
7248                     !nested_host_cr0_valid(vcpu, val))
7249                         return 1;
7250
7251                 return kvm_set_cr0(vcpu, val);
7252         }
7253 }
7254
7255 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
7256 {
7257         if (is_guest_mode(vcpu)) {
7258                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7259                 unsigned long orig_val = val;
7260
7261                 /* analogously to handle_set_cr0 */
7262                 val = (val & ~vmcs12->cr4_guest_host_mask) |
7263                         (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
7264                 if (kvm_set_cr4(vcpu, val))
7265                         return 1;
7266                 vmcs_writel(CR4_READ_SHADOW, orig_val);
7267                 return 0;
7268         } else
7269                 return kvm_set_cr4(vcpu, val);
7270 }
7271
7272 static int handle_desc(struct kvm_vcpu *vcpu)
7273 {
7274         WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
7275         return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7276 }
7277
7278 static int handle_cr(struct kvm_vcpu *vcpu)
7279 {
7280         unsigned long exit_qualification, val;
7281         int cr;
7282         int reg;
7283         int err;
7284         int ret;
7285
7286         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7287         cr = exit_qualification & 15;
7288         reg = (exit_qualification >> 8) & 15;
7289         switch ((exit_qualification >> 4) & 3) {
7290         case 0: /* mov to cr */
7291                 val = kvm_register_readl(vcpu, reg);
7292                 trace_kvm_cr_write(cr, val);
7293                 switch (cr) {
7294                 case 0:
7295                         err = handle_set_cr0(vcpu, val);
7296                         return kvm_complete_insn_gp(vcpu, err);
7297                 case 3:
7298                         WARN_ON_ONCE(enable_unrestricted_guest);
7299                         err = kvm_set_cr3(vcpu, val);
7300                         return kvm_complete_insn_gp(vcpu, err);
7301                 case 4:
7302                         err = handle_set_cr4(vcpu, val);
7303                         return kvm_complete_insn_gp(vcpu, err);
7304                 case 8: {
7305                                 u8 cr8_prev = kvm_get_cr8(vcpu);
7306                                 u8 cr8 = (u8)val;
7307                                 err = kvm_set_cr8(vcpu, cr8);
7308                                 ret = kvm_complete_insn_gp(vcpu, err);
7309                                 if (lapic_in_kernel(vcpu))
7310                                         return ret;
7311                                 if (cr8_prev <= cr8)
7312                                         return ret;
7313                                 /*
7314                                  * TODO: we might be squashing a
7315                                  * KVM_GUESTDBG_SINGLESTEP-triggered
7316                                  * KVM_EXIT_DEBUG here.
7317                                  */
7318                                 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
7319                                 return 0;
7320                         }
7321                 }
7322                 break;
7323         case 2: /* clts */
7324                 WARN_ONCE(1, "Guest should always own CR0.TS");
7325                 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
7326                 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
7327                 return kvm_skip_emulated_instruction(vcpu);
7328         case 1: /*mov from cr*/
7329                 switch (cr) {
7330                 case 3:
7331                         WARN_ON_ONCE(enable_unrestricted_guest);
7332                         val = kvm_read_cr3(vcpu);
7333                         kvm_register_write(vcpu, reg, val);
7334                         trace_kvm_cr_read(cr, val);
7335                         return kvm_skip_emulated_instruction(vcpu);
7336                 case 8:
7337                         val = kvm_get_cr8(vcpu);
7338                         kvm_register_write(vcpu, reg, val);
7339                         trace_kvm_cr_read(cr, val);
7340                         return kvm_skip_emulated_instruction(vcpu);
7341                 }
7342                 break;
7343         case 3: /* lmsw */
7344                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
7345                 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
7346                 kvm_lmsw(vcpu, val);
7347
7348                 return kvm_skip_emulated_instruction(vcpu);
7349         default:
7350                 break;
7351         }
7352         vcpu->run->exit_reason = 0;
7353         vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
7354                (int)(exit_qualification >> 4) & 3, cr);
7355         return 0;
7356 }
7357
7358 static int handle_dr(struct kvm_vcpu *vcpu)
7359 {
7360         unsigned long exit_qualification;
7361         int dr, dr7, reg;
7362
7363         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7364         dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
7365
7366         /* First, if DR does not exist, trigger UD */
7367         if (!kvm_require_dr(vcpu, dr))
7368                 return 1;
7369
7370         /* Do not handle if the CPL > 0, will trigger GP on re-entry */
7371         if (!kvm_require_cpl(vcpu, 0))
7372                 return 1;
7373         dr7 = vmcs_readl(GUEST_DR7);
7374         if (dr7 & DR7_GD) {
7375                 /*
7376                  * As the vm-exit takes precedence over the debug trap, we
7377                  * need to emulate the latter, either for the host or the
7378                  * guest debugging itself.
7379                  */
7380                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
7381                         vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
7382                         vcpu->run->debug.arch.dr7 = dr7;
7383                         vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
7384                         vcpu->run->debug.arch.exception = DB_VECTOR;
7385                         vcpu->run->exit_reason = KVM_EXIT_DEBUG;
7386                         return 0;
7387                 } else {
7388                         vcpu->arch.dr6 &= ~15;
7389                         vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
7390                         kvm_queue_exception(vcpu, DB_VECTOR);
7391                         return 1;
7392                 }
7393         }
7394
7395         if (vcpu->guest_debug == 0) {
7396                 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7397                                 CPU_BASED_MOV_DR_EXITING);
7398
7399                 /*
7400                  * No more DR vmexits; force a reload of the debug registers
7401                  * and reenter on this instruction.  The next vmexit will
7402                  * retrieve the full state of the debug registers.
7403                  */
7404                 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
7405                 return 1;
7406         }
7407
7408         reg = DEBUG_REG_ACCESS_REG(exit_qualification);
7409         if (exit_qualification & TYPE_MOV_FROM_DR) {
7410                 unsigned long val;
7411
7412                 if (kvm_get_dr(vcpu, dr, &val))
7413                         return 1;
7414                 kvm_register_write(vcpu, reg, val);
7415         } else
7416                 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
7417                         return 1;
7418
7419         return kvm_skip_emulated_instruction(vcpu);
7420 }
7421
7422 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
7423 {
7424         return vcpu->arch.dr6;
7425 }
7426
7427 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
7428 {
7429 }
7430
7431 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
7432 {
7433         get_debugreg(vcpu->arch.db[0], 0);
7434         get_debugreg(vcpu->arch.db[1], 1);
7435         get_debugreg(vcpu->arch.db[2], 2);
7436         get_debugreg(vcpu->arch.db[3], 3);
7437         get_debugreg(vcpu->arch.dr6, 6);
7438         vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
7439
7440         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
7441         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
7442 }
7443
7444 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
7445 {
7446         vmcs_writel(GUEST_DR7, val);
7447 }
7448
7449 static int handle_cpuid(struct kvm_vcpu *vcpu)
7450 {
7451         return kvm_emulate_cpuid(vcpu);
7452 }
7453
7454 static int handle_rdmsr(struct kvm_vcpu *vcpu)
7455 {
7456         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
7457         struct msr_data msr_info;
7458
7459         msr_info.index = ecx;
7460         msr_info.host_initiated = false;
7461         if (vmx_get_msr(vcpu, &msr_info)) {
7462                 trace_kvm_msr_read_ex(ecx);
7463                 kvm_inject_gp(vcpu, 0);
7464                 return 1;
7465         }
7466
7467         trace_kvm_msr_read(ecx, msr_info.data);
7468
7469         /* FIXME: handling of bits 32:63 of rax, rdx */
7470         vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
7471         vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
7472         return kvm_skip_emulated_instruction(vcpu);
7473 }
7474
7475 static int handle_wrmsr(struct kvm_vcpu *vcpu)
7476 {
7477         struct msr_data msr;
7478         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
7479         u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
7480                 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
7481
7482         msr.data = data;
7483         msr.index = ecx;
7484         msr.host_initiated = false;
7485         if (kvm_set_msr(vcpu, &msr) != 0) {
7486                 trace_kvm_msr_write_ex(ecx, data);
7487                 kvm_inject_gp(vcpu, 0);
7488                 return 1;
7489         }
7490
7491         trace_kvm_msr_write(ecx, data);
7492         return kvm_skip_emulated_instruction(vcpu);
7493 }
7494
7495 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
7496 {
7497         kvm_apic_update_ppr(vcpu);
7498         return 1;
7499 }
7500
7501 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
7502 {
7503         vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7504                         CPU_BASED_VIRTUAL_INTR_PENDING);
7505
7506         kvm_make_request(KVM_REQ_EVENT, vcpu);
7507
7508         ++vcpu->stat.irq_window_exits;
7509         return 1;
7510 }
7511
7512 static int handle_halt(struct kvm_vcpu *vcpu)
7513 {
7514         return kvm_emulate_halt(vcpu);
7515 }
7516
7517 static int handle_vmcall(struct kvm_vcpu *vcpu)
7518 {
7519         return kvm_emulate_hypercall(vcpu);
7520 }
7521
7522 static int handle_invd(struct kvm_vcpu *vcpu)
7523 {
7524         return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7525 }
7526
7527 static int handle_invlpg(struct kvm_vcpu *vcpu)
7528 {
7529         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7530
7531         kvm_mmu_invlpg(vcpu, exit_qualification);
7532         return kvm_skip_emulated_instruction(vcpu);
7533 }
7534
7535 static int handle_rdpmc(struct kvm_vcpu *vcpu)
7536 {
7537         int err;
7538
7539         err = kvm_rdpmc(vcpu);
7540         return kvm_complete_insn_gp(vcpu, err);
7541 }
7542
7543 static int handle_wbinvd(struct kvm_vcpu *vcpu)
7544 {
7545         return kvm_emulate_wbinvd(vcpu);
7546 }
7547
7548 static int handle_xsetbv(struct kvm_vcpu *vcpu)
7549 {
7550         u64 new_bv = kvm_read_edx_eax(vcpu);
7551         u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
7552
7553         if (kvm_set_xcr(vcpu, index, new_bv) == 0)
7554                 return kvm_skip_emulated_instruction(vcpu);
7555         return 1;
7556 }
7557
7558 static int handle_xsaves(struct kvm_vcpu *vcpu)
7559 {
7560         kvm_skip_emulated_instruction(vcpu);
7561         WARN(1, "this should never happen\n");
7562         return 1;
7563 }
7564
7565 static int handle_xrstors(struct kvm_vcpu *vcpu)
7566 {
7567         kvm_skip_emulated_instruction(vcpu);
7568         WARN(1, "this should never happen\n");
7569         return 1;
7570 }
7571
7572 static int handle_apic_access(struct kvm_vcpu *vcpu)
7573 {
7574         if (likely(fasteoi)) {
7575                 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7576                 int access_type, offset;
7577
7578                 access_type = exit_qualification & APIC_ACCESS_TYPE;
7579                 offset = exit_qualification & APIC_ACCESS_OFFSET;
7580                 /*
7581                  * Sane guest uses MOV to write EOI, with written value
7582                  * not cared. So make a short-circuit here by avoiding
7583                  * heavy instruction emulation.
7584                  */
7585                 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
7586                     (offset == APIC_EOI)) {
7587                         kvm_lapic_set_eoi(vcpu);
7588                         return kvm_skip_emulated_instruction(vcpu);
7589                 }
7590         }
7591         return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7592 }
7593
7594 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
7595 {
7596         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7597         int vector = exit_qualification & 0xff;
7598
7599         /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
7600         kvm_apic_set_eoi_accelerated(vcpu, vector);
7601         return 1;
7602 }
7603
7604 static int handle_apic_write(struct kvm_vcpu *vcpu)
7605 {
7606         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7607         u32 offset = exit_qualification & 0xfff;
7608
7609         /* APIC-write VM exit is trap-like and thus no need to adjust IP */
7610         kvm_apic_write_nodecode(vcpu, offset);
7611         return 1;
7612 }
7613
7614 static int handle_task_switch(struct kvm_vcpu *vcpu)
7615 {
7616         struct vcpu_vmx *vmx = to_vmx(vcpu);
7617         unsigned long exit_qualification;
7618         bool has_error_code = false;
7619         u32 error_code = 0;
7620         u16 tss_selector;
7621         int reason, type, idt_v, idt_index;
7622
7623         idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
7624         idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
7625         type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
7626
7627         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7628
7629         reason = (u32)exit_qualification >> 30;
7630         if (reason == TASK_SWITCH_GATE && idt_v) {
7631                 switch (type) {
7632                 case INTR_TYPE_NMI_INTR:
7633                         vcpu->arch.nmi_injected = false;
7634                         vmx_set_nmi_mask(vcpu, true);
7635                         break;
7636                 case INTR_TYPE_EXT_INTR:
7637                 case INTR_TYPE_SOFT_INTR:
7638                         kvm_clear_interrupt_queue(vcpu);
7639                         break;
7640                 case INTR_TYPE_HARD_EXCEPTION:
7641                         if (vmx->idt_vectoring_info &
7642                             VECTORING_INFO_DELIVER_CODE_MASK) {
7643                                 has_error_code = true;
7644                                 error_code =
7645                                         vmcs_read32(IDT_VECTORING_ERROR_CODE);
7646                         }
7647                         /* fall through */
7648                 case INTR_TYPE_SOFT_EXCEPTION:
7649                         kvm_clear_exception_queue(vcpu);
7650                         break;
7651                 default:
7652                         break;
7653                 }
7654         }
7655         tss_selector = exit_qualification;
7656
7657         if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
7658                        type != INTR_TYPE_EXT_INTR &&
7659                        type != INTR_TYPE_NMI_INTR))
7660                 skip_emulated_instruction(vcpu);
7661
7662         if (kvm_task_switch(vcpu, tss_selector,
7663                             type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
7664                             has_error_code, error_code) == EMULATE_FAIL) {
7665                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7666                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7667                 vcpu->run->internal.ndata = 0;
7668                 return 0;
7669         }
7670
7671         /*
7672          * TODO: What about debug traps on tss switch?
7673          *       Are we supposed to inject them and update dr6?
7674          */
7675
7676         return 1;
7677 }
7678
7679 static int handle_ept_violation(struct kvm_vcpu *vcpu)
7680 {
7681         unsigned long exit_qualification;
7682         gpa_t gpa;
7683         u64 error_code;
7684
7685         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7686
7687         /*
7688          * EPT violation happened while executing iret from NMI,
7689          * "blocked by NMI" bit has to be set before next VM entry.
7690          * There are errata that may cause this bit to not be set:
7691          * AAK134, BY25.
7692          */
7693         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
7694                         enable_vnmi &&
7695                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
7696                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
7697
7698         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
7699         trace_kvm_page_fault(gpa, exit_qualification);
7700
7701         /* Is it a read fault? */
7702         error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
7703                      ? PFERR_USER_MASK : 0;
7704         /* Is it a write fault? */
7705         error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
7706                       ? PFERR_WRITE_MASK : 0;
7707         /* Is it a fetch fault? */
7708         error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
7709                       ? PFERR_FETCH_MASK : 0;
7710         /* ept page table entry is present? */
7711         error_code |= (exit_qualification &
7712                        (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
7713                         EPT_VIOLATION_EXECUTABLE))
7714                       ? PFERR_PRESENT_MASK : 0;
7715
7716         error_code |= (exit_qualification & 0x100) != 0 ?
7717                PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
7718
7719         vcpu->arch.exit_qualification = exit_qualification;
7720         return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
7721 }
7722
7723 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
7724 {
7725         gpa_t gpa;
7726
7727         /*
7728          * A nested guest cannot optimize MMIO vmexits, because we have an
7729          * nGPA here instead of the required GPA.
7730          */
7731         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
7732         if (!is_guest_mode(vcpu) &&
7733             !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
7734                 trace_kvm_fast_mmio(gpa);
7735                 /*
7736                  * Doing kvm_skip_emulated_instruction() depends on undefined
7737                  * behavior: Intel's manual doesn't mandate
7738                  * VM_EXIT_INSTRUCTION_LEN to be set in VMCS when EPT MISCONFIG
7739                  * occurs and while on real hardware it was observed to be set,
7740                  * other hypervisors (namely Hyper-V) don't set it, we end up
7741                  * advancing IP with some random value. Disable fast mmio when
7742                  * running nested and keep it for real hardware in hope that
7743                  * VM_EXIT_INSTRUCTION_LEN will always be set correctly.
7744                  */
7745                 if (!static_cpu_has(X86_FEATURE_HYPERVISOR))
7746                         return kvm_skip_emulated_instruction(vcpu);
7747                 else
7748                         return kvm_emulate_instruction(vcpu, EMULTYPE_SKIP) ==
7749                                                                 EMULATE_DONE;
7750         }
7751
7752         return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
7753 }
7754
7755 static int handle_nmi_window(struct kvm_vcpu *vcpu)
7756 {
7757         WARN_ON_ONCE(!enable_vnmi);
7758         vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7759                         CPU_BASED_VIRTUAL_NMI_PENDING);
7760         ++vcpu->stat.nmi_window_exits;
7761         kvm_make_request(KVM_REQ_EVENT, vcpu);
7762
7763         return 1;
7764 }
7765
7766 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
7767 {
7768         struct vcpu_vmx *vmx = to_vmx(vcpu);
7769         enum emulation_result err = EMULATE_DONE;
7770         int ret = 1;
7771         u32 cpu_exec_ctrl;
7772         bool intr_window_requested;
7773         unsigned count = 130;
7774
7775         /*
7776          * We should never reach the point where we are emulating L2
7777          * due to invalid guest state as that means we incorrectly
7778          * allowed a nested VMEntry with an invalid vmcs12.
7779          */
7780         WARN_ON_ONCE(vmx->emulation_required && vmx->nested.nested_run_pending);
7781
7782         cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
7783         intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
7784
7785         while (vmx->emulation_required && count-- != 0) {
7786                 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
7787                         return handle_interrupt_window(&vmx->vcpu);
7788
7789                 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
7790                         return 1;
7791
7792                 err = kvm_emulate_instruction(vcpu, 0);
7793
7794                 if (err == EMULATE_USER_EXIT) {
7795                         ++vcpu->stat.mmio_exits;
7796                         ret = 0;
7797                         goto out;
7798                 }
7799
7800                 if (err != EMULATE_DONE)
7801                         goto emulation_error;
7802
7803                 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
7804                     vcpu->arch.exception.pending)
7805                         goto emulation_error;
7806
7807                 if (vcpu->arch.halt_request) {
7808                         vcpu->arch.halt_request = 0;
7809                         ret = kvm_vcpu_halt(vcpu);
7810                         goto out;
7811                 }
7812
7813                 if (signal_pending(current))
7814                         goto out;
7815                 if (need_resched())
7816                         schedule();
7817         }
7818
7819 out:
7820         return ret;
7821
7822 emulation_error:
7823         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7824         vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7825         vcpu->run->internal.ndata = 0;
7826         return 0;
7827 }
7828
7829 static void grow_ple_window(struct kvm_vcpu *vcpu)
7830 {
7831         struct vcpu_vmx *vmx = to_vmx(vcpu);
7832         int old = vmx->ple_window;
7833
7834         vmx->ple_window = __grow_ple_window(old, ple_window,
7835                                             ple_window_grow,
7836                                             ple_window_max);
7837
7838         if (vmx->ple_window != old)
7839                 vmx->ple_window_dirty = true;
7840
7841         trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
7842 }
7843
7844 static void shrink_ple_window(struct kvm_vcpu *vcpu)
7845 {
7846         struct vcpu_vmx *vmx = to_vmx(vcpu);
7847         int old = vmx->ple_window;
7848
7849         vmx->ple_window = __shrink_ple_window(old, ple_window,
7850                                               ple_window_shrink,
7851                                               ple_window);
7852
7853         if (vmx->ple_window != old)
7854                 vmx->ple_window_dirty = true;
7855
7856         trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
7857 }
7858
7859 /*
7860  * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
7861  */
7862 static void wakeup_handler(void)
7863 {
7864         struct kvm_vcpu *vcpu;
7865         int cpu = smp_processor_id();
7866
7867         spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
7868         list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
7869                         blocked_vcpu_list) {
7870                 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7871
7872                 if (pi_test_on(pi_desc) == 1)
7873                         kvm_vcpu_kick(vcpu);
7874         }
7875         spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
7876 }
7877
7878 static void vmx_enable_tdp(void)
7879 {
7880         kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
7881                 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
7882                 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
7883                 0ull, VMX_EPT_EXECUTABLE_MASK,
7884                 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
7885                 VMX_EPT_RWX_MASK, 0ull);
7886
7887         ept_set_mmio_spte_mask();
7888         kvm_enable_tdp();
7889 }
7890
7891 static __init int hardware_setup(void)
7892 {
7893         unsigned long host_bndcfgs;
7894         int r = -ENOMEM, i;
7895
7896         rdmsrl_safe(MSR_EFER, &host_efer);
7897
7898         for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7899                 kvm_define_shared_msr(i, vmx_msr_index[i]);
7900
7901         for (i = 0; i < VMX_BITMAP_NR; i++) {
7902                 vmx_bitmap[i] = (unsigned long *)__get_free_page(GFP_KERNEL);
7903                 if (!vmx_bitmap[i])
7904                         goto out;
7905         }
7906
7907         memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
7908         memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
7909
7910         if (setup_vmcs_config(&vmcs_config) < 0) {
7911                 r = -EIO;
7912                 goto out;
7913         }
7914
7915         if (boot_cpu_has(X86_FEATURE_NX))
7916                 kvm_enable_efer_bits(EFER_NX);
7917
7918         if (boot_cpu_has(X86_FEATURE_MPX)) {
7919                 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7920                 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7921         }
7922
7923         if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7924                 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7925                 enable_vpid = 0;
7926
7927         if (!cpu_has_vmx_ept() ||
7928             !cpu_has_vmx_ept_4levels() ||
7929             !cpu_has_vmx_ept_mt_wb() ||
7930             !cpu_has_vmx_invept_global())
7931                 enable_ept = 0;
7932
7933         if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7934                 enable_ept_ad_bits = 0;
7935
7936         if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7937                 enable_unrestricted_guest = 0;
7938
7939         if (!cpu_has_vmx_flexpriority())
7940                 flexpriority_enabled = 0;
7941
7942         if (!cpu_has_virtual_nmis())
7943                 enable_vnmi = 0;
7944
7945         /*
7946          * set_apic_access_page_addr() is used to reload apic access
7947          * page upon invalidation.  No need to do anything if not
7948          * using the APIC_ACCESS_ADDR VMCS field.
7949          */
7950         if (!flexpriority_enabled)
7951                 kvm_x86_ops->set_apic_access_page_addr = NULL;
7952
7953         if (!cpu_has_vmx_tpr_shadow())
7954                 kvm_x86_ops->update_cr8_intercept = NULL;
7955
7956         if (enable_ept && !cpu_has_vmx_ept_2m_page())
7957                 kvm_disable_largepages();
7958
7959 #if IS_ENABLED(CONFIG_HYPERV)
7960         if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7961             && enable_ept)
7962                 kvm_x86_ops->tlb_remote_flush = vmx_hv_remote_flush_tlb;
7963 #endif
7964
7965         if (!cpu_has_vmx_ple()) {
7966                 ple_gap = 0;
7967                 ple_window = 0;
7968                 ple_window_grow = 0;
7969                 ple_window_max = 0;
7970                 ple_window_shrink = 0;
7971         }
7972
7973         if (!cpu_has_vmx_apicv()) {
7974                 enable_apicv = 0;
7975                 kvm_x86_ops->sync_pir_to_irr = NULL;
7976         }
7977
7978         if (cpu_has_vmx_tsc_scaling()) {
7979                 kvm_has_tsc_control = true;
7980                 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7981                 kvm_tsc_scaling_ratio_frac_bits = 48;
7982         }
7983
7984         set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7985
7986         if (enable_ept)
7987                 vmx_enable_tdp();
7988         else
7989                 kvm_disable_tdp();
7990
7991         if (!nested) {
7992                 kvm_x86_ops->get_nested_state = NULL;
7993                 kvm_x86_ops->set_nested_state = NULL;
7994         }
7995
7996         /*
7997          * Only enable PML when hardware supports PML feature, and both EPT
7998          * and EPT A/D bit features are enabled -- PML depends on them to work.
7999          */
8000         if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
8001                 enable_pml = 0;
8002
8003         if (!enable_pml) {
8004                 kvm_x86_ops->slot_enable_log_dirty = NULL;
8005                 kvm_x86_ops->slot_disable_log_dirty = NULL;
8006                 kvm_x86_ops->flush_log_dirty = NULL;
8007                 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
8008         }
8009
8010         if (!cpu_has_vmx_preemption_timer())
8011                 kvm_x86_ops->request_immediate_exit = __kvm_request_immediate_exit;
8012
8013         if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
8014                 u64 vmx_msr;
8015
8016                 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
8017                 cpu_preemption_timer_multi =
8018                          vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
8019         } else {
8020                 kvm_x86_ops->set_hv_timer = NULL;
8021                 kvm_x86_ops->cancel_hv_timer = NULL;
8022         }
8023
8024         if (!cpu_has_vmx_shadow_vmcs())
8025                 enable_shadow_vmcs = 0;
8026         if (enable_shadow_vmcs)
8027                 init_vmcs_shadow_fields();
8028
8029         kvm_set_posted_intr_wakeup_handler(wakeup_handler);
8030         nested_vmx_setup_ctls_msrs(&vmcs_config.nested, enable_apicv);
8031
8032         kvm_mce_cap_supported |= MCG_LMCE_P;
8033
8034         return alloc_kvm_area();
8035
8036 out:
8037         for (i = 0; i < VMX_BITMAP_NR; i++)
8038                 free_page((unsigned long)vmx_bitmap[i]);
8039
8040     return r;
8041 }
8042
8043 static __exit void hardware_unsetup(void)
8044 {
8045         int i;
8046
8047         for (i = 0; i < VMX_BITMAP_NR; i++)
8048                 free_page((unsigned long)vmx_bitmap[i]);
8049
8050         free_kvm_area();
8051 }
8052
8053 /*
8054  * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
8055  * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
8056  */
8057 static int handle_pause(struct kvm_vcpu *vcpu)
8058 {
8059         if (!kvm_pause_in_guest(vcpu->kvm))
8060                 grow_ple_window(vcpu);
8061
8062         /*
8063          * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
8064          * VM-execution control is ignored if CPL > 0. OTOH, KVM
8065          * never set PAUSE_EXITING and just set PLE if supported,
8066          * so the vcpu must be CPL=0 if it gets a PAUSE exit.
8067          */
8068         kvm_vcpu_on_spin(vcpu, true);
8069         return kvm_skip_emulated_instruction(vcpu);
8070 }
8071
8072 static int handle_nop(struct kvm_vcpu *vcpu)
8073 {
8074         return kvm_skip_emulated_instruction(vcpu);
8075 }
8076
8077 static int handle_mwait(struct kvm_vcpu *vcpu)
8078 {
8079         printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
8080         return handle_nop(vcpu);
8081 }
8082
8083 static int handle_invalid_op(struct kvm_vcpu *vcpu)
8084 {
8085         kvm_queue_exception(vcpu, UD_VECTOR);
8086         return 1;
8087 }
8088
8089 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
8090 {
8091         return 1;
8092 }
8093
8094 static int handle_monitor(struct kvm_vcpu *vcpu)
8095 {
8096         printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
8097         return handle_nop(vcpu);
8098 }
8099
8100 /*
8101  * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
8102  * set the success or error code of an emulated VMX instruction (as specified
8103  * by Vol 2B, VMX Instruction Reference, "Conventions"), and skip the emulated
8104  * instruction.
8105  */
8106 static int nested_vmx_succeed(struct kvm_vcpu *vcpu)
8107 {
8108         vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
8109                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
8110                             X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
8111         return kvm_skip_emulated_instruction(vcpu);
8112 }
8113
8114 static int nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
8115 {
8116         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
8117                         & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
8118                             X86_EFLAGS_SF | X86_EFLAGS_OF))
8119                         | X86_EFLAGS_CF);
8120         return kvm_skip_emulated_instruction(vcpu);
8121 }
8122
8123 static int nested_vmx_failValid(struct kvm_vcpu *vcpu,
8124                                 u32 vm_instruction_error)
8125 {
8126         struct vcpu_vmx *vmx = to_vmx(vcpu);
8127
8128         /*
8129          * failValid writes the error number to the current VMCS, which
8130          * can't be done if there isn't a current VMCS.
8131          */
8132         if (vmx->nested.current_vmptr == -1ull && !vmx->nested.hv_evmcs)
8133                 return nested_vmx_failInvalid(vcpu);
8134
8135         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
8136                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
8137                             X86_EFLAGS_SF | X86_EFLAGS_OF))
8138                         | X86_EFLAGS_ZF);
8139         get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
8140         /*
8141          * We don't need to force a shadow sync because
8142          * VM_INSTRUCTION_ERROR is not shadowed
8143          */
8144         return kvm_skip_emulated_instruction(vcpu);
8145 }
8146
8147 static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
8148 {
8149         /* TODO: not to reset guest simply here. */
8150         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8151         pr_debug_ratelimited("kvm: nested vmx abort, indicator %d\n", indicator);
8152 }
8153
8154 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
8155 {
8156         struct vcpu_vmx *vmx =
8157                 container_of(timer, struct vcpu_vmx, nested.preemption_timer);
8158
8159         vmx->nested.preemption_timer_expired = true;
8160         kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
8161         kvm_vcpu_kick(&vmx->vcpu);
8162
8163         return HRTIMER_NORESTART;
8164 }
8165
8166 /*
8167  * Decode the memory-address operand of a vmx instruction, as recorded on an
8168  * exit caused by such an instruction (run by a guest hypervisor).
8169  * On success, returns 0. When the operand is invalid, returns 1 and throws
8170  * #UD or #GP.
8171  */
8172 static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
8173                                  unsigned long exit_qualification,
8174                                  u32 vmx_instruction_info, bool wr, gva_t *ret)
8175 {
8176         gva_t off;
8177         bool exn;
8178         struct kvm_segment s;
8179
8180         /*
8181          * According to Vol. 3B, "Information for VM Exits Due to Instruction
8182          * Execution", on an exit, vmx_instruction_info holds most of the
8183          * addressing components of the operand. Only the displacement part
8184          * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
8185          * For how an actual address is calculated from all these components,
8186          * refer to Vol. 1, "Operand Addressing".
8187          */
8188         int  scaling = vmx_instruction_info & 3;
8189         int  addr_size = (vmx_instruction_info >> 7) & 7;
8190         bool is_reg = vmx_instruction_info & (1u << 10);
8191         int  seg_reg = (vmx_instruction_info >> 15) & 7;
8192         int  index_reg = (vmx_instruction_info >> 18) & 0xf;
8193         bool index_is_valid = !(vmx_instruction_info & (1u << 22));
8194         int  base_reg       = (vmx_instruction_info >> 23) & 0xf;
8195         bool base_is_valid  = !(vmx_instruction_info & (1u << 27));
8196
8197         if (is_reg) {
8198                 kvm_queue_exception(vcpu, UD_VECTOR);
8199                 return 1;
8200         }
8201
8202         /* Addr = segment_base + offset */
8203         /* offset = base + [index * scale] + displacement */
8204         off = exit_qualification; /* holds the displacement */
8205         if (base_is_valid)
8206                 off += kvm_register_read(vcpu, base_reg);
8207         if (index_is_valid)
8208                 off += kvm_register_read(vcpu, index_reg)<<scaling;
8209         vmx_get_segment(vcpu, &s, seg_reg);
8210         *ret = s.base + off;
8211
8212         if (addr_size == 1) /* 32 bit */
8213                 *ret &= 0xffffffff;
8214
8215         /* Checks for #GP/#SS exceptions. */
8216         exn = false;
8217         if (is_long_mode(vcpu)) {
8218                 /* Long mode: #GP(0)/#SS(0) if the memory address is in a
8219                  * non-canonical form. This is the only check on the memory
8220                  * destination for long mode!
8221                  */
8222                 exn = is_noncanonical_address(*ret, vcpu);
8223         } else if (is_protmode(vcpu)) {
8224                 /* Protected mode: apply checks for segment validity in the
8225                  * following order:
8226                  * - segment type check (#GP(0) may be thrown)
8227                  * - usability check (#GP(0)/#SS(0))
8228                  * - limit check (#GP(0)/#SS(0))
8229                  */
8230                 if (wr)
8231                         /* #GP(0) if the destination operand is located in a
8232                          * read-only data segment or any code segment.
8233                          */
8234                         exn = ((s.type & 0xa) == 0 || (s.type & 8));
8235                 else
8236                         /* #GP(0) if the source operand is located in an
8237                          * execute-only code segment
8238                          */
8239                         exn = ((s.type & 0xa) == 8);
8240                 if (exn) {
8241                         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
8242                         return 1;
8243                 }
8244                 /* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
8245                  */
8246                 exn = (s.unusable != 0);
8247                 /* Protected mode: #GP(0)/#SS(0) if the memory
8248                  * operand is outside the segment limit.
8249                  */
8250                 exn = exn || (off + sizeof(u64) > s.limit);
8251         }
8252         if (exn) {
8253                 kvm_queue_exception_e(vcpu,
8254                                       seg_reg == VCPU_SREG_SS ?
8255                                                 SS_VECTOR : GP_VECTOR,
8256                                       0);
8257                 return 1;
8258         }
8259
8260         return 0;
8261 }
8262
8263 static int nested_vmx_get_vmptr(struct kvm_vcpu *vcpu, gpa_t *vmpointer)
8264 {
8265         gva_t gva;
8266         struct x86_exception e;
8267
8268         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
8269                         vmcs_read32(VMX_INSTRUCTION_INFO), false, &gva))
8270                 return 1;
8271
8272         if (kvm_read_guest_virt(vcpu, gva, vmpointer, sizeof(*vmpointer), &e)) {
8273                 kvm_inject_page_fault(vcpu, &e);
8274                 return 1;
8275         }
8276
8277         return 0;
8278 }
8279
8280 /*
8281  * Allocate a shadow VMCS and associate it with the currently loaded
8282  * VMCS, unless such a shadow VMCS already exists. The newly allocated
8283  * VMCS is also VMCLEARed, so that it is ready for use.
8284  */
8285 static struct vmcs *alloc_shadow_vmcs(struct kvm_vcpu *vcpu)
8286 {
8287         struct vcpu_vmx *vmx = to_vmx(vcpu);
8288         struct loaded_vmcs *loaded_vmcs = vmx->loaded_vmcs;
8289
8290         /*
8291          * We should allocate a shadow vmcs for vmcs01 only when L1
8292          * executes VMXON and free it when L1 executes VMXOFF.
8293          * As it is invalid to execute VMXON twice, we shouldn't reach
8294          * here when vmcs01 already have an allocated shadow vmcs.
8295          */
8296         WARN_ON(loaded_vmcs == &vmx->vmcs01 && loaded_vmcs->shadow_vmcs);
8297
8298         if (!loaded_vmcs->shadow_vmcs) {
8299                 loaded_vmcs->shadow_vmcs = alloc_vmcs(true);
8300                 if (loaded_vmcs->shadow_vmcs)
8301                         vmcs_clear(loaded_vmcs->shadow_vmcs);
8302         }
8303         return loaded_vmcs->shadow_vmcs;
8304 }
8305
8306 static int enter_vmx_operation(struct kvm_vcpu *vcpu)
8307 {
8308         struct vcpu_vmx *vmx = to_vmx(vcpu);
8309         int r;
8310
8311         r = alloc_loaded_vmcs(&vmx->nested.vmcs02);
8312         if (r < 0)
8313                 goto out_vmcs02;
8314
8315         vmx->nested.cached_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
8316         if (!vmx->nested.cached_vmcs12)
8317                 goto out_cached_vmcs12;
8318
8319         vmx->nested.cached_shadow_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
8320         if (!vmx->nested.cached_shadow_vmcs12)
8321                 goto out_cached_shadow_vmcs12;
8322
8323         if (enable_shadow_vmcs && !alloc_shadow_vmcs(vcpu))
8324                 goto out_shadow_vmcs;
8325
8326         hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
8327                      HRTIMER_MODE_REL_PINNED);
8328         vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
8329
8330         vmx->nested.vpid02 = allocate_vpid();
8331
8332         vmx->nested.vmcs02_initialized = false;
8333         vmx->nested.vmxon = true;
8334         return 0;
8335
8336 out_shadow_vmcs:
8337         kfree(vmx->nested.cached_shadow_vmcs12);
8338
8339 out_cached_shadow_vmcs12:
8340         kfree(vmx->nested.cached_vmcs12);
8341
8342 out_cached_vmcs12:
8343         free_loaded_vmcs(&vmx->nested.vmcs02);
8344
8345 out_vmcs02:
8346         return -ENOMEM;
8347 }
8348
8349 /*
8350  * Emulate the VMXON instruction.
8351  * Currently, we just remember that VMX is active, and do not save or even
8352  * inspect the argument to VMXON (the so-called "VMXON pointer") because we
8353  * do not currently need to store anything in that guest-allocated memory
8354  * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
8355  * argument is different from the VMXON pointer (which the spec says they do).
8356  */
8357 static int handle_vmon(struct kvm_vcpu *vcpu)
8358 {
8359         int ret;
8360         gpa_t vmptr;
8361         struct page *page;
8362         struct vcpu_vmx *vmx = to_vmx(vcpu);
8363         const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
8364                 | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
8365
8366         /*
8367          * The Intel VMX Instruction Reference lists a bunch of bits that are
8368          * prerequisite to running VMXON, most notably cr4.VMXE must be set to
8369          * 1 (see vmx_set_cr4() for when we allow the guest to set this).
8370          * Otherwise, we should fail with #UD.  But most faulting conditions
8371          * have already been checked by hardware, prior to the VM-exit for
8372          * VMXON.  We do test guest cr4.VMXE because processor CR4 always has
8373          * that bit set to 1 in non-root mode.
8374          */
8375         if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) {
8376                 kvm_queue_exception(vcpu, UD_VECTOR);
8377                 return 1;
8378         }
8379
8380         /* CPL=0 must be checked manually. */
8381         if (vmx_get_cpl(vcpu)) {
8382                 kvm_inject_gp(vcpu, 0);
8383                 return 1;
8384         }
8385
8386         if (vmx->nested.vmxon)
8387                 return nested_vmx_failValid(vcpu,
8388                         VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
8389
8390         if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
8391                         != VMXON_NEEDED_FEATURES) {
8392                 kvm_inject_gp(vcpu, 0);
8393                 return 1;
8394         }
8395
8396         if (nested_vmx_get_vmptr(vcpu, &vmptr))
8397                 return 1;
8398
8399         /*
8400          * SDM 3: 24.11.5
8401          * The first 4 bytes of VMXON region contain the supported
8402          * VMCS revision identifier
8403          *
8404          * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
8405          * which replaces physical address width with 32
8406          */
8407         if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu)))
8408                 return nested_vmx_failInvalid(vcpu);
8409
8410         page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
8411         if (is_error_page(page))
8412                 return nested_vmx_failInvalid(vcpu);
8413
8414         if (*(u32 *)kmap(page) != VMCS12_REVISION) {
8415                 kunmap(page);
8416                 kvm_release_page_clean(page);
8417                 return nested_vmx_failInvalid(vcpu);
8418         }
8419         kunmap(page);
8420         kvm_release_page_clean(page);
8421
8422         vmx->nested.vmxon_ptr = vmptr;
8423         ret = enter_vmx_operation(vcpu);
8424         if (ret)
8425                 return ret;
8426
8427         return nested_vmx_succeed(vcpu);
8428 }
8429
8430 /*
8431  * Intel's VMX Instruction Reference specifies a common set of prerequisites
8432  * for running VMX instructions (except VMXON, whose prerequisites are
8433  * slightly different). It also specifies what exception to inject otherwise.
8434  * Note that many of these exceptions have priority over VM exits, so they
8435  * don't have to be checked again here.
8436  */
8437 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
8438 {
8439         if (!to_vmx(vcpu)->nested.vmxon) {
8440                 kvm_queue_exception(vcpu, UD_VECTOR);
8441                 return 0;
8442         }
8443
8444         if (vmx_get_cpl(vcpu)) {
8445                 kvm_inject_gp(vcpu, 0);
8446                 return 0;
8447         }
8448
8449         return 1;
8450 }
8451
8452 static void vmx_disable_shadow_vmcs(struct vcpu_vmx *vmx)
8453 {
8454         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL, SECONDARY_EXEC_SHADOW_VMCS);
8455         vmcs_write64(VMCS_LINK_POINTER, -1ull);
8456 }
8457
8458 static inline void nested_release_evmcs(struct kvm_vcpu *vcpu)
8459 {
8460         struct vcpu_vmx *vmx = to_vmx(vcpu);
8461
8462         if (!vmx->nested.hv_evmcs)
8463                 return;
8464
8465         kunmap(vmx->nested.hv_evmcs_page);
8466         kvm_release_page_dirty(vmx->nested.hv_evmcs_page);
8467         vmx->nested.hv_evmcs_vmptr = -1ull;
8468         vmx->nested.hv_evmcs_page = NULL;
8469         vmx->nested.hv_evmcs = NULL;
8470 }
8471
8472 static inline void nested_release_vmcs12(struct kvm_vcpu *vcpu)
8473 {
8474         struct vcpu_vmx *vmx = to_vmx(vcpu);
8475
8476         if (vmx->nested.current_vmptr == -1ull)
8477                 return;
8478
8479         if (enable_shadow_vmcs) {
8480                 /* copy to memory all shadowed fields in case
8481                    they were modified */
8482                 copy_shadow_to_vmcs12(vmx);
8483                 vmx->nested.need_vmcs12_sync = false;
8484                 vmx_disable_shadow_vmcs(vmx);
8485         }
8486         vmx->nested.posted_intr_nv = -1;
8487
8488         /* Flush VMCS12 to guest memory */
8489         kvm_vcpu_write_guest_page(vcpu,
8490                                   vmx->nested.current_vmptr >> PAGE_SHIFT,
8491                                   vmx->nested.cached_vmcs12, 0, VMCS12_SIZE);
8492
8493         kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
8494
8495         vmx->nested.current_vmptr = -1ull;
8496 }
8497
8498 /*
8499  * Free whatever needs to be freed from vmx->nested when L1 goes down, or
8500  * just stops using VMX.
8501  */
8502 static void free_nested(struct kvm_vcpu *vcpu)
8503 {
8504         struct vcpu_vmx *vmx = to_vmx(vcpu);
8505
8506         if (!vmx->nested.vmxon && !vmx->nested.smm.vmxon)
8507                 return;
8508
8509         vmx->nested.vmxon = false;
8510         vmx->nested.smm.vmxon = false;
8511         free_vpid(vmx->nested.vpid02);
8512         vmx->nested.posted_intr_nv = -1;
8513         vmx->nested.current_vmptr = -1ull;
8514         if (enable_shadow_vmcs) {
8515                 vmx_disable_shadow_vmcs(vmx);
8516                 vmcs_clear(vmx->vmcs01.shadow_vmcs);
8517                 free_vmcs(vmx->vmcs01.shadow_vmcs);
8518                 vmx->vmcs01.shadow_vmcs = NULL;
8519         }
8520         kfree(vmx->nested.cached_vmcs12);
8521         kfree(vmx->nested.cached_shadow_vmcs12);
8522         /* Unpin physical memory we referred to in the vmcs02 */
8523         if (vmx->nested.apic_access_page) {
8524                 kvm_release_page_dirty(vmx->nested.apic_access_page);
8525                 vmx->nested.apic_access_page = NULL;
8526         }
8527         if (vmx->nested.virtual_apic_page) {
8528                 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
8529                 vmx->nested.virtual_apic_page = NULL;
8530         }
8531         if (vmx->nested.pi_desc_page) {
8532                 kunmap(vmx->nested.pi_desc_page);
8533                 kvm_release_page_dirty(vmx->nested.pi_desc_page);
8534                 vmx->nested.pi_desc_page = NULL;
8535                 vmx->nested.pi_desc = NULL;
8536         }
8537
8538         kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
8539
8540         nested_release_evmcs(vcpu);
8541
8542         free_loaded_vmcs(&vmx->nested.vmcs02);
8543 }
8544
8545 /* Emulate the VMXOFF instruction */
8546 static int handle_vmoff(struct kvm_vcpu *vcpu)
8547 {
8548         if (!nested_vmx_check_permission(vcpu))
8549                 return 1;
8550         free_nested(vcpu);
8551         return nested_vmx_succeed(vcpu);
8552 }
8553
8554 /* Emulate the VMCLEAR instruction */
8555 static int handle_vmclear(struct kvm_vcpu *vcpu)
8556 {
8557         struct vcpu_vmx *vmx = to_vmx(vcpu);
8558         u32 zero = 0;
8559         gpa_t vmptr;
8560
8561         if (!nested_vmx_check_permission(vcpu))
8562                 return 1;
8563
8564         if (nested_vmx_get_vmptr(vcpu, &vmptr))
8565                 return 1;
8566
8567         if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu)))
8568                 return nested_vmx_failValid(vcpu,
8569                         VMXERR_VMCLEAR_INVALID_ADDRESS);
8570
8571         if (vmptr == vmx->nested.vmxon_ptr)
8572                 return nested_vmx_failValid(vcpu,
8573                         VMXERR_VMCLEAR_VMXON_POINTER);
8574
8575         if (vmx->nested.hv_evmcs_page) {
8576                 if (vmptr == vmx->nested.hv_evmcs_vmptr)
8577                         nested_release_evmcs(vcpu);
8578         } else {
8579                 if (vmptr == vmx->nested.current_vmptr)
8580                         nested_release_vmcs12(vcpu);
8581
8582                 kvm_vcpu_write_guest(vcpu,
8583                                      vmptr + offsetof(struct vmcs12,
8584                                                       launch_state),
8585                                      &zero, sizeof(zero));
8586         }
8587
8588         return nested_vmx_succeed(vcpu);
8589 }
8590
8591 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
8592
8593 /* Emulate the VMLAUNCH instruction */
8594 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
8595 {
8596         return nested_vmx_run(vcpu, true);
8597 }
8598
8599 /* Emulate the VMRESUME instruction */
8600 static int handle_vmresume(struct kvm_vcpu *vcpu)
8601 {
8602
8603         return nested_vmx_run(vcpu, false);
8604 }
8605
8606 /*
8607  * Read a vmcs12 field. Since these can have varying lengths and we return
8608  * one type, we chose the biggest type (u64) and zero-extend the return value
8609  * to that size. Note that the caller, handle_vmread, might need to use only
8610  * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
8611  * 64-bit fields are to be returned).
8612  */
8613 static inline int vmcs12_read_any(struct vmcs12 *vmcs12,
8614                                   unsigned long field, u64 *ret)
8615 {
8616         short offset = vmcs_field_to_offset(field);
8617         char *p;
8618
8619         if (offset < 0)
8620                 return offset;
8621
8622         p = (char *)vmcs12 + offset;
8623
8624         switch (vmcs_field_width(field)) {
8625         case VMCS_FIELD_WIDTH_NATURAL_WIDTH:
8626                 *ret = *((natural_width *)p);
8627                 return 0;
8628         case VMCS_FIELD_WIDTH_U16:
8629                 *ret = *((u16 *)p);
8630                 return 0;
8631         case VMCS_FIELD_WIDTH_U32:
8632                 *ret = *((u32 *)p);
8633                 return 0;
8634         case VMCS_FIELD_WIDTH_U64:
8635                 *ret = *((u64 *)p);
8636                 return 0;
8637         default:
8638                 WARN_ON(1);
8639                 return -ENOENT;
8640         }
8641 }
8642
8643
8644 static inline int vmcs12_write_any(struct vmcs12 *vmcs12,
8645                                    unsigned long field, u64 field_value){
8646         short offset = vmcs_field_to_offset(field);
8647         char *p = (char *)vmcs12 + offset;
8648         if (offset < 0)
8649                 return offset;
8650
8651         switch (vmcs_field_width(field)) {
8652         case VMCS_FIELD_WIDTH_U16:
8653                 *(u16 *)p = field_value;
8654                 return 0;
8655         case VMCS_FIELD_WIDTH_U32:
8656                 *(u32 *)p = field_value;
8657                 return 0;
8658         case VMCS_FIELD_WIDTH_U64:
8659                 *(u64 *)p = field_value;
8660                 return 0;
8661         case VMCS_FIELD_WIDTH_NATURAL_WIDTH:
8662                 *(natural_width *)p = field_value;
8663                 return 0;
8664         default:
8665                 WARN_ON(1);
8666                 return -ENOENT;
8667         }
8668
8669 }
8670
8671 static int copy_enlightened_to_vmcs12(struct vcpu_vmx *vmx)
8672 {
8673         struct vmcs12 *vmcs12 = vmx->nested.cached_vmcs12;
8674         struct hv_enlightened_vmcs *evmcs = vmx->nested.hv_evmcs;
8675
8676         /* HV_VMX_ENLIGHTENED_CLEAN_FIELD_NONE */
8677         vmcs12->tpr_threshold = evmcs->tpr_threshold;
8678         vmcs12->guest_rip = evmcs->guest_rip;
8679
8680         if (unlikely(!(evmcs->hv_clean_fields &
8681                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_BASIC))) {
8682                 vmcs12->guest_rsp = evmcs->guest_rsp;
8683                 vmcs12->guest_rflags = evmcs->guest_rflags;
8684                 vmcs12->guest_interruptibility_info =
8685                         evmcs->guest_interruptibility_info;
8686         }
8687
8688         if (unlikely(!(evmcs->hv_clean_fields &
8689                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_PROC))) {
8690                 vmcs12->cpu_based_vm_exec_control =
8691                         evmcs->cpu_based_vm_exec_control;
8692         }
8693
8694         if (unlikely(!(evmcs->hv_clean_fields &
8695                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_PROC))) {
8696                 vmcs12->exception_bitmap = evmcs->exception_bitmap;
8697         }
8698
8699         if (unlikely(!(evmcs->hv_clean_fields &
8700                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_ENTRY))) {
8701                 vmcs12->vm_entry_controls = evmcs->vm_entry_controls;
8702         }
8703
8704         if (unlikely(!(evmcs->hv_clean_fields &
8705                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_EVENT))) {
8706                 vmcs12->vm_entry_intr_info_field =
8707                         evmcs->vm_entry_intr_info_field;
8708                 vmcs12->vm_entry_exception_error_code =
8709                         evmcs->vm_entry_exception_error_code;
8710                 vmcs12->vm_entry_instruction_len =
8711                         evmcs->vm_entry_instruction_len;
8712         }
8713
8714         if (unlikely(!(evmcs->hv_clean_fields &
8715                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_HOST_GRP1))) {
8716                 vmcs12->host_ia32_pat = evmcs->host_ia32_pat;
8717                 vmcs12->host_ia32_efer = evmcs->host_ia32_efer;
8718                 vmcs12->host_cr0 = evmcs->host_cr0;
8719                 vmcs12->host_cr3 = evmcs->host_cr3;
8720                 vmcs12->host_cr4 = evmcs->host_cr4;
8721                 vmcs12->host_ia32_sysenter_esp = evmcs->host_ia32_sysenter_esp;
8722                 vmcs12->host_ia32_sysenter_eip = evmcs->host_ia32_sysenter_eip;
8723                 vmcs12->host_rip = evmcs->host_rip;
8724                 vmcs12->host_ia32_sysenter_cs = evmcs->host_ia32_sysenter_cs;
8725                 vmcs12->host_es_selector = evmcs->host_es_selector;
8726                 vmcs12->host_cs_selector = evmcs->host_cs_selector;
8727                 vmcs12->host_ss_selector = evmcs->host_ss_selector;
8728                 vmcs12->host_ds_selector = evmcs->host_ds_selector;
8729                 vmcs12->host_fs_selector = evmcs->host_fs_selector;
8730                 vmcs12->host_gs_selector = evmcs->host_gs_selector;
8731                 vmcs12->host_tr_selector = evmcs->host_tr_selector;
8732         }
8733
8734         if (unlikely(!(evmcs->hv_clean_fields &
8735                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_HOST_GRP1))) {
8736                 vmcs12->pin_based_vm_exec_control =
8737                         evmcs->pin_based_vm_exec_control;
8738                 vmcs12->vm_exit_controls = evmcs->vm_exit_controls;
8739                 vmcs12->secondary_vm_exec_control =
8740                         evmcs->secondary_vm_exec_control;
8741         }
8742
8743         if (unlikely(!(evmcs->hv_clean_fields &
8744                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_IO_BITMAP))) {
8745                 vmcs12->io_bitmap_a = evmcs->io_bitmap_a;
8746                 vmcs12->io_bitmap_b = evmcs->io_bitmap_b;
8747         }
8748
8749         if (unlikely(!(evmcs->hv_clean_fields &
8750                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP))) {
8751                 vmcs12->msr_bitmap = evmcs->msr_bitmap;
8752         }
8753
8754         if (unlikely(!(evmcs->hv_clean_fields &
8755                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2))) {
8756                 vmcs12->guest_es_base = evmcs->guest_es_base;
8757                 vmcs12->guest_cs_base = evmcs->guest_cs_base;
8758                 vmcs12->guest_ss_base = evmcs->guest_ss_base;
8759                 vmcs12->guest_ds_base = evmcs->guest_ds_base;
8760                 vmcs12->guest_fs_base = evmcs->guest_fs_base;
8761                 vmcs12->guest_gs_base = evmcs->guest_gs_base;
8762                 vmcs12->guest_ldtr_base = evmcs->guest_ldtr_base;
8763                 vmcs12->guest_tr_base = evmcs->guest_tr_base;
8764                 vmcs12->guest_gdtr_base = evmcs->guest_gdtr_base;
8765                 vmcs12->guest_idtr_base = evmcs->guest_idtr_base;
8766                 vmcs12->guest_es_limit = evmcs->guest_es_limit;
8767                 vmcs12->guest_cs_limit = evmcs->guest_cs_limit;
8768                 vmcs12->guest_ss_limit = evmcs->guest_ss_limit;
8769                 vmcs12->guest_ds_limit = evmcs->guest_ds_limit;
8770                 vmcs12->guest_fs_limit = evmcs->guest_fs_limit;
8771                 vmcs12->guest_gs_limit = evmcs->guest_gs_limit;
8772                 vmcs12->guest_ldtr_limit = evmcs->guest_ldtr_limit;
8773                 vmcs12->guest_tr_limit = evmcs->guest_tr_limit;
8774                 vmcs12->guest_gdtr_limit = evmcs->guest_gdtr_limit;
8775                 vmcs12->guest_idtr_limit = evmcs->guest_idtr_limit;
8776                 vmcs12->guest_es_ar_bytes = evmcs->guest_es_ar_bytes;
8777                 vmcs12->guest_cs_ar_bytes = evmcs->guest_cs_ar_bytes;
8778                 vmcs12->guest_ss_ar_bytes = evmcs->guest_ss_ar_bytes;
8779                 vmcs12->guest_ds_ar_bytes = evmcs->guest_ds_ar_bytes;
8780                 vmcs12->guest_fs_ar_bytes = evmcs->guest_fs_ar_bytes;
8781                 vmcs12->guest_gs_ar_bytes = evmcs->guest_gs_ar_bytes;
8782                 vmcs12->guest_ldtr_ar_bytes = evmcs->guest_ldtr_ar_bytes;
8783                 vmcs12->guest_tr_ar_bytes = evmcs->guest_tr_ar_bytes;
8784                 vmcs12->guest_es_selector = evmcs->guest_es_selector;
8785                 vmcs12->guest_cs_selector = evmcs->guest_cs_selector;
8786                 vmcs12->guest_ss_selector = evmcs->guest_ss_selector;
8787                 vmcs12->guest_ds_selector = evmcs->guest_ds_selector;
8788                 vmcs12->guest_fs_selector = evmcs->guest_fs_selector;
8789                 vmcs12->guest_gs_selector = evmcs->guest_gs_selector;
8790                 vmcs12->guest_ldtr_selector = evmcs->guest_ldtr_selector;
8791                 vmcs12->guest_tr_selector = evmcs->guest_tr_selector;
8792         }
8793
8794         if (unlikely(!(evmcs->hv_clean_fields &
8795                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_GRP2))) {
8796                 vmcs12->tsc_offset = evmcs->tsc_offset;
8797                 vmcs12->virtual_apic_page_addr = evmcs->virtual_apic_page_addr;
8798                 vmcs12->xss_exit_bitmap = evmcs->xss_exit_bitmap;
8799         }
8800
8801         if (unlikely(!(evmcs->hv_clean_fields &
8802                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CRDR))) {
8803                 vmcs12->cr0_guest_host_mask = evmcs->cr0_guest_host_mask;
8804                 vmcs12->cr4_guest_host_mask = evmcs->cr4_guest_host_mask;
8805                 vmcs12->cr0_read_shadow = evmcs->cr0_read_shadow;
8806                 vmcs12->cr4_read_shadow = evmcs->cr4_read_shadow;
8807                 vmcs12->guest_cr0 = evmcs->guest_cr0;
8808                 vmcs12->guest_cr3 = evmcs->guest_cr3;
8809                 vmcs12->guest_cr4 = evmcs->guest_cr4;
8810                 vmcs12->guest_dr7 = evmcs->guest_dr7;
8811         }
8812
8813         if (unlikely(!(evmcs->hv_clean_fields &
8814                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_HOST_POINTER))) {
8815                 vmcs12->host_fs_base = evmcs->host_fs_base;
8816                 vmcs12->host_gs_base = evmcs->host_gs_base;
8817                 vmcs12->host_tr_base = evmcs->host_tr_base;
8818                 vmcs12->host_gdtr_base = evmcs->host_gdtr_base;
8819                 vmcs12->host_idtr_base = evmcs->host_idtr_base;
8820                 vmcs12->host_rsp = evmcs->host_rsp;
8821         }
8822
8823         if (unlikely(!(evmcs->hv_clean_fields &
8824                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_XLAT))) {
8825                 vmcs12->ept_pointer = evmcs->ept_pointer;
8826                 vmcs12->virtual_processor_id = evmcs->virtual_processor_id;
8827         }
8828
8829         if (unlikely(!(evmcs->hv_clean_fields &
8830                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1))) {
8831                 vmcs12->vmcs_link_pointer = evmcs->vmcs_link_pointer;
8832                 vmcs12->guest_ia32_debugctl = evmcs->guest_ia32_debugctl;
8833                 vmcs12->guest_ia32_pat = evmcs->guest_ia32_pat;
8834                 vmcs12->guest_ia32_efer = evmcs->guest_ia32_efer;
8835                 vmcs12->guest_pdptr0 = evmcs->guest_pdptr0;
8836                 vmcs12->guest_pdptr1 = evmcs->guest_pdptr1;
8837                 vmcs12->guest_pdptr2 = evmcs->guest_pdptr2;
8838                 vmcs12->guest_pdptr3 = evmcs->guest_pdptr3;
8839                 vmcs12->guest_pending_dbg_exceptions =
8840                         evmcs->guest_pending_dbg_exceptions;
8841                 vmcs12->guest_sysenter_esp = evmcs->guest_sysenter_esp;
8842                 vmcs12->guest_sysenter_eip = evmcs->guest_sysenter_eip;
8843                 vmcs12->guest_bndcfgs = evmcs->guest_bndcfgs;
8844                 vmcs12->guest_activity_state = evmcs->guest_activity_state;
8845                 vmcs12->guest_sysenter_cs = evmcs->guest_sysenter_cs;
8846         }
8847
8848         /*
8849          * Not used?
8850          * vmcs12->vm_exit_msr_store_addr = evmcs->vm_exit_msr_store_addr;
8851          * vmcs12->vm_exit_msr_load_addr = evmcs->vm_exit_msr_load_addr;
8852          * vmcs12->vm_entry_msr_load_addr = evmcs->vm_entry_msr_load_addr;
8853          * vmcs12->cr3_target_value0 = evmcs->cr3_target_value0;
8854          * vmcs12->cr3_target_value1 = evmcs->cr3_target_value1;
8855          * vmcs12->cr3_target_value2 = evmcs->cr3_target_value2;
8856          * vmcs12->cr3_target_value3 = evmcs->cr3_target_value3;
8857          * vmcs12->page_fault_error_code_mask =
8858          *              evmcs->page_fault_error_code_mask;
8859          * vmcs12->page_fault_error_code_match =
8860          *              evmcs->page_fault_error_code_match;
8861          * vmcs12->cr3_target_count = evmcs->cr3_target_count;
8862          * vmcs12->vm_exit_msr_store_count = evmcs->vm_exit_msr_store_count;
8863          * vmcs12->vm_exit_msr_load_count = evmcs->vm_exit_msr_load_count;
8864          * vmcs12->vm_entry_msr_load_count = evmcs->vm_entry_msr_load_count;
8865          */
8866
8867         /*
8868          * Read only fields:
8869          * vmcs12->guest_physical_address = evmcs->guest_physical_address;
8870          * vmcs12->vm_instruction_error = evmcs->vm_instruction_error;
8871          * vmcs12->vm_exit_reason = evmcs->vm_exit_reason;
8872          * vmcs12->vm_exit_intr_info = evmcs->vm_exit_intr_info;
8873          * vmcs12->vm_exit_intr_error_code = evmcs->vm_exit_intr_error_code;
8874          * vmcs12->idt_vectoring_info_field = evmcs->idt_vectoring_info_field;
8875          * vmcs12->idt_vectoring_error_code = evmcs->idt_vectoring_error_code;
8876          * vmcs12->vm_exit_instruction_len = evmcs->vm_exit_instruction_len;
8877          * vmcs12->vmx_instruction_info = evmcs->vmx_instruction_info;
8878          * vmcs12->exit_qualification = evmcs->exit_qualification;
8879          * vmcs12->guest_linear_address = evmcs->guest_linear_address;
8880          *
8881          * Not present in struct vmcs12:
8882          * vmcs12->exit_io_instruction_ecx = evmcs->exit_io_instruction_ecx;
8883          * vmcs12->exit_io_instruction_esi = evmcs->exit_io_instruction_esi;
8884          * vmcs12->exit_io_instruction_edi = evmcs->exit_io_instruction_edi;
8885          * vmcs12->exit_io_instruction_eip = evmcs->exit_io_instruction_eip;
8886          */
8887
8888         return 0;
8889 }
8890
8891 static int copy_vmcs12_to_enlightened(struct vcpu_vmx *vmx)
8892 {
8893         struct vmcs12 *vmcs12 = vmx->nested.cached_vmcs12;
8894         struct hv_enlightened_vmcs *evmcs = vmx->nested.hv_evmcs;
8895
8896         /*
8897          * Should not be changed by KVM:
8898          *
8899          * evmcs->host_es_selector = vmcs12->host_es_selector;
8900          * evmcs->host_cs_selector = vmcs12->host_cs_selector;
8901          * evmcs->host_ss_selector = vmcs12->host_ss_selector;
8902          * evmcs->host_ds_selector = vmcs12->host_ds_selector;
8903          * evmcs->host_fs_selector = vmcs12->host_fs_selector;
8904          * evmcs->host_gs_selector = vmcs12->host_gs_selector;
8905          * evmcs->host_tr_selector = vmcs12->host_tr_selector;
8906          * evmcs->host_ia32_pat = vmcs12->host_ia32_pat;
8907          * evmcs->host_ia32_efer = vmcs12->host_ia32_efer;
8908          * evmcs->host_cr0 = vmcs12->host_cr0;
8909          * evmcs->host_cr3 = vmcs12->host_cr3;
8910          * evmcs->host_cr4 = vmcs12->host_cr4;
8911          * evmcs->host_ia32_sysenter_esp = vmcs12->host_ia32_sysenter_esp;
8912          * evmcs->host_ia32_sysenter_eip = vmcs12->host_ia32_sysenter_eip;
8913          * evmcs->host_rip = vmcs12->host_rip;
8914          * evmcs->host_ia32_sysenter_cs = vmcs12->host_ia32_sysenter_cs;
8915          * evmcs->host_fs_base = vmcs12->host_fs_base;
8916          * evmcs->host_gs_base = vmcs12->host_gs_base;
8917          * evmcs->host_tr_base = vmcs12->host_tr_base;
8918          * evmcs->host_gdtr_base = vmcs12->host_gdtr_base;
8919          * evmcs->host_idtr_base = vmcs12->host_idtr_base;
8920          * evmcs->host_rsp = vmcs12->host_rsp;
8921          * sync_vmcs12() doesn't read these:
8922          * evmcs->io_bitmap_a = vmcs12->io_bitmap_a;
8923          * evmcs->io_bitmap_b = vmcs12->io_bitmap_b;
8924          * evmcs->msr_bitmap = vmcs12->msr_bitmap;
8925          * evmcs->ept_pointer = vmcs12->ept_pointer;
8926          * evmcs->xss_exit_bitmap = vmcs12->xss_exit_bitmap;
8927          * evmcs->vm_exit_msr_store_addr = vmcs12->vm_exit_msr_store_addr;
8928          * evmcs->vm_exit_msr_load_addr = vmcs12->vm_exit_msr_load_addr;
8929          * evmcs->vm_entry_msr_load_addr = vmcs12->vm_entry_msr_load_addr;
8930          * evmcs->cr3_target_value0 = vmcs12->cr3_target_value0;
8931          * evmcs->cr3_target_value1 = vmcs12->cr3_target_value1;
8932          * evmcs->cr3_target_value2 = vmcs12->cr3_target_value2;
8933          * evmcs->cr3_target_value3 = vmcs12->cr3_target_value3;
8934          * evmcs->tpr_threshold = vmcs12->tpr_threshold;
8935          * evmcs->virtual_processor_id = vmcs12->virtual_processor_id;
8936          * evmcs->exception_bitmap = vmcs12->exception_bitmap;
8937          * evmcs->vmcs_link_pointer = vmcs12->vmcs_link_pointer;
8938          * evmcs->pin_based_vm_exec_control = vmcs12->pin_based_vm_exec_control;
8939          * evmcs->vm_exit_controls = vmcs12->vm_exit_controls;
8940          * evmcs->secondary_vm_exec_control = vmcs12->secondary_vm_exec_control;
8941          * evmcs->page_fault_error_code_mask =
8942          *              vmcs12->page_fault_error_code_mask;
8943          * evmcs->page_fault_error_code_match =
8944          *              vmcs12->page_fault_error_code_match;
8945          * evmcs->cr3_target_count = vmcs12->cr3_target_count;
8946          * evmcs->virtual_apic_page_addr = vmcs12->virtual_apic_page_addr;
8947          * evmcs->tsc_offset = vmcs12->tsc_offset;
8948          * evmcs->guest_ia32_debugctl = vmcs12->guest_ia32_debugctl;
8949          * evmcs->cr0_guest_host_mask = vmcs12->cr0_guest_host_mask;
8950          * evmcs->cr4_guest_host_mask = vmcs12->cr4_guest_host_mask;
8951          * evmcs->cr0_read_shadow = vmcs12->cr0_read_shadow;
8952          * evmcs->cr4_read_shadow = vmcs12->cr4_read_shadow;
8953          * evmcs->vm_exit_msr_store_count = vmcs12->vm_exit_msr_store_count;
8954          * evmcs->vm_exit_msr_load_count = vmcs12->vm_exit_msr_load_count;
8955          * evmcs->vm_entry_msr_load_count = vmcs12->vm_entry_msr_load_count;
8956          *
8957          * Not present in struct vmcs12:
8958          * evmcs->exit_io_instruction_ecx = vmcs12->exit_io_instruction_ecx;
8959          * evmcs->exit_io_instruction_esi = vmcs12->exit_io_instruction_esi;
8960          * evmcs->exit_io_instruction_edi = vmcs12->exit_io_instruction_edi;
8961          * evmcs->exit_io_instruction_eip = vmcs12->exit_io_instruction_eip;
8962          */
8963
8964         evmcs->guest_es_selector = vmcs12->guest_es_selector;
8965         evmcs->guest_cs_selector = vmcs12->guest_cs_selector;
8966         evmcs->guest_ss_selector = vmcs12->guest_ss_selector;
8967         evmcs->guest_ds_selector = vmcs12->guest_ds_selector;
8968         evmcs->guest_fs_selector = vmcs12->guest_fs_selector;
8969         evmcs->guest_gs_selector = vmcs12->guest_gs_selector;
8970         evmcs->guest_ldtr_selector = vmcs12->guest_ldtr_selector;
8971         evmcs->guest_tr_selector = vmcs12->guest_tr_selector;
8972
8973         evmcs->guest_es_limit = vmcs12->guest_es_limit;
8974         evmcs->guest_cs_limit = vmcs12->guest_cs_limit;
8975         evmcs->guest_ss_limit = vmcs12->guest_ss_limit;
8976         evmcs->guest_ds_limit = vmcs12->guest_ds_limit;
8977         evmcs->guest_fs_limit = vmcs12->guest_fs_limit;
8978         evmcs->guest_gs_limit = vmcs12->guest_gs_limit;
8979         evmcs->guest_ldtr_limit = vmcs12->guest_ldtr_limit;
8980         evmcs->guest_tr_limit = vmcs12->guest_tr_limit;
8981         evmcs->guest_gdtr_limit = vmcs12->guest_gdtr_limit;
8982         evmcs->guest_idtr_limit = vmcs12->guest_idtr_limit;
8983
8984         evmcs->guest_es_ar_bytes = vmcs12->guest_es_ar_bytes;
8985         evmcs->guest_cs_ar_bytes = vmcs12->guest_cs_ar_bytes;
8986         evmcs->guest_ss_ar_bytes = vmcs12->guest_ss_ar_bytes;
8987         evmcs->guest_ds_ar_bytes = vmcs12->guest_ds_ar_bytes;
8988         evmcs->guest_fs_ar_bytes = vmcs12->guest_fs_ar_bytes;
8989         evmcs->guest_gs_ar_bytes = vmcs12->guest_gs_ar_bytes;
8990         evmcs->guest_ldtr_ar_bytes = vmcs12->guest_ldtr_ar_bytes;
8991         evmcs->guest_tr_ar_bytes = vmcs12->guest_tr_ar_bytes;
8992
8993         evmcs->guest_es_base = vmcs12->guest_es_base;
8994         evmcs->guest_cs_base = vmcs12->guest_cs_base;
8995         evmcs->guest_ss_base = vmcs12->guest_ss_base;
8996         evmcs->guest_ds_base = vmcs12->guest_ds_base;
8997         evmcs->guest_fs_base = vmcs12->guest_fs_base;
8998         evmcs->guest_gs_base = vmcs12->guest_gs_base;
8999         evmcs->guest_ldtr_base = vmcs12->guest_ldtr_base;
9000         evmcs->guest_tr_base = vmcs12->guest_tr_base;
9001         evmcs->guest_gdtr_base = vmcs12->guest_gdtr_base;
9002         evmcs->guest_idtr_base = vmcs12->guest_idtr_base;
9003
9004         evmcs->guest_ia32_pat = vmcs12->guest_ia32_pat;
9005         evmcs->guest_ia32_efer = vmcs12->guest_ia32_efer;
9006
9007         evmcs->guest_pdptr0 = vmcs12->guest_pdptr0;
9008         evmcs->guest_pdptr1 = vmcs12->guest_pdptr1;
9009         evmcs->guest_pdptr2 = vmcs12->guest_pdptr2;
9010         evmcs->guest_pdptr3 = vmcs12->guest_pdptr3;
9011
9012         evmcs->guest_pending_dbg_exceptions =
9013                 vmcs12->guest_pending_dbg_exceptions;
9014         evmcs->guest_sysenter_esp = vmcs12->guest_sysenter_esp;
9015         evmcs->guest_sysenter_eip = vmcs12->guest_sysenter_eip;
9016
9017         evmcs->guest_activity_state = vmcs12->guest_activity_state;
9018         evmcs->guest_sysenter_cs = vmcs12->guest_sysenter_cs;
9019
9020         evmcs->guest_cr0 = vmcs12->guest_cr0;
9021         evmcs->guest_cr3 = vmcs12->guest_cr3;
9022         evmcs->guest_cr4 = vmcs12->guest_cr4;
9023         evmcs->guest_dr7 = vmcs12->guest_dr7;
9024
9025         evmcs->guest_physical_address = vmcs12->guest_physical_address;
9026
9027         evmcs->vm_instruction_error = vmcs12->vm_instruction_error;
9028         evmcs->vm_exit_reason = vmcs12->vm_exit_reason;
9029         evmcs->vm_exit_intr_info = vmcs12->vm_exit_intr_info;
9030         evmcs->vm_exit_intr_error_code = vmcs12->vm_exit_intr_error_code;
9031         evmcs->idt_vectoring_info_field = vmcs12->idt_vectoring_info_field;
9032         evmcs->idt_vectoring_error_code = vmcs12->idt_vectoring_error_code;
9033         evmcs->vm_exit_instruction_len = vmcs12->vm_exit_instruction_len;
9034         evmcs->vmx_instruction_info = vmcs12->vmx_instruction_info;
9035
9036         evmcs->exit_qualification = vmcs12->exit_qualification;
9037
9038         evmcs->guest_linear_address = vmcs12->guest_linear_address;
9039         evmcs->guest_rsp = vmcs12->guest_rsp;
9040         evmcs->guest_rflags = vmcs12->guest_rflags;
9041
9042         evmcs->guest_interruptibility_info =
9043                 vmcs12->guest_interruptibility_info;
9044         evmcs->cpu_based_vm_exec_control = vmcs12->cpu_based_vm_exec_control;
9045         evmcs->vm_entry_controls = vmcs12->vm_entry_controls;
9046         evmcs->vm_entry_intr_info_field = vmcs12->vm_entry_intr_info_field;
9047         evmcs->vm_entry_exception_error_code =
9048                 vmcs12->vm_entry_exception_error_code;
9049         evmcs->vm_entry_instruction_len = vmcs12->vm_entry_instruction_len;
9050
9051         evmcs->guest_rip = vmcs12->guest_rip;
9052
9053         evmcs->guest_bndcfgs = vmcs12->guest_bndcfgs;
9054
9055         return 0;
9056 }
9057
9058 /*
9059  * Copy the writable VMCS shadow fields back to the VMCS12, in case
9060  * they have been modified by the L1 guest. Note that the "read-only"
9061  * VM-exit information fields are actually writable if the vCPU is
9062  * configured to support "VMWRITE to any supported field in the VMCS."
9063  */
9064 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
9065 {
9066         const u16 *fields[] = {
9067                 shadow_read_write_fields,
9068                 shadow_read_only_fields
9069         };
9070         const int max_fields[] = {
9071                 max_shadow_read_write_fields,
9072                 max_shadow_read_only_fields
9073         };
9074         int i, q;
9075         unsigned long field;
9076         u64 field_value;
9077         struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
9078
9079         preempt_disable();
9080
9081         vmcs_load(shadow_vmcs);
9082
9083         for (q = 0; q < ARRAY_SIZE(fields); q++) {
9084                 for (i = 0; i < max_fields[q]; i++) {
9085                         field = fields[q][i];
9086                         field_value = __vmcs_readl(field);
9087                         vmcs12_write_any(get_vmcs12(&vmx->vcpu), field, field_value);
9088                 }
9089                 /*
9090                  * Skip the VM-exit information fields if they are read-only.
9091                  */
9092                 if (!nested_cpu_has_vmwrite_any_field(&vmx->vcpu))
9093                         break;
9094         }
9095
9096         vmcs_clear(shadow_vmcs);
9097         vmcs_load(vmx->loaded_vmcs->vmcs);
9098
9099         preempt_enable();
9100 }
9101
9102 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
9103 {
9104         const u16 *fields[] = {
9105                 shadow_read_write_fields,
9106                 shadow_read_only_fields
9107         };
9108         const int max_fields[] = {
9109                 max_shadow_read_write_fields,
9110                 max_shadow_read_only_fields
9111         };
9112         int i, q;
9113         unsigned long field;
9114         u64 field_value = 0;
9115         struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
9116
9117         vmcs_load(shadow_vmcs);
9118
9119         for (q = 0; q < ARRAY_SIZE(fields); q++) {
9120                 for (i = 0; i < max_fields[q]; i++) {
9121                         field = fields[q][i];
9122                         vmcs12_read_any(get_vmcs12(&vmx->vcpu), field, &field_value);
9123                         __vmcs_writel(field, field_value);
9124                 }
9125         }
9126
9127         vmcs_clear(shadow_vmcs);
9128         vmcs_load(vmx->loaded_vmcs->vmcs);
9129 }
9130
9131 static int handle_vmread(struct kvm_vcpu *vcpu)
9132 {
9133         unsigned long field;
9134         u64 field_value;
9135         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9136         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9137         gva_t gva = 0;
9138         struct vmcs12 *vmcs12;
9139
9140         if (!nested_vmx_check_permission(vcpu))
9141                 return 1;
9142
9143         if (to_vmx(vcpu)->nested.current_vmptr == -1ull)
9144                 return nested_vmx_failInvalid(vcpu);
9145
9146         if (!is_guest_mode(vcpu))
9147                 vmcs12 = get_vmcs12(vcpu);
9148         else {
9149                 /*
9150                  * When vmcs->vmcs_link_pointer is -1ull, any VMREAD
9151                  * to shadowed-field sets the ALU flags for VMfailInvalid.
9152                  */
9153                 if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull)
9154                         return nested_vmx_failInvalid(vcpu);
9155                 vmcs12 = get_shadow_vmcs12(vcpu);
9156         }
9157
9158         /* Decode instruction info and find the field to read */
9159         field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
9160         /* Read the field, zero-extended to a u64 field_value */
9161         if (vmcs12_read_any(vmcs12, field, &field_value) < 0)
9162                 return nested_vmx_failValid(vcpu,
9163                         VMXERR_UNSUPPORTED_VMCS_COMPONENT);
9164
9165         /*
9166          * Now copy part of this value to register or memory, as requested.
9167          * Note that the number of bits actually copied is 32 or 64 depending
9168          * on the guest's mode (32 or 64 bit), not on the given field's length.
9169          */
9170         if (vmx_instruction_info & (1u << 10)) {
9171                 kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
9172                         field_value);
9173         } else {
9174                 if (get_vmx_mem_address(vcpu, exit_qualification,
9175                                 vmx_instruction_info, true, &gva))
9176                         return 1;
9177                 /* _system ok, nested_vmx_check_permission has verified cpl=0 */
9178                 kvm_write_guest_virt_system(vcpu, gva, &field_value,
9179                                             (is_long_mode(vcpu) ? 8 : 4), NULL);
9180         }
9181
9182         return nested_vmx_succeed(vcpu);
9183 }
9184
9185
9186 static int handle_vmwrite(struct kvm_vcpu *vcpu)
9187 {
9188         unsigned long field;
9189         gva_t gva;
9190         struct vcpu_vmx *vmx = to_vmx(vcpu);
9191         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9192         u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9193
9194         /* The value to write might be 32 or 64 bits, depending on L1's long
9195          * mode, and eventually we need to write that into a field of several
9196          * possible lengths. The code below first zero-extends the value to 64
9197          * bit (field_value), and then copies only the appropriate number of
9198          * bits into the vmcs12 field.
9199          */
9200         u64 field_value = 0;
9201         struct x86_exception e;
9202         struct vmcs12 *vmcs12;
9203
9204         if (!nested_vmx_check_permission(vcpu))
9205                 return 1;
9206
9207         if (vmx->nested.current_vmptr == -1ull)
9208                 return nested_vmx_failInvalid(vcpu);
9209
9210         if (vmx_instruction_info & (1u << 10))
9211                 field_value = kvm_register_readl(vcpu,
9212                         (((vmx_instruction_info) >> 3) & 0xf));
9213         else {
9214                 if (get_vmx_mem_address(vcpu, exit_qualification,
9215                                 vmx_instruction_info, false, &gva))
9216                         return 1;
9217                 if (kvm_read_guest_virt(vcpu, gva, &field_value,
9218                                         (is_64_bit_mode(vcpu) ? 8 : 4), &e)) {
9219                         kvm_inject_page_fault(vcpu, &e);
9220                         return 1;
9221                 }
9222         }
9223
9224
9225         field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
9226         /*
9227          * If the vCPU supports "VMWRITE to any supported field in the
9228          * VMCS," then the "read-only" fields are actually read/write.
9229          */
9230         if (vmcs_field_readonly(field) &&
9231             !nested_cpu_has_vmwrite_any_field(vcpu))
9232                 return nested_vmx_failValid(vcpu,
9233                         VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
9234
9235         if (!is_guest_mode(vcpu))
9236                 vmcs12 = get_vmcs12(vcpu);
9237         else {
9238                 /*
9239                  * When vmcs->vmcs_link_pointer is -1ull, any VMWRITE
9240                  * to shadowed-field sets the ALU flags for VMfailInvalid.
9241                  */
9242                 if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull)
9243                         return nested_vmx_failInvalid(vcpu);
9244                 vmcs12 = get_shadow_vmcs12(vcpu);
9245         }
9246
9247         if (vmcs12_write_any(vmcs12, field, field_value) < 0)
9248                 return nested_vmx_failValid(vcpu,
9249                         VMXERR_UNSUPPORTED_VMCS_COMPONENT);
9250
9251         /*
9252          * Do not track vmcs12 dirty-state if in guest-mode
9253          * as we actually dirty shadow vmcs12 instead of vmcs12.
9254          */
9255         if (!is_guest_mode(vcpu)) {
9256                 switch (field) {
9257 #define SHADOW_FIELD_RW(x) case x:
9258 #include "vmx_shadow_fields.h"
9259                         /*
9260                          * The fields that can be updated by L1 without a vmexit are
9261                          * always updated in the vmcs02, the others go down the slow
9262                          * path of prepare_vmcs02.
9263                          */
9264                         break;
9265                 default:
9266                         vmx->nested.dirty_vmcs12 = true;
9267                         break;
9268                 }
9269         }
9270
9271         return nested_vmx_succeed(vcpu);
9272 }
9273
9274 static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
9275 {
9276         vmx->nested.current_vmptr = vmptr;
9277         if (enable_shadow_vmcs) {
9278                 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
9279                               SECONDARY_EXEC_SHADOW_VMCS);
9280                 vmcs_write64(VMCS_LINK_POINTER,
9281                              __pa(vmx->vmcs01.shadow_vmcs));
9282                 vmx->nested.need_vmcs12_sync = true;
9283         }
9284         vmx->nested.dirty_vmcs12 = true;
9285 }
9286
9287 /* Emulate the VMPTRLD instruction */
9288 static int handle_vmptrld(struct kvm_vcpu *vcpu)
9289 {
9290         struct vcpu_vmx *vmx = to_vmx(vcpu);
9291         gpa_t vmptr;
9292
9293         if (!nested_vmx_check_permission(vcpu))
9294                 return 1;
9295
9296         if (nested_vmx_get_vmptr(vcpu, &vmptr))
9297                 return 1;
9298
9299         if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu)))
9300                 return nested_vmx_failValid(vcpu,
9301                         VMXERR_VMPTRLD_INVALID_ADDRESS);
9302
9303         if (vmptr == vmx->nested.vmxon_ptr)
9304                 return nested_vmx_failValid(vcpu,
9305                         VMXERR_VMPTRLD_VMXON_POINTER);
9306
9307         /* Forbid normal VMPTRLD if Enlightened version was used */
9308         if (vmx->nested.hv_evmcs)
9309                 return 1;
9310
9311         if (vmx->nested.current_vmptr != vmptr) {
9312                 struct vmcs12 *new_vmcs12;
9313                 struct page *page;
9314                 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
9315                 if (is_error_page(page))
9316                         return nested_vmx_failInvalid(vcpu);
9317
9318                 new_vmcs12 = kmap(page);
9319                 if (new_vmcs12->hdr.revision_id != VMCS12_REVISION ||
9320                     (new_vmcs12->hdr.shadow_vmcs &&
9321                      !nested_cpu_has_vmx_shadow_vmcs(vcpu))) {
9322                         kunmap(page);
9323                         kvm_release_page_clean(page);
9324                         return nested_vmx_failValid(vcpu,
9325                                 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
9326                 }
9327
9328                 nested_release_vmcs12(vcpu);
9329
9330                 /*
9331                  * Load VMCS12 from guest memory since it is not already
9332                  * cached.
9333                  */
9334                 memcpy(vmx->nested.cached_vmcs12, new_vmcs12, VMCS12_SIZE);
9335                 kunmap(page);
9336                 kvm_release_page_clean(page);
9337
9338                 set_current_vmptr(vmx, vmptr);
9339         }
9340
9341         return nested_vmx_succeed(vcpu);
9342 }
9343
9344 /*
9345  * This is an equivalent of the nested hypervisor executing the vmptrld
9346  * instruction.
9347  */
9348 static int nested_vmx_handle_enlightened_vmptrld(struct kvm_vcpu *vcpu,
9349                                                  bool from_launch)
9350 {
9351         struct vcpu_vmx *vmx = to_vmx(vcpu);
9352         struct hv_vp_assist_page assist_page;
9353
9354         if (likely(!vmx->nested.enlightened_vmcs_enabled))
9355                 return 1;
9356
9357         if (unlikely(!kvm_hv_get_assist_page(vcpu, &assist_page)))
9358                 return 1;
9359
9360         if (unlikely(!assist_page.enlighten_vmentry))
9361                 return 1;
9362
9363         if (unlikely(assist_page.current_nested_vmcs !=
9364                      vmx->nested.hv_evmcs_vmptr)) {
9365
9366                 if (!vmx->nested.hv_evmcs)
9367                         vmx->nested.current_vmptr = -1ull;
9368
9369                 nested_release_evmcs(vcpu);
9370
9371                 vmx->nested.hv_evmcs_page = kvm_vcpu_gpa_to_page(
9372                         vcpu, assist_page.current_nested_vmcs);
9373
9374                 if (unlikely(is_error_page(vmx->nested.hv_evmcs_page)))
9375                         return 0;
9376
9377                 vmx->nested.hv_evmcs = kmap(vmx->nested.hv_evmcs_page);
9378
9379                 /*
9380                  * Currently, KVM only supports eVMCS version 1
9381                  * (== KVM_EVMCS_VERSION) and thus we expect guest to set this
9382                  * value to first u32 field of eVMCS which should specify eVMCS
9383                  * VersionNumber.
9384                  *
9385                  * Guest should be aware of supported eVMCS versions by host by
9386                  * examining CPUID.0x4000000A.EAX[0:15]. Host userspace VMM is
9387                  * expected to set this CPUID leaf according to the value
9388                  * returned in vmcs_version from nested_enable_evmcs().
9389                  *
9390                  * However, it turns out that Microsoft Hyper-V fails to comply
9391                  * to their own invented interface: When Hyper-V use eVMCS, it
9392                  * just sets first u32 field of eVMCS to revision_id specified
9393                  * in MSR_IA32_VMX_BASIC. Instead of used eVMCS version number
9394                  * which is one of the supported versions specified in
9395                  * CPUID.0x4000000A.EAX[0:15].
9396                  *
9397                  * To overcome Hyper-V bug, we accept here either a supported
9398                  * eVMCS version or VMCS12 revision_id as valid values for first
9399                  * u32 field of eVMCS.
9400                  */
9401                 if ((vmx->nested.hv_evmcs->revision_id != KVM_EVMCS_VERSION) &&
9402                     (vmx->nested.hv_evmcs->revision_id != VMCS12_REVISION)) {
9403                         nested_release_evmcs(vcpu);
9404                         return 0;
9405                 }
9406
9407                 vmx->nested.dirty_vmcs12 = true;
9408                 /*
9409                  * As we keep L2 state for one guest only 'hv_clean_fields' mask
9410                  * can't be used when we switch between them. Reset it here for
9411                  * simplicity.
9412                  */
9413                 vmx->nested.hv_evmcs->hv_clean_fields &=
9414                         ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
9415                 vmx->nested.hv_evmcs_vmptr = assist_page.current_nested_vmcs;
9416
9417                 /*
9418                  * Unlike normal vmcs12, enlightened vmcs12 is not fully
9419                  * reloaded from guest's memory (read only fields, fields not
9420                  * present in struct hv_enlightened_vmcs, ...). Make sure there
9421                  * are no leftovers.
9422                  */
9423                 if (from_launch) {
9424                         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9425                         memset(vmcs12, 0, sizeof(*vmcs12));
9426                         vmcs12->hdr.revision_id = VMCS12_REVISION;
9427                 }
9428
9429         }
9430         return 1;
9431 }
9432
9433 /* Emulate the VMPTRST instruction */
9434 static int handle_vmptrst(struct kvm_vcpu *vcpu)
9435 {
9436         unsigned long exit_qual = vmcs_readl(EXIT_QUALIFICATION);
9437         u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9438         gpa_t current_vmptr = to_vmx(vcpu)->nested.current_vmptr;
9439         struct x86_exception e;
9440         gva_t gva;
9441
9442         if (!nested_vmx_check_permission(vcpu))
9443                 return 1;
9444
9445         if (unlikely(to_vmx(vcpu)->nested.hv_evmcs))
9446                 return 1;
9447
9448         if (get_vmx_mem_address(vcpu, exit_qual, instr_info, true, &gva))
9449                 return 1;
9450         /* *_system ok, nested_vmx_check_permission has verified cpl=0 */
9451         if (kvm_write_guest_virt_system(vcpu, gva, (void *)&current_vmptr,
9452                                         sizeof(gpa_t), &e)) {
9453                 kvm_inject_page_fault(vcpu, &e);
9454                 return 1;
9455         }
9456         return nested_vmx_succeed(vcpu);
9457 }
9458
9459 /* Emulate the INVEPT instruction */
9460 static int handle_invept(struct kvm_vcpu *vcpu)
9461 {
9462         struct vcpu_vmx *vmx = to_vmx(vcpu);
9463         u32 vmx_instruction_info, types;
9464         unsigned long type;
9465         gva_t gva;
9466         struct x86_exception e;
9467         struct {
9468                 u64 eptp, gpa;
9469         } operand;
9470
9471         if (!(vmx->nested.msrs.secondary_ctls_high &
9472               SECONDARY_EXEC_ENABLE_EPT) ||
9473             !(vmx->nested.msrs.ept_caps & VMX_EPT_INVEPT_BIT)) {
9474                 kvm_queue_exception(vcpu, UD_VECTOR);
9475                 return 1;
9476         }
9477
9478         if (!nested_vmx_check_permission(vcpu))
9479                 return 1;
9480
9481         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9482         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9483
9484         types = (vmx->nested.msrs.ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
9485
9486         if (type >= 32 || !(types & (1 << type)))
9487                 return nested_vmx_failValid(vcpu,
9488                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9489
9490         /* According to the Intel VMX instruction reference, the memory
9491          * operand is read even if it isn't needed (e.g., for type==global)
9492          */
9493         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9494                         vmx_instruction_info, false, &gva))
9495                 return 1;
9496         if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9497                 kvm_inject_page_fault(vcpu, &e);
9498                 return 1;
9499         }
9500
9501         switch (type) {
9502         case VMX_EPT_EXTENT_GLOBAL:
9503         /*
9504          * TODO: track mappings and invalidate
9505          * single context requests appropriately
9506          */
9507         case VMX_EPT_EXTENT_CONTEXT:
9508                 kvm_mmu_sync_roots(vcpu);
9509                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
9510                 break;
9511         default:
9512                 BUG_ON(1);
9513                 break;
9514         }
9515
9516         return nested_vmx_succeed(vcpu);
9517 }
9518
9519 static u16 nested_get_vpid02(struct kvm_vcpu *vcpu)
9520 {
9521         struct vcpu_vmx *vmx = to_vmx(vcpu);
9522
9523         return vmx->nested.vpid02 ? vmx->nested.vpid02 : vmx->vpid;
9524 }
9525
9526 static int handle_invvpid(struct kvm_vcpu *vcpu)
9527 {
9528         struct vcpu_vmx *vmx = to_vmx(vcpu);
9529         u32 vmx_instruction_info;
9530         unsigned long type, types;
9531         gva_t gva;
9532         struct x86_exception e;
9533         struct {
9534                 u64 vpid;
9535                 u64 gla;
9536         } operand;
9537         u16 vpid02;
9538
9539         if (!(vmx->nested.msrs.secondary_ctls_high &
9540               SECONDARY_EXEC_ENABLE_VPID) ||
9541                         !(vmx->nested.msrs.vpid_caps & VMX_VPID_INVVPID_BIT)) {
9542                 kvm_queue_exception(vcpu, UD_VECTOR);
9543                 return 1;
9544         }
9545
9546         if (!nested_vmx_check_permission(vcpu))
9547                 return 1;
9548
9549         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9550         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9551
9552         types = (vmx->nested.msrs.vpid_caps &
9553                         VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
9554
9555         if (type >= 32 || !(types & (1 << type)))
9556                 return nested_vmx_failValid(vcpu,
9557                         VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9558
9559         /* according to the intel vmx instruction reference, the memory
9560          * operand is read even if it isn't needed (e.g., for type==global)
9561          */
9562         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9563                         vmx_instruction_info, false, &gva))
9564                 return 1;
9565         if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9566                 kvm_inject_page_fault(vcpu, &e);
9567                 return 1;
9568         }
9569         if (operand.vpid >> 16)
9570                 return nested_vmx_failValid(vcpu,
9571                         VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9572
9573         vpid02 = nested_get_vpid02(vcpu);
9574         switch (type) {
9575         case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
9576                 if (!operand.vpid ||
9577                     is_noncanonical_address(operand.gla, vcpu))
9578                         return nested_vmx_failValid(vcpu,
9579                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9580                 if (cpu_has_vmx_invvpid_individual_addr()) {
9581                         __invvpid(VMX_VPID_EXTENT_INDIVIDUAL_ADDR,
9582                                 vpid02, operand.gla);
9583                 } else
9584                         __vmx_flush_tlb(vcpu, vpid02, false);
9585                 break;
9586         case VMX_VPID_EXTENT_SINGLE_CONTEXT:
9587         case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
9588                 if (!operand.vpid)
9589                         return nested_vmx_failValid(vcpu,
9590                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9591                 __vmx_flush_tlb(vcpu, vpid02, false);
9592                 break;
9593         case VMX_VPID_EXTENT_ALL_CONTEXT:
9594                 __vmx_flush_tlb(vcpu, vpid02, false);
9595                 break;
9596         default:
9597                 WARN_ON_ONCE(1);
9598                 return kvm_skip_emulated_instruction(vcpu);
9599         }
9600
9601         return nested_vmx_succeed(vcpu);
9602 }
9603
9604 static int handle_invpcid(struct kvm_vcpu *vcpu)
9605 {
9606         u32 vmx_instruction_info;
9607         unsigned long type;
9608         bool pcid_enabled;
9609         gva_t gva;
9610         struct x86_exception e;
9611         unsigned i;
9612         unsigned long roots_to_free = 0;
9613         struct {
9614                 u64 pcid;
9615                 u64 gla;
9616         } operand;
9617
9618         if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
9619                 kvm_queue_exception(vcpu, UD_VECTOR);
9620                 return 1;
9621         }
9622
9623         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9624         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9625
9626         if (type > 3) {
9627                 kvm_inject_gp(vcpu, 0);
9628                 return 1;
9629         }
9630
9631         /* According to the Intel instruction reference, the memory operand
9632          * is read even if it isn't needed (e.g., for type==all)
9633          */
9634         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9635                                 vmx_instruction_info, false, &gva))
9636                 return 1;
9637
9638         if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9639                 kvm_inject_page_fault(vcpu, &e);
9640                 return 1;
9641         }
9642
9643         if (operand.pcid >> 12 != 0) {
9644                 kvm_inject_gp(vcpu, 0);
9645                 return 1;
9646         }
9647
9648         pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
9649
9650         switch (type) {
9651         case INVPCID_TYPE_INDIV_ADDR:
9652                 if ((!pcid_enabled && (operand.pcid != 0)) ||
9653                     is_noncanonical_address(operand.gla, vcpu)) {
9654                         kvm_inject_gp(vcpu, 0);
9655                         return 1;
9656                 }
9657                 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
9658                 return kvm_skip_emulated_instruction(vcpu);
9659
9660         case INVPCID_TYPE_SINGLE_CTXT:
9661                 if (!pcid_enabled && (operand.pcid != 0)) {
9662                         kvm_inject_gp(vcpu, 0);
9663                         return 1;
9664                 }
9665
9666                 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
9667                         kvm_mmu_sync_roots(vcpu);
9668                         kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
9669                 }
9670
9671                 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
9672                         if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].cr3)
9673                             == operand.pcid)
9674                                 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
9675
9676                 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
9677                 /*
9678                  * If neither the current cr3 nor any of the prev_roots use the
9679                  * given PCID, then nothing needs to be done here because a
9680                  * resync will happen anyway before switching to any other CR3.
9681                  */
9682
9683                 return kvm_skip_emulated_instruction(vcpu);
9684
9685         case INVPCID_TYPE_ALL_NON_GLOBAL:
9686                 /*
9687                  * Currently, KVM doesn't mark global entries in the shadow
9688                  * page tables, so a non-global flush just degenerates to a
9689                  * global flush. If needed, we could optimize this later by
9690                  * keeping track of global entries in shadow page tables.
9691                  */
9692
9693                 /* fall-through */
9694         case INVPCID_TYPE_ALL_INCL_GLOBAL:
9695                 kvm_mmu_unload(vcpu);
9696                 return kvm_skip_emulated_instruction(vcpu);
9697
9698         default:
9699                 BUG(); /* We have already checked above that type <= 3 */
9700         }
9701 }
9702
9703 static int handle_pml_full(struct kvm_vcpu *vcpu)
9704 {
9705         unsigned long exit_qualification;
9706
9707         trace_kvm_pml_full(vcpu->vcpu_id);
9708
9709         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9710
9711         /*
9712          * PML buffer FULL happened while executing iret from NMI,
9713          * "blocked by NMI" bit has to be set before next VM entry.
9714          */
9715         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
9716                         enable_vnmi &&
9717                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
9718                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
9719                                 GUEST_INTR_STATE_NMI);
9720
9721         /*
9722          * PML buffer already flushed at beginning of VMEXIT. Nothing to do
9723          * here.., and there's no userspace involvement needed for PML.
9724          */
9725         return 1;
9726 }
9727
9728 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
9729 {
9730         if (!to_vmx(vcpu)->req_immediate_exit)
9731                 kvm_lapic_expired_hv_timer(vcpu);
9732         return 1;
9733 }
9734
9735 static bool valid_ept_address(struct kvm_vcpu *vcpu, u64 address)
9736 {
9737         struct vcpu_vmx *vmx = to_vmx(vcpu);
9738         int maxphyaddr = cpuid_maxphyaddr(vcpu);
9739
9740         /* Check for memory type validity */
9741         switch (address & VMX_EPTP_MT_MASK) {
9742         case VMX_EPTP_MT_UC:
9743                 if (!(vmx->nested.msrs.ept_caps & VMX_EPTP_UC_BIT))
9744                         return false;
9745                 break;
9746         case VMX_EPTP_MT_WB:
9747                 if (!(vmx->nested.msrs.ept_caps & VMX_EPTP_WB_BIT))
9748                         return false;
9749                 break;
9750         default:
9751                 return false;
9752         }
9753
9754         /* only 4 levels page-walk length are valid */
9755         if ((address & VMX_EPTP_PWL_MASK) != VMX_EPTP_PWL_4)
9756                 return false;
9757
9758         /* Reserved bits should not be set */
9759         if (address >> maxphyaddr || ((address >> 7) & 0x1f))
9760                 return false;
9761
9762         /* AD, if set, should be supported */
9763         if (address & VMX_EPTP_AD_ENABLE_BIT) {
9764                 if (!(vmx->nested.msrs.ept_caps & VMX_EPT_AD_BIT))
9765                         return false;
9766         }
9767
9768         return true;
9769 }
9770
9771 static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
9772                                      struct vmcs12 *vmcs12)
9773 {
9774         u32 index = vcpu->arch.regs[VCPU_REGS_RCX];
9775         u64 address;
9776         bool accessed_dirty;
9777         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
9778
9779         if (!nested_cpu_has_eptp_switching(vmcs12) ||
9780             !nested_cpu_has_ept(vmcs12))
9781                 return 1;
9782
9783         if (index >= VMFUNC_EPTP_ENTRIES)
9784                 return 1;
9785
9786
9787         if (kvm_vcpu_read_guest_page(vcpu, vmcs12->eptp_list_address >> PAGE_SHIFT,
9788                                      &address, index * 8, 8))
9789                 return 1;
9790
9791         accessed_dirty = !!(address & VMX_EPTP_AD_ENABLE_BIT);
9792
9793         /*
9794          * If the (L2) guest does a vmfunc to the currently
9795          * active ept pointer, we don't have to do anything else
9796          */
9797         if (vmcs12->ept_pointer != address) {
9798                 if (!valid_ept_address(vcpu, address))
9799                         return 1;
9800
9801                 kvm_mmu_unload(vcpu);
9802                 mmu->ept_ad = accessed_dirty;
9803                 mmu->mmu_role.base.ad_disabled = !accessed_dirty;
9804                 vmcs12->ept_pointer = address;
9805                 /*
9806                  * TODO: Check what's the correct approach in case
9807                  * mmu reload fails. Currently, we just let the next
9808                  * reload potentially fail
9809                  */
9810                 kvm_mmu_reload(vcpu);
9811         }
9812
9813         return 0;
9814 }
9815
9816 static int handle_vmfunc(struct kvm_vcpu *vcpu)
9817 {
9818         struct vcpu_vmx *vmx = to_vmx(vcpu);
9819         struct vmcs12 *vmcs12;
9820         u32 function = vcpu->arch.regs[VCPU_REGS_RAX];
9821
9822         /*
9823          * VMFUNC is only supported for nested guests, but we always enable the
9824          * secondary control for simplicity; for non-nested mode, fake that we
9825          * didn't by injecting #UD.
9826          */
9827         if (!is_guest_mode(vcpu)) {
9828                 kvm_queue_exception(vcpu, UD_VECTOR);
9829                 return 1;
9830         }
9831
9832         vmcs12 = get_vmcs12(vcpu);
9833         if ((vmcs12->vm_function_control & (1 << function)) == 0)
9834                 goto fail;
9835
9836         switch (function) {
9837         case 0:
9838                 if (nested_vmx_eptp_switching(vcpu, vmcs12))
9839                         goto fail;
9840                 break;
9841         default:
9842                 goto fail;
9843         }
9844         return kvm_skip_emulated_instruction(vcpu);
9845
9846 fail:
9847         nested_vmx_vmexit(vcpu, vmx->exit_reason,
9848                           vmcs_read32(VM_EXIT_INTR_INFO),
9849                           vmcs_readl(EXIT_QUALIFICATION));
9850         return 1;
9851 }
9852
9853 static int handle_encls(struct kvm_vcpu *vcpu)
9854 {
9855         /*
9856          * SGX virtualization is not yet supported.  There is no software
9857          * enable bit for SGX, so we have to trap ENCLS and inject a #UD
9858          * to prevent the guest from executing ENCLS.
9859          */
9860         kvm_queue_exception(vcpu, UD_VECTOR);
9861         return 1;
9862 }
9863
9864 /*
9865  * The exit handlers return 1 if the exit was handled fully and guest execution
9866  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
9867  * to be done to userspace and return 0.
9868  */
9869 static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
9870         [EXIT_REASON_EXCEPTION_NMI]           = handle_exception,
9871         [EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
9872         [EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
9873         [EXIT_REASON_NMI_WINDOW]              = handle_nmi_window,
9874         [EXIT_REASON_IO_INSTRUCTION]          = handle_io,
9875         [EXIT_REASON_CR_ACCESS]               = handle_cr,
9876         [EXIT_REASON_DR_ACCESS]               = handle_dr,
9877         [EXIT_REASON_CPUID]                   = handle_cpuid,
9878         [EXIT_REASON_MSR_READ]                = handle_rdmsr,
9879         [EXIT_REASON_MSR_WRITE]               = handle_wrmsr,
9880         [EXIT_REASON_PENDING_INTERRUPT]       = handle_interrupt_window,
9881         [EXIT_REASON_HLT]                     = handle_halt,
9882         [EXIT_REASON_INVD]                    = handle_invd,
9883         [EXIT_REASON_INVLPG]                  = handle_invlpg,
9884         [EXIT_REASON_RDPMC]                   = handle_rdpmc,
9885         [EXIT_REASON_VMCALL]                  = handle_vmcall,
9886         [EXIT_REASON_VMCLEAR]                 = handle_vmclear,
9887         [EXIT_REASON_VMLAUNCH]                = handle_vmlaunch,
9888         [EXIT_REASON_VMPTRLD]                 = handle_vmptrld,
9889         [EXIT_REASON_VMPTRST]                 = handle_vmptrst,
9890         [EXIT_REASON_VMREAD]                  = handle_vmread,
9891         [EXIT_REASON_VMRESUME]                = handle_vmresume,
9892         [EXIT_REASON_VMWRITE]                 = handle_vmwrite,
9893         [EXIT_REASON_VMOFF]                   = handle_vmoff,
9894         [EXIT_REASON_VMON]                    = handle_vmon,
9895         [EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
9896         [EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
9897         [EXIT_REASON_APIC_WRITE]              = handle_apic_write,
9898         [EXIT_REASON_EOI_INDUCED]             = handle_apic_eoi_induced,
9899         [EXIT_REASON_WBINVD]                  = handle_wbinvd,
9900         [EXIT_REASON_XSETBV]                  = handle_xsetbv,
9901         [EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
9902         [EXIT_REASON_MCE_DURING_VMENTRY]      = handle_machine_check,
9903         [EXIT_REASON_GDTR_IDTR]               = handle_desc,
9904         [EXIT_REASON_LDTR_TR]                 = handle_desc,
9905         [EXIT_REASON_EPT_VIOLATION]           = handle_ept_violation,
9906         [EXIT_REASON_EPT_MISCONFIG]           = handle_ept_misconfig,
9907         [EXIT_REASON_PAUSE_INSTRUCTION]       = handle_pause,
9908         [EXIT_REASON_MWAIT_INSTRUCTION]       = handle_mwait,
9909         [EXIT_REASON_MONITOR_TRAP_FLAG]       = handle_monitor_trap,
9910         [EXIT_REASON_MONITOR_INSTRUCTION]     = handle_monitor,
9911         [EXIT_REASON_INVEPT]                  = handle_invept,
9912         [EXIT_REASON_INVVPID]                 = handle_invvpid,
9913         [EXIT_REASON_RDRAND]                  = handle_invalid_op,
9914         [EXIT_REASON_RDSEED]                  = handle_invalid_op,
9915         [EXIT_REASON_XSAVES]                  = handle_xsaves,
9916         [EXIT_REASON_XRSTORS]                 = handle_xrstors,
9917         [EXIT_REASON_PML_FULL]                = handle_pml_full,
9918         [EXIT_REASON_INVPCID]                 = handle_invpcid,
9919         [EXIT_REASON_VMFUNC]                  = handle_vmfunc,
9920         [EXIT_REASON_PREEMPTION_TIMER]        = handle_preemption_timer,
9921         [EXIT_REASON_ENCLS]                   = handle_encls,
9922 };
9923
9924 static const int kvm_vmx_max_exit_handlers =
9925         ARRAY_SIZE(kvm_vmx_exit_handlers);
9926
9927 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
9928                                        struct vmcs12 *vmcs12)
9929 {
9930         unsigned long exit_qualification;
9931         gpa_t bitmap, last_bitmap;
9932         unsigned int port;
9933         int size;
9934         u8 b;
9935
9936         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
9937                 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
9938
9939         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9940
9941         port = exit_qualification >> 16;
9942         size = (exit_qualification & 7) + 1;
9943
9944         last_bitmap = (gpa_t)-1;
9945         b = -1;
9946
9947         while (size > 0) {
9948                 if (port < 0x8000)
9949                         bitmap = vmcs12->io_bitmap_a;
9950                 else if (port < 0x10000)
9951                         bitmap = vmcs12->io_bitmap_b;
9952                 else
9953                         return true;
9954                 bitmap += (port & 0x7fff) / 8;
9955
9956                 if (last_bitmap != bitmap)
9957                         if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
9958                                 return true;
9959                 if (b & (1 << (port & 7)))
9960                         return true;
9961
9962                 port++;
9963                 size--;
9964                 last_bitmap = bitmap;
9965         }
9966
9967         return false;
9968 }
9969
9970 /*
9971  * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
9972  * rather than handle it ourselves in L0. I.e., check whether L1 expressed
9973  * disinterest in the current event (read or write a specific MSR) by using an
9974  * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
9975  */
9976 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
9977         struct vmcs12 *vmcs12, u32 exit_reason)
9978 {
9979         u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
9980         gpa_t bitmap;
9981
9982         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
9983                 return true;
9984
9985         /*
9986          * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
9987          * for the four combinations of read/write and low/high MSR numbers.
9988          * First we need to figure out which of the four to use:
9989          */
9990         bitmap = vmcs12->msr_bitmap;
9991         if (exit_reason == EXIT_REASON_MSR_WRITE)
9992                 bitmap += 2048;
9993         if (msr_index >= 0xc0000000) {
9994                 msr_index -= 0xc0000000;
9995                 bitmap += 1024;
9996         }
9997
9998         /* Then read the msr_index'th bit from this bitmap: */
9999         if (msr_index < 1024*8) {
10000                 unsigned char b;
10001                 if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
10002                         return true;
10003                 return 1 & (b >> (msr_index & 7));
10004         } else
10005                 return true; /* let L1 handle the wrong parameter */
10006 }
10007
10008 /*
10009  * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
10010  * rather than handle it ourselves in L0. I.e., check if L1 wanted to
10011  * intercept (via guest_host_mask etc.) the current event.
10012  */
10013 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
10014         struct vmcs12 *vmcs12)
10015 {
10016         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
10017         int cr = exit_qualification & 15;
10018         int reg;
10019         unsigned long val;
10020
10021         switch ((exit_qualification >> 4) & 3) {
10022         case 0: /* mov to cr */
10023                 reg = (exit_qualification >> 8) & 15;
10024                 val = kvm_register_readl(vcpu, reg);
10025                 switch (cr) {
10026                 case 0:
10027                         if (vmcs12->cr0_guest_host_mask &
10028                             (val ^ vmcs12->cr0_read_shadow))
10029                                 return true;
10030                         break;
10031                 case 3:
10032                         if ((vmcs12->cr3_target_count >= 1 &&
10033                                         vmcs12->cr3_target_value0 == val) ||
10034                                 (vmcs12->cr3_target_count >= 2 &&
10035                                         vmcs12->cr3_target_value1 == val) ||
10036                                 (vmcs12->cr3_target_count >= 3 &&
10037                                         vmcs12->cr3_target_value2 == val) ||
10038                                 (vmcs12->cr3_target_count >= 4 &&
10039                                         vmcs12->cr3_target_value3 == val))
10040                                 return false;
10041                         if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
10042                                 return true;
10043                         break;
10044                 case 4:
10045                         if (vmcs12->cr4_guest_host_mask &
10046                             (vmcs12->cr4_read_shadow ^ val))
10047                                 return true;
10048                         break;
10049                 case 8:
10050                         if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
10051                                 return true;
10052                         break;
10053                 }
10054                 break;
10055         case 2: /* clts */
10056                 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
10057                     (vmcs12->cr0_read_shadow & X86_CR0_TS))
10058                         return true;
10059                 break;
10060         case 1: /* mov from cr */
10061                 switch (cr) {
10062                 case 3:
10063                         if (vmcs12->cpu_based_vm_exec_control &
10064                             CPU_BASED_CR3_STORE_EXITING)
10065                                 return true;
10066                         break;
10067                 case 8:
10068                         if (vmcs12->cpu_based_vm_exec_control &
10069                             CPU_BASED_CR8_STORE_EXITING)
10070                                 return true;
10071                         break;
10072                 }
10073                 break;
10074         case 3: /* lmsw */
10075                 /*
10076                  * lmsw can change bits 1..3 of cr0, and only set bit 0 of
10077                  * cr0. Other attempted changes are ignored, with no exit.
10078                  */
10079                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
10080                 if (vmcs12->cr0_guest_host_mask & 0xe &
10081                     (val ^ vmcs12->cr0_read_shadow))
10082                         return true;
10083                 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
10084                     !(vmcs12->cr0_read_shadow & 0x1) &&
10085                     (val & 0x1))
10086                         return true;
10087                 break;
10088         }
10089         return false;
10090 }
10091
10092 static bool nested_vmx_exit_handled_vmcs_access(struct kvm_vcpu *vcpu,
10093         struct vmcs12 *vmcs12, gpa_t bitmap)
10094 {
10095         u32 vmx_instruction_info;
10096         unsigned long field;
10097         u8 b;
10098
10099         if (!nested_cpu_has_shadow_vmcs(vmcs12))
10100                 return true;
10101
10102         /* Decode instruction info and find the field to access */
10103         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
10104         field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
10105
10106         /* Out-of-range fields always cause a VM exit from L2 to L1 */
10107         if (field >> 15)
10108                 return true;
10109
10110         if (kvm_vcpu_read_guest(vcpu, bitmap + field/8, &b, 1))
10111                 return true;
10112
10113         return 1 & (b >> (field & 7));
10114 }
10115
10116 /*
10117  * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
10118  * should handle it ourselves in L0 (and then continue L2). Only call this
10119  * when in is_guest_mode (L2).
10120  */
10121 static bool nested_vmx_exit_reflected(struct kvm_vcpu *vcpu, u32 exit_reason)
10122 {
10123         u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10124         struct vcpu_vmx *vmx = to_vmx(vcpu);
10125         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10126
10127         if (vmx->nested.nested_run_pending)
10128                 return false;
10129
10130         if (unlikely(vmx->fail)) {
10131                 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
10132                                     vmcs_read32(VM_INSTRUCTION_ERROR));
10133                 return true;
10134         }
10135
10136         /*
10137          * The host physical addresses of some pages of guest memory
10138          * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
10139          * Page). The CPU may write to these pages via their host
10140          * physical address while L2 is running, bypassing any
10141          * address-translation-based dirty tracking (e.g. EPT write
10142          * protection).
10143          *
10144          * Mark them dirty on every exit from L2 to prevent them from
10145          * getting out of sync with dirty tracking.
10146          */
10147         nested_mark_vmcs12_pages_dirty(vcpu);
10148
10149         trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
10150                                 vmcs_readl(EXIT_QUALIFICATION),
10151                                 vmx->idt_vectoring_info,
10152                                 intr_info,
10153                                 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
10154                                 KVM_ISA_VMX);
10155
10156         switch (exit_reason) {
10157         case EXIT_REASON_EXCEPTION_NMI:
10158                 if (is_nmi(intr_info))
10159                         return false;
10160                 else if (is_page_fault(intr_info))
10161                         return !vmx->vcpu.arch.apf.host_apf_reason && enable_ept;
10162                 else if (is_debug(intr_info) &&
10163                          vcpu->guest_debug &
10164                          (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
10165                         return false;
10166                 else if (is_breakpoint(intr_info) &&
10167                          vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
10168                         return false;
10169                 return vmcs12->exception_bitmap &
10170                                 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
10171         case EXIT_REASON_EXTERNAL_INTERRUPT:
10172                 return false;
10173         case EXIT_REASON_TRIPLE_FAULT:
10174                 return true;
10175         case EXIT_REASON_PENDING_INTERRUPT:
10176                 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
10177         case EXIT_REASON_NMI_WINDOW:
10178                 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
10179         case EXIT_REASON_TASK_SWITCH:
10180                 return true;
10181         case EXIT_REASON_CPUID:
10182                 return true;
10183         case EXIT_REASON_HLT:
10184                 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
10185         case EXIT_REASON_INVD:
10186                 return true;
10187         case EXIT_REASON_INVLPG:
10188                 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
10189         case EXIT_REASON_RDPMC:
10190                 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
10191         case EXIT_REASON_RDRAND:
10192                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDRAND_EXITING);
10193         case EXIT_REASON_RDSEED:
10194                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDSEED_EXITING);
10195         case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
10196                 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
10197         case EXIT_REASON_VMREAD:
10198                 return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
10199                         vmcs12->vmread_bitmap);
10200         case EXIT_REASON_VMWRITE:
10201                 return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
10202                         vmcs12->vmwrite_bitmap);
10203         case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
10204         case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
10205         case EXIT_REASON_VMPTRST: case EXIT_REASON_VMRESUME:
10206         case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
10207         case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
10208                 /*
10209                  * VMX instructions trap unconditionally. This allows L1 to
10210                  * emulate them for its L2 guest, i.e., allows 3-level nesting!
10211                  */
10212                 return true;
10213         case EXIT_REASON_CR_ACCESS:
10214                 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
10215         case EXIT_REASON_DR_ACCESS:
10216                 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
10217         case EXIT_REASON_IO_INSTRUCTION:
10218                 return nested_vmx_exit_handled_io(vcpu, vmcs12);
10219         case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
10220                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
10221         case EXIT_REASON_MSR_READ:
10222         case EXIT_REASON_MSR_WRITE:
10223                 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
10224         case EXIT_REASON_INVALID_STATE:
10225                 return true;
10226         case EXIT_REASON_MWAIT_INSTRUCTION:
10227                 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
10228         case EXIT_REASON_MONITOR_TRAP_FLAG:
10229                 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG);
10230         case EXIT_REASON_MONITOR_INSTRUCTION:
10231                 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
10232         case EXIT_REASON_PAUSE_INSTRUCTION:
10233                 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
10234                         nested_cpu_has2(vmcs12,
10235                                 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
10236         case EXIT_REASON_MCE_DURING_VMENTRY:
10237                 return false;
10238         case EXIT_REASON_TPR_BELOW_THRESHOLD:
10239                 return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
10240         case EXIT_REASON_APIC_ACCESS:
10241         case EXIT_REASON_APIC_WRITE:
10242         case EXIT_REASON_EOI_INDUCED:
10243                 /*
10244                  * The controls for "virtualize APIC accesses," "APIC-
10245                  * register virtualization," and "virtual-interrupt
10246                  * delivery" only come from vmcs12.
10247                  */
10248                 return true;
10249         case EXIT_REASON_EPT_VIOLATION:
10250                 /*
10251                  * L0 always deals with the EPT violation. If nested EPT is
10252                  * used, and the nested mmu code discovers that the address is
10253                  * missing in the guest EPT table (EPT12), the EPT violation
10254                  * will be injected with nested_ept_inject_page_fault()
10255                  */
10256                 return false;
10257         case EXIT_REASON_EPT_MISCONFIG:
10258                 /*
10259                  * L2 never uses directly L1's EPT, but rather L0's own EPT
10260                  * table (shadow on EPT) or a merged EPT table that L0 built
10261                  * (EPT on EPT). So any problems with the structure of the
10262                  * table is L0's fault.
10263                  */
10264                 return false;
10265         case EXIT_REASON_INVPCID:
10266                 return
10267                         nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_INVPCID) &&
10268                         nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
10269         case EXIT_REASON_WBINVD:
10270                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
10271         case EXIT_REASON_XSETBV:
10272                 return true;
10273         case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
10274                 /*
10275                  * This should never happen, since it is not possible to
10276                  * set XSS to a non-zero value---neither in L1 nor in L2.
10277                  * If if it were, XSS would have to be checked against
10278                  * the XSS exit bitmap in vmcs12.
10279                  */
10280                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
10281         case EXIT_REASON_PREEMPTION_TIMER:
10282                 return false;
10283         case EXIT_REASON_PML_FULL:
10284                 /* We emulate PML support to L1. */
10285                 return false;
10286         case EXIT_REASON_VMFUNC:
10287                 /* VM functions are emulated through L2->L0 vmexits. */
10288                 return false;
10289         case EXIT_REASON_ENCLS:
10290                 /* SGX is never exposed to L1 */
10291                 return false;
10292         default:
10293                 return true;
10294         }
10295 }
10296
10297 static int nested_vmx_reflect_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason)
10298 {
10299         u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10300
10301         /*
10302          * At this point, the exit interruption info in exit_intr_info
10303          * is only valid for EXCEPTION_NMI exits.  For EXTERNAL_INTERRUPT
10304          * we need to query the in-kernel LAPIC.
10305          */
10306         WARN_ON(exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT);
10307         if ((exit_intr_info &
10308              (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
10309             (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) {
10310                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10311                 vmcs12->vm_exit_intr_error_code =
10312                         vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
10313         }
10314
10315         nested_vmx_vmexit(vcpu, exit_reason, exit_intr_info,
10316                           vmcs_readl(EXIT_QUALIFICATION));
10317         return 1;
10318 }
10319
10320 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
10321 {
10322         *info1 = vmcs_readl(EXIT_QUALIFICATION);
10323         *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
10324 }
10325
10326 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
10327 {
10328         if (vmx->pml_pg) {
10329                 __free_page(vmx->pml_pg);
10330                 vmx->pml_pg = NULL;
10331         }
10332 }
10333
10334 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
10335 {
10336         struct vcpu_vmx *vmx = to_vmx(vcpu);
10337         u64 *pml_buf;
10338         u16 pml_idx;
10339
10340         pml_idx = vmcs_read16(GUEST_PML_INDEX);
10341
10342         /* Do nothing if PML buffer is empty */
10343         if (pml_idx == (PML_ENTITY_NUM - 1))
10344                 return;
10345
10346         /* PML index always points to next available PML buffer entity */
10347         if (pml_idx >= PML_ENTITY_NUM)
10348                 pml_idx = 0;
10349         else
10350                 pml_idx++;
10351
10352         pml_buf = page_address(vmx->pml_pg);
10353         for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
10354                 u64 gpa;
10355
10356                 gpa = pml_buf[pml_idx];
10357                 WARN_ON(gpa & (PAGE_SIZE - 1));
10358                 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
10359         }
10360
10361         /* reset PML index */
10362         vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
10363 }
10364
10365 /*
10366  * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
10367  * Called before reporting dirty_bitmap to userspace.
10368  */
10369 static void kvm_flush_pml_buffers(struct kvm *kvm)
10370 {
10371         int i;
10372         struct kvm_vcpu *vcpu;
10373         /*
10374          * We only need to kick vcpu out of guest mode here, as PML buffer
10375          * is flushed at beginning of all VMEXITs, and it's obvious that only
10376          * vcpus running in guest are possible to have unflushed GPAs in PML
10377          * buffer.
10378          */
10379         kvm_for_each_vcpu(i, vcpu, kvm)
10380                 kvm_vcpu_kick(vcpu);
10381 }
10382
10383 static void vmx_dump_sel(char *name, uint32_t sel)
10384 {
10385         pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
10386                name, vmcs_read16(sel),
10387                vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
10388                vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
10389                vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
10390 }
10391
10392 static void vmx_dump_dtsel(char *name, uint32_t limit)
10393 {
10394         pr_err("%s                           limit=0x%08x, base=0x%016lx\n",
10395                name, vmcs_read32(limit),
10396                vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
10397 }
10398
10399 static void dump_vmcs(void)
10400 {
10401         u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
10402         u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
10403         u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
10404         u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
10405         u32 secondary_exec_control = 0;
10406         unsigned long cr4 = vmcs_readl(GUEST_CR4);
10407         u64 efer = vmcs_read64(GUEST_IA32_EFER);
10408         int i, n;
10409
10410         if (cpu_has_secondary_exec_ctrls())
10411                 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
10412
10413         pr_err("*** Guest State ***\n");
10414         pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
10415                vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
10416                vmcs_readl(CR0_GUEST_HOST_MASK));
10417         pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
10418                cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
10419         pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
10420         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
10421             (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
10422         {
10423                 pr_err("PDPTR0 = 0x%016llx  PDPTR1 = 0x%016llx\n",
10424                        vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
10425                 pr_err("PDPTR2 = 0x%016llx  PDPTR3 = 0x%016llx\n",
10426                        vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
10427         }
10428         pr_err("RSP = 0x%016lx  RIP = 0x%016lx\n",
10429                vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
10430         pr_err("RFLAGS=0x%08lx         DR7 = 0x%016lx\n",
10431                vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
10432         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
10433                vmcs_readl(GUEST_SYSENTER_ESP),
10434                vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
10435         vmx_dump_sel("CS:  ", GUEST_CS_SELECTOR);
10436         vmx_dump_sel("DS:  ", GUEST_DS_SELECTOR);
10437         vmx_dump_sel("SS:  ", GUEST_SS_SELECTOR);
10438         vmx_dump_sel("ES:  ", GUEST_ES_SELECTOR);
10439         vmx_dump_sel("FS:  ", GUEST_FS_SELECTOR);
10440         vmx_dump_sel("GS:  ", GUEST_GS_SELECTOR);
10441         vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
10442         vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
10443         vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
10444         vmx_dump_sel("TR:  ", GUEST_TR_SELECTOR);
10445         if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
10446             (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
10447                 pr_err("EFER =     0x%016llx  PAT = 0x%016llx\n",
10448                        efer, vmcs_read64(GUEST_IA32_PAT));
10449         pr_err("DebugCtl = 0x%016llx  DebugExceptions = 0x%016lx\n",
10450                vmcs_read64(GUEST_IA32_DEBUGCTL),
10451                vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
10452         if (cpu_has_load_perf_global_ctrl &&
10453             vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
10454                 pr_err("PerfGlobCtl = 0x%016llx\n",
10455                        vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
10456         if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
10457                 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
10458         pr_err("Interruptibility = %08x  ActivityState = %08x\n",
10459                vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
10460                vmcs_read32(GUEST_ACTIVITY_STATE));
10461         if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
10462                 pr_err("InterruptStatus = %04x\n",
10463                        vmcs_read16(GUEST_INTR_STATUS));
10464
10465         pr_err("*** Host State ***\n");
10466         pr_err("RIP = 0x%016lx  RSP = 0x%016lx\n",
10467                vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
10468         pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
10469                vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
10470                vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
10471                vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
10472                vmcs_read16(HOST_TR_SELECTOR));
10473         pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
10474                vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
10475                vmcs_readl(HOST_TR_BASE));
10476         pr_err("GDTBase=%016lx IDTBase=%016lx\n",
10477                vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
10478         pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
10479                vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
10480                vmcs_readl(HOST_CR4));
10481         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
10482                vmcs_readl(HOST_IA32_SYSENTER_ESP),
10483                vmcs_read32(HOST_IA32_SYSENTER_CS),
10484                vmcs_readl(HOST_IA32_SYSENTER_EIP));
10485         if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
10486                 pr_err("EFER = 0x%016llx  PAT = 0x%016llx\n",
10487                        vmcs_read64(HOST_IA32_EFER),
10488                        vmcs_read64(HOST_IA32_PAT));
10489         if (cpu_has_load_perf_global_ctrl &&
10490             vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
10491                 pr_err("PerfGlobCtl = 0x%016llx\n",
10492                        vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
10493
10494         pr_err("*** Control State ***\n");
10495         pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
10496                pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
10497         pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
10498         pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
10499                vmcs_read32(EXCEPTION_BITMAP),
10500                vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
10501                vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
10502         pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
10503                vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
10504                vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
10505                vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
10506         pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
10507                vmcs_read32(VM_EXIT_INTR_INFO),
10508                vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
10509                vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
10510         pr_err("        reason=%08x qualification=%016lx\n",
10511                vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
10512         pr_err("IDTVectoring: info=%08x errcode=%08x\n",
10513                vmcs_read32(IDT_VECTORING_INFO_FIELD),
10514                vmcs_read32(IDT_VECTORING_ERROR_CODE));
10515         pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
10516         if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
10517                 pr_err("TSC Multiplier = 0x%016llx\n",
10518                        vmcs_read64(TSC_MULTIPLIER));
10519         if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
10520                 pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
10521         if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
10522                 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
10523         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
10524                 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
10525         n = vmcs_read32(CR3_TARGET_COUNT);
10526         for (i = 0; i + 1 < n; i += 4)
10527                 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
10528                        i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
10529                        i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
10530         if (i < n)
10531                 pr_err("CR3 target%u=%016lx\n",
10532                        i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
10533         if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
10534                 pr_err("PLE Gap=%08x Window=%08x\n",
10535                        vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
10536         if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
10537                 pr_err("Virtual processor ID = 0x%04x\n",
10538                        vmcs_read16(VIRTUAL_PROCESSOR_ID));
10539 }
10540
10541 /*
10542  * The guest has exited.  See if we can fix it or if we need userspace
10543  * assistance.
10544  */
10545 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
10546 {
10547         struct vcpu_vmx *vmx = to_vmx(vcpu);
10548         u32 exit_reason = vmx->exit_reason;
10549         u32 vectoring_info = vmx->idt_vectoring_info;
10550
10551         trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
10552
10553         /*
10554          * Flush logged GPAs PML buffer, this will make dirty_bitmap more
10555          * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
10556          * querying dirty_bitmap, we only need to kick all vcpus out of guest
10557          * mode as if vcpus is in root mode, the PML buffer must has been
10558          * flushed already.
10559          */
10560         if (enable_pml)
10561                 vmx_flush_pml_buffer(vcpu);
10562
10563         /* If guest state is invalid, start emulating */
10564         if (vmx->emulation_required)
10565                 return handle_invalid_guest_state(vcpu);
10566
10567         if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
10568                 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
10569
10570         if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
10571                 dump_vmcs();
10572                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
10573                 vcpu->run->fail_entry.hardware_entry_failure_reason
10574                         = exit_reason;
10575                 return 0;
10576         }
10577
10578         if (unlikely(vmx->fail)) {
10579                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
10580                 vcpu->run->fail_entry.hardware_entry_failure_reason
10581                         = vmcs_read32(VM_INSTRUCTION_ERROR);
10582                 return 0;
10583         }
10584
10585         /*
10586          * Note:
10587          * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
10588          * delivery event since it indicates guest is accessing MMIO.
10589          * The vm-exit can be triggered again after return to guest that
10590          * will cause infinite loop.
10591          */
10592         if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
10593                         (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
10594                         exit_reason != EXIT_REASON_EPT_VIOLATION &&
10595                         exit_reason != EXIT_REASON_PML_FULL &&
10596                         exit_reason != EXIT_REASON_TASK_SWITCH)) {
10597                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
10598                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
10599                 vcpu->run->internal.ndata = 3;
10600                 vcpu->run->internal.data[0] = vectoring_info;
10601                 vcpu->run->internal.data[1] = exit_reason;
10602                 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
10603                 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
10604                         vcpu->run->internal.ndata++;
10605                         vcpu->run->internal.data[3] =
10606                                 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
10607                 }
10608                 return 0;
10609         }
10610
10611         if (unlikely(!enable_vnmi &&
10612                      vmx->loaded_vmcs->soft_vnmi_blocked)) {
10613                 if (vmx_interrupt_allowed(vcpu)) {
10614                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
10615                 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
10616                            vcpu->arch.nmi_pending) {
10617                         /*
10618                          * This CPU don't support us in finding the end of an
10619                          * NMI-blocked window if the guest runs with IRQs
10620                          * disabled. So we pull the trigger after 1 s of
10621                          * futile waiting, but inform the user about this.
10622                          */
10623                         printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
10624                                "state on VCPU %d after 1 s timeout\n",
10625                                __func__, vcpu->vcpu_id);
10626                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
10627                 }
10628         }
10629
10630         if (exit_reason < kvm_vmx_max_exit_handlers
10631             && kvm_vmx_exit_handlers[exit_reason])
10632                 return kvm_vmx_exit_handlers[exit_reason](vcpu);
10633         else {
10634                 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
10635                                 exit_reason);
10636                 kvm_queue_exception(vcpu, UD_VECTOR);
10637                 return 1;
10638         }
10639 }
10640
10641 /*
10642  * Software based L1D cache flush which is used when microcode providing
10643  * the cache control MSR is not loaded.
10644  *
10645  * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
10646  * flush it is required to read in 64 KiB because the replacement algorithm
10647  * is not exactly LRU. This could be sized at runtime via topology
10648  * information but as all relevant affected CPUs have 32KiB L1D cache size
10649  * there is no point in doing so.
10650  */
10651 static void vmx_l1d_flush(struct kvm_vcpu *vcpu)
10652 {
10653         int size = PAGE_SIZE << L1D_CACHE_ORDER;
10654
10655         /*
10656          * This code is only executed when the the flush mode is 'cond' or
10657          * 'always'
10658          */
10659         if (static_branch_likely(&vmx_l1d_flush_cond)) {
10660                 bool flush_l1d;
10661
10662                 /*
10663                  * Clear the per-vcpu flush bit, it gets set again
10664                  * either from vcpu_run() or from one of the unsafe
10665                  * VMEXIT handlers.
10666                  */
10667                 flush_l1d = vcpu->arch.l1tf_flush_l1d;
10668                 vcpu->arch.l1tf_flush_l1d = false;
10669
10670                 /*
10671                  * Clear the per-cpu flush bit, it gets set again from
10672                  * the interrupt handlers.
10673                  */
10674                 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
10675                 kvm_clear_cpu_l1tf_flush_l1d();
10676
10677                 if (!flush_l1d)
10678                         return;
10679         }
10680
10681         vcpu->stat.l1d_flush++;
10682
10683         if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
10684                 wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
10685                 return;
10686         }
10687
10688         asm volatile(
10689                 /* First ensure the pages are in the TLB */
10690                 "xorl   %%eax, %%eax\n"
10691                 ".Lpopulate_tlb:\n\t"
10692                 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
10693                 "addl   $4096, %%eax\n\t"
10694                 "cmpl   %%eax, %[size]\n\t"
10695                 "jne    .Lpopulate_tlb\n\t"
10696                 "xorl   %%eax, %%eax\n\t"
10697                 "cpuid\n\t"
10698                 /* Now fill the cache */
10699                 "xorl   %%eax, %%eax\n"
10700                 ".Lfill_cache:\n"
10701                 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
10702                 "addl   $64, %%eax\n\t"
10703                 "cmpl   %%eax, %[size]\n\t"
10704                 "jne    .Lfill_cache\n\t"
10705                 "lfence\n"
10706                 :: [flush_pages] "r" (vmx_l1d_flush_pages),
10707                     [size] "r" (size)
10708                 : "eax", "ebx", "ecx", "edx");
10709 }
10710
10711 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
10712 {
10713         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10714
10715         if (is_guest_mode(vcpu) &&
10716                 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10717                 return;
10718
10719         if (irr == -1 || tpr < irr) {
10720                 vmcs_write32(TPR_THRESHOLD, 0);
10721                 return;
10722         }
10723
10724         vmcs_write32(TPR_THRESHOLD, irr);
10725 }
10726
10727 static void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
10728 {
10729         u32 sec_exec_control;
10730
10731         if (!lapic_in_kernel(vcpu))
10732                 return;
10733
10734         if (!flexpriority_enabled &&
10735             !cpu_has_vmx_virtualize_x2apic_mode())
10736                 return;
10737
10738         /* Postpone execution until vmcs01 is the current VMCS. */
10739         if (is_guest_mode(vcpu)) {
10740                 to_vmx(vcpu)->nested.change_vmcs01_virtual_apic_mode = true;
10741                 return;
10742         }
10743
10744         sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
10745         sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
10746                               SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
10747
10748         switch (kvm_get_apic_mode(vcpu)) {
10749         case LAPIC_MODE_INVALID:
10750                 WARN_ONCE(true, "Invalid local APIC state");
10751         case LAPIC_MODE_DISABLED:
10752                 break;
10753         case LAPIC_MODE_XAPIC:
10754                 if (flexpriority_enabled) {
10755                         sec_exec_control |=
10756                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
10757                         vmx_flush_tlb(vcpu, true);
10758                 }
10759                 break;
10760         case LAPIC_MODE_X2APIC:
10761                 if (cpu_has_vmx_virtualize_x2apic_mode())
10762                         sec_exec_control |=
10763                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
10764                 break;
10765         }
10766         vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
10767
10768         vmx_update_msr_bitmap(vcpu);
10769 }
10770
10771 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
10772 {
10773         if (!is_guest_mode(vcpu)) {
10774                 vmcs_write64(APIC_ACCESS_ADDR, hpa);
10775                 vmx_flush_tlb(vcpu, true);
10776         }
10777 }
10778
10779 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
10780 {
10781         u16 status;
10782         u8 old;
10783
10784         if (max_isr == -1)
10785                 max_isr = 0;
10786
10787         status = vmcs_read16(GUEST_INTR_STATUS);
10788         old = status >> 8;
10789         if (max_isr != old) {
10790                 status &= 0xff;
10791                 status |= max_isr << 8;
10792                 vmcs_write16(GUEST_INTR_STATUS, status);
10793         }
10794 }
10795
10796 static void vmx_set_rvi(int vector)
10797 {
10798         u16 status;
10799         u8 old;
10800
10801         if (vector == -1)
10802                 vector = 0;
10803
10804         status = vmcs_read16(GUEST_INTR_STATUS);
10805         old = (u8)status & 0xff;
10806         if ((u8)vector != old) {
10807                 status &= ~0xff;
10808                 status |= (u8)vector;
10809                 vmcs_write16(GUEST_INTR_STATUS, status);
10810         }
10811 }
10812
10813 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
10814 {
10815         /*
10816          * When running L2, updating RVI is only relevant when
10817          * vmcs12 virtual-interrupt-delivery enabled.
10818          * However, it can be enabled only when L1 also
10819          * intercepts external-interrupts and in that case
10820          * we should not update vmcs02 RVI but instead intercept
10821          * interrupt. Therefore, do nothing when running L2.
10822          */
10823         if (!is_guest_mode(vcpu))
10824                 vmx_set_rvi(max_irr);
10825 }
10826
10827 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
10828 {
10829         struct vcpu_vmx *vmx = to_vmx(vcpu);
10830         int max_irr;
10831         bool max_irr_updated;
10832
10833         WARN_ON(!vcpu->arch.apicv_active);
10834         if (pi_test_on(&vmx->pi_desc)) {
10835                 pi_clear_on(&vmx->pi_desc);
10836                 /*
10837                  * IOMMU can write to PIR.ON, so the barrier matters even on UP.
10838                  * But on x86 this is just a compiler barrier anyway.
10839                  */
10840                 smp_mb__after_atomic();
10841                 max_irr_updated =
10842                         kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
10843
10844                 /*
10845                  * If we are running L2 and L1 has a new pending interrupt
10846                  * which can be injected, we should re-evaluate
10847                  * what should be done with this new L1 interrupt.
10848                  * If L1 intercepts external-interrupts, we should
10849                  * exit from L2 to L1. Otherwise, interrupt should be
10850                  * delivered directly to L2.
10851                  */
10852                 if (is_guest_mode(vcpu) && max_irr_updated) {
10853                         if (nested_exit_on_intr(vcpu))
10854                                 kvm_vcpu_exiting_guest_mode(vcpu);
10855                         else
10856                                 kvm_make_request(KVM_REQ_EVENT, vcpu);
10857                 }
10858         } else {
10859                 max_irr = kvm_lapic_find_highest_irr(vcpu);
10860         }
10861         vmx_hwapic_irr_update(vcpu, max_irr);
10862         return max_irr;
10863 }
10864
10865 static u8 vmx_has_apicv_interrupt(struct kvm_vcpu *vcpu)
10866 {
10867         u8 rvi = vmx_get_rvi();
10868         u8 vppr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_PROCPRI);
10869
10870         return ((rvi & 0xf0) > (vppr & 0xf0));
10871 }
10872
10873 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
10874 {
10875         if (!kvm_vcpu_apicv_active(vcpu))
10876                 return;
10877
10878         vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
10879         vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
10880         vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
10881         vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
10882 }
10883
10884 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
10885 {
10886         struct vcpu_vmx *vmx = to_vmx(vcpu);
10887
10888         pi_clear_on(&vmx->pi_desc);
10889         memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
10890 }
10891
10892 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
10893 {
10894         u32 exit_intr_info = 0;
10895         u16 basic_exit_reason = (u16)vmx->exit_reason;
10896
10897         if (!(basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
10898               || basic_exit_reason == EXIT_REASON_EXCEPTION_NMI))
10899                 return;
10900
10901         if (!(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
10902                 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10903         vmx->exit_intr_info = exit_intr_info;
10904
10905         /* if exit due to PF check for async PF */
10906         if (is_page_fault(exit_intr_info))
10907                 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
10908
10909         /* Handle machine checks before interrupts are enabled */
10910         if (basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY ||
10911             is_machine_check(exit_intr_info))
10912                 kvm_machine_check();
10913
10914         /* We need to handle NMIs before interrupts are enabled */
10915         if (is_nmi(exit_intr_info)) {
10916                 kvm_before_interrupt(&vmx->vcpu);
10917                 asm("int $2");
10918                 kvm_after_interrupt(&vmx->vcpu);
10919         }
10920 }
10921
10922 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
10923 {
10924         u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10925
10926         if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
10927                         == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
10928                 unsigned int vector;
10929                 unsigned long entry;
10930                 gate_desc *desc;
10931                 struct vcpu_vmx *vmx = to_vmx(vcpu);
10932 #ifdef CONFIG_X86_64
10933                 unsigned long tmp;
10934 #endif
10935
10936                 vector =  exit_intr_info & INTR_INFO_VECTOR_MASK;
10937                 desc = (gate_desc *)vmx->host_idt_base + vector;
10938                 entry = gate_offset(desc);
10939                 asm volatile(
10940 #ifdef CONFIG_X86_64
10941                         "mov %%" _ASM_SP ", %[sp]\n\t"
10942                         "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
10943                         "push $%c[ss]\n\t"
10944                         "push %[sp]\n\t"
10945 #endif
10946                         "pushf\n\t"
10947                         __ASM_SIZE(push) " $%c[cs]\n\t"
10948                         CALL_NOSPEC
10949                         :
10950 #ifdef CONFIG_X86_64
10951                         [sp]"=&r"(tmp),
10952 #endif
10953                         ASM_CALL_CONSTRAINT
10954                         :
10955                         THUNK_TARGET(entry),
10956                         [ss]"i"(__KERNEL_DS),
10957                         [cs]"i"(__KERNEL_CS)
10958                         );
10959         }
10960 }
10961 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
10962
10963 static bool vmx_has_emulated_msr(int index)
10964 {
10965         switch (index) {
10966         case MSR_IA32_SMBASE:
10967                 /*
10968                  * We cannot do SMM unless we can run the guest in big
10969                  * real mode.
10970                  */
10971                 return enable_unrestricted_guest || emulate_invalid_guest_state;
10972         case MSR_AMD64_VIRT_SPEC_CTRL:
10973                 /* This is AMD only.  */
10974                 return false;
10975         default:
10976                 return true;
10977         }
10978 }
10979
10980 static bool vmx_mpx_supported(void)
10981 {
10982         return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
10983                 (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
10984 }
10985
10986 static bool vmx_xsaves_supported(void)
10987 {
10988         return vmcs_config.cpu_based_2nd_exec_ctrl &
10989                 SECONDARY_EXEC_XSAVES;
10990 }
10991
10992 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
10993 {
10994         u32 exit_intr_info;
10995         bool unblock_nmi;
10996         u8 vector;
10997         bool idtv_info_valid;
10998
10999         idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
11000
11001         if (enable_vnmi) {
11002                 if (vmx->loaded_vmcs->nmi_known_unmasked)
11003                         return;
11004                 /*
11005                  * Can't use vmx->exit_intr_info since we're not sure what
11006                  * the exit reason is.
11007                  */
11008                 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
11009                 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
11010                 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
11011                 /*
11012                  * SDM 3: 27.7.1.2 (September 2008)
11013                  * Re-set bit "block by NMI" before VM entry if vmexit caused by
11014                  * a guest IRET fault.
11015                  * SDM 3: 23.2.2 (September 2008)
11016                  * Bit 12 is undefined in any of the following cases:
11017                  *  If the VM exit sets the valid bit in the IDT-vectoring
11018                  *   information field.
11019                  *  If the VM exit is due to a double fault.
11020                  */
11021                 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
11022                     vector != DF_VECTOR && !idtv_info_valid)
11023                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
11024                                       GUEST_INTR_STATE_NMI);
11025                 else
11026                         vmx->loaded_vmcs->nmi_known_unmasked =
11027                                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
11028                                   & GUEST_INTR_STATE_NMI);
11029         } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
11030                 vmx->loaded_vmcs->vnmi_blocked_time +=
11031                         ktime_to_ns(ktime_sub(ktime_get(),
11032                                               vmx->loaded_vmcs->entry_time));
11033 }
11034
11035 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
11036                                       u32 idt_vectoring_info,
11037                                       int instr_len_field,
11038                                       int error_code_field)
11039 {
11040         u8 vector;
11041         int type;
11042         bool idtv_info_valid;
11043
11044         idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
11045
11046         vcpu->arch.nmi_injected = false;
11047         kvm_clear_exception_queue(vcpu);
11048         kvm_clear_interrupt_queue(vcpu);
11049
11050         if (!idtv_info_valid)
11051                 return;
11052
11053         kvm_make_request(KVM_REQ_EVENT, vcpu);
11054
11055         vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
11056         type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
11057
11058         switch (type) {
11059         case INTR_TYPE_NMI_INTR:
11060                 vcpu->arch.nmi_injected = true;
11061                 /*
11062                  * SDM 3: 27.7.1.2 (September 2008)
11063                  * Clear bit "block by NMI" before VM entry if a NMI
11064                  * delivery faulted.
11065                  */
11066                 vmx_set_nmi_mask(vcpu, false);
11067                 break;
11068         case INTR_TYPE_SOFT_EXCEPTION:
11069                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
11070                 /* fall through */
11071         case INTR_TYPE_HARD_EXCEPTION:
11072                 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
11073                         u32 err = vmcs_read32(error_code_field);
11074                         kvm_requeue_exception_e(vcpu, vector, err);
11075                 } else
11076                         kvm_requeue_exception(vcpu, vector);
11077                 break;
11078         case INTR_TYPE_SOFT_INTR:
11079                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
11080                 /* fall through */
11081         case INTR_TYPE_EXT_INTR:
11082                 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
11083                 break;
11084         default:
11085                 break;
11086         }
11087 }
11088
11089 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
11090 {
11091         __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
11092                                   VM_EXIT_INSTRUCTION_LEN,
11093                                   IDT_VECTORING_ERROR_CODE);
11094 }
11095
11096 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
11097 {
11098         __vmx_complete_interrupts(vcpu,
11099                                   vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
11100                                   VM_ENTRY_INSTRUCTION_LEN,
11101                                   VM_ENTRY_EXCEPTION_ERROR_CODE);
11102
11103         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
11104 }
11105
11106 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
11107 {
11108         int i, nr_msrs;
11109         struct perf_guest_switch_msr *msrs;
11110
11111         msrs = perf_guest_get_msrs(&nr_msrs);
11112
11113         if (!msrs)
11114                 return;
11115
11116         for (i = 0; i < nr_msrs; i++)
11117                 if (msrs[i].host == msrs[i].guest)
11118                         clear_atomic_switch_msr(vmx, msrs[i].msr);
11119                 else
11120                         add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
11121                                         msrs[i].host, false);
11122 }
11123
11124 static void vmx_arm_hv_timer(struct vcpu_vmx *vmx, u32 val)
11125 {
11126         vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, val);
11127         if (!vmx->loaded_vmcs->hv_timer_armed)
11128                 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
11129                               PIN_BASED_VMX_PREEMPTION_TIMER);
11130         vmx->loaded_vmcs->hv_timer_armed = true;
11131 }
11132
11133 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
11134 {
11135         struct vcpu_vmx *vmx = to_vmx(vcpu);
11136         u64 tscl;
11137         u32 delta_tsc;
11138
11139         if (vmx->req_immediate_exit) {
11140                 vmx_arm_hv_timer(vmx, 0);
11141                 return;
11142         }
11143
11144         if (vmx->hv_deadline_tsc != -1) {
11145                 tscl = rdtsc();
11146                 if (vmx->hv_deadline_tsc > tscl)
11147                         /* set_hv_timer ensures the delta fits in 32-bits */
11148                         delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
11149                                 cpu_preemption_timer_multi);
11150                 else
11151                         delta_tsc = 0;
11152
11153                 vmx_arm_hv_timer(vmx, delta_tsc);
11154                 return;
11155         }
11156
11157         if (vmx->loaded_vmcs->hv_timer_armed)
11158                 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
11159                                 PIN_BASED_VMX_PREEMPTION_TIMER);
11160         vmx->loaded_vmcs->hv_timer_armed = false;
11161 }
11162
11163 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
11164 {
11165         struct vcpu_vmx *vmx = to_vmx(vcpu);
11166         unsigned long cr3, cr4, evmcs_rsp;
11167
11168         /* Record the guest's net vcpu time for enforced NMI injections. */
11169         if (unlikely(!enable_vnmi &&
11170                      vmx->loaded_vmcs->soft_vnmi_blocked))
11171                 vmx->loaded_vmcs->entry_time = ktime_get();
11172
11173         /* Don't enter VMX if guest state is invalid, let the exit handler
11174            start emulation until we arrive back to a valid state */
11175         if (vmx->emulation_required)
11176                 return;
11177
11178         if (vmx->ple_window_dirty) {
11179                 vmx->ple_window_dirty = false;
11180                 vmcs_write32(PLE_WINDOW, vmx->ple_window);
11181         }
11182
11183         if (vmx->nested.need_vmcs12_sync) {
11184                 /*
11185                  * hv_evmcs may end up being not mapped after migration (when
11186                  * L2 was running), map it here to make sure vmcs12 changes are
11187                  * properly reflected.
11188                  */
11189                 if (vmx->nested.enlightened_vmcs_enabled &&
11190                     !vmx->nested.hv_evmcs)
11191                         nested_vmx_handle_enlightened_vmptrld(vcpu, false);
11192
11193                 if (vmx->nested.hv_evmcs) {
11194                         copy_vmcs12_to_enlightened(vmx);
11195                         /* All fields are clean */
11196                         vmx->nested.hv_evmcs->hv_clean_fields |=
11197                                 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
11198                 } else {
11199                         copy_vmcs12_to_shadow(vmx);
11200                 }
11201                 vmx->nested.need_vmcs12_sync = false;
11202         }
11203
11204         if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
11205                 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
11206         if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
11207                 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
11208
11209         cr3 = __get_current_cr3_fast();
11210         if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
11211                 vmcs_writel(HOST_CR3, cr3);
11212                 vmx->loaded_vmcs->host_state.cr3 = cr3;
11213         }
11214
11215         cr4 = cr4_read_shadow();
11216         if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
11217                 vmcs_writel(HOST_CR4, cr4);
11218                 vmx->loaded_vmcs->host_state.cr4 = cr4;
11219         }
11220
11221         /* When single-stepping over STI and MOV SS, we must clear the
11222          * corresponding interruptibility bits in the guest state. Otherwise
11223          * vmentry fails as it then expects bit 14 (BS) in pending debug
11224          * exceptions being set, but that's not correct for the guest debugging
11225          * case. */
11226         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
11227                 vmx_set_interrupt_shadow(vcpu, 0);
11228
11229         if (static_cpu_has(X86_FEATURE_PKU) &&
11230             kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
11231             vcpu->arch.pkru != vmx->host_pkru)
11232                 __write_pkru(vcpu->arch.pkru);
11233
11234         atomic_switch_perf_msrs(vmx);
11235
11236         vmx_update_hv_timer(vcpu);
11237
11238         /*
11239          * If this vCPU has touched SPEC_CTRL, restore the guest's value if
11240          * it's non-zero. Since vmentry is serialising on affected CPUs, there
11241          * is no need to worry about the conditional branch over the wrmsr
11242          * being speculatively taken.
11243          */
11244         x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
11245
11246         vmx->__launched = vmx->loaded_vmcs->launched;
11247
11248         evmcs_rsp = static_branch_unlikely(&enable_evmcs) ?
11249                 (unsigned long)&current_evmcs->host_rsp : 0;
11250
11251         if (static_branch_unlikely(&vmx_l1d_should_flush))
11252                 vmx_l1d_flush(vcpu);
11253
11254         asm(
11255                 /* Store host registers */
11256                 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
11257                 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
11258                 "push %%" _ASM_CX " \n\t"
11259                 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
11260                 "je 1f \n\t"
11261                 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
11262                 /* Avoid VMWRITE when Enlightened VMCS is in use */
11263                 "test %%" _ASM_SI ", %%" _ASM_SI " \n\t"
11264                 "jz 2f \n\t"
11265                 "mov %%" _ASM_SP ", (%%" _ASM_SI ") \n\t"
11266                 "jmp 1f \n\t"
11267                 "2: \n\t"
11268                 __ex("vmwrite %%" _ASM_SP ", %%" _ASM_DX) "\n\t"
11269                 "1: \n\t"
11270                 /* Reload cr2 if changed */
11271                 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
11272                 "mov %%cr2, %%" _ASM_DX " \n\t"
11273                 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
11274                 "je 3f \n\t"
11275                 "mov %%" _ASM_AX", %%cr2 \n\t"
11276                 "3: \n\t"
11277                 /* Check if vmlaunch of vmresume is needed */
11278                 "cmpl $0, %c[launched](%0) \n\t"
11279                 /* Load guest registers.  Don't clobber flags. */
11280                 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
11281                 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
11282                 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
11283                 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
11284                 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
11285                 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
11286 #ifdef CONFIG_X86_64
11287                 "mov %c[r8](%0),  %%r8  \n\t"
11288                 "mov %c[r9](%0),  %%r9  \n\t"
11289                 "mov %c[r10](%0), %%r10 \n\t"
11290                 "mov %c[r11](%0), %%r11 \n\t"
11291                 "mov %c[r12](%0), %%r12 \n\t"
11292                 "mov %c[r13](%0), %%r13 \n\t"
11293                 "mov %c[r14](%0), %%r14 \n\t"
11294                 "mov %c[r15](%0), %%r15 \n\t"
11295 #endif
11296                 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
11297
11298                 /* Enter guest mode */
11299                 "jne 1f \n\t"
11300                 __ex("vmlaunch") "\n\t"
11301                 "jmp 2f \n\t"
11302                 "1: " __ex("vmresume") "\n\t"
11303                 "2: "
11304                 /* Save guest registers, load host registers, keep flags */
11305                 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
11306                 "pop %0 \n\t"
11307                 "setbe %c[fail](%0)\n\t"
11308                 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
11309                 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
11310                 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
11311                 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
11312                 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
11313                 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
11314                 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
11315 #ifdef CONFIG_X86_64
11316                 "mov %%r8,  %c[r8](%0) \n\t"
11317                 "mov %%r9,  %c[r9](%0) \n\t"
11318                 "mov %%r10, %c[r10](%0) \n\t"
11319                 "mov %%r11, %c[r11](%0) \n\t"
11320                 "mov %%r12, %c[r12](%0) \n\t"
11321                 "mov %%r13, %c[r13](%0) \n\t"
11322                 "mov %%r14, %c[r14](%0) \n\t"
11323                 "mov %%r15, %c[r15](%0) \n\t"
11324                 /*
11325                 * Clear host registers marked as clobbered to prevent
11326                 * speculative use.
11327                 */
11328                 "xor %%r8d,  %%r8d \n\t"
11329                 "xor %%r9d,  %%r9d \n\t"
11330                 "xor %%r10d, %%r10d \n\t"
11331                 "xor %%r11d, %%r11d \n\t"
11332                 "xor %%r12d, %%r12d \n\t"
11333                 "xor %%r13d, %%r13d \n\t"
11334                 "xor %%r14d, %%r14d \n\t"
11335                 "xor %%r15d, %%r15d \n\t"
11336 #endif
11337                 "mov %%cr2, %%" _ASM_AX "   \n\t"
11338                 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
11339
11340                 "xor %%eax, %%eax \n\t"
11341                 "xor %%ebx, %%ebx \n\t"
11342                 "xor %%esi, %%esi \n\t"
11343                 "xor %%edi, %%edi \n\t"
11344                 "pop  %%" _ASM_BP "; pop  %%" _ASM_DX " \n\t"
11345                 ".pushsection .rodata \n\t"
11346                 ".global vmx_return \n\t"
11347                 "vmx_return: " _ASM_PTR " 2b \n\t"
11348                 ".popsection"
11349               : : "c"(vmx), "d"((unsigned long)HOST_RSP), "S"(evmcs_rsp),
11350                 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
11351                 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
11352                 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
11353                 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
11354                 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
11355                 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
11356                 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
11357                 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
11358                 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
11359                 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
11360 #ifdef CONFIG_X86_64
11361                 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
11362                 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
11363                 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
11364                 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
11365                 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
11366                 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
11367                 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
11368                 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
11369 #endif
11370                 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
11371                 [wordsize]"i"(sizeof(ulong))
11372               : "cc", "memory"
11373 #ifdef CONFIG_X86_64
11374                 , "rax", "rbx", "rdi"
11375                 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
11376 #else
11377                 , "eax", "ebx", "edi"
11378 #endif
11379               );
11380
11381         /*
11382          * We do not use IBRS in the kernel. If this vCPU has used the
11383          * SPEC_CTRL MSR it may have left it on; save the value and
11384          * turn it off. This is much more efficient than blindly adding
11385          * it to the atomic save/restore list. Especially as the former
11386          * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
11387          *
11388          * For non-nested case:
11389          * If the L01 MSR bitmap does not intercept the MSR, then we need to
11390          * save it.
11391          *
11392          * For nested case:
11393          * If the L02 MSR bitmap does not intercept the MSR, then we need to
11394          * save it.
11395          */
11396         if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
11397                 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
11398
11399         x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
11400
11401         /* Eliminate branch target predictions from guest mode */
11402         vmexit_fill_RSB();
11403
11404         /* All fields are clean at this point */
11405         if (static_branch_unlikely(&enable_evmcs))
11406                 current_evmcs->hv_clean_fields |=
11407                         HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
11408
11409         /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
11410         if (vmx->host_debugctlmsr)
11411                 update_debugctlmsr(vmx->host_debugctlmsr);
11412
11413 #ifndef CONFIG_X86_64
11414         /*
11415          * The sysexit path does not restore ds/es, so we must set them to
11416          * a reasonable value ourselves.
11417          *
11418          * We can't defer this to vmx_prepare_switch_to_host() since that
11419          * function may be executed in interrupt context, which saves and
11420          * restore segments around it, nullifying its effect.
11421          */
11422         loadsegment(ds, __USER_DS);
11423         loadsegment(es, __USER_DS);
11424 #endif
11425
11426         vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
11427                                   | (1 << VCPU_EXREG_RFLAGS)
11428                                   | (1 << VCPU_EXREG_PDPTR)
11429                                   | (1 << VCPU_EXREG_SEGMENTS)
11430                                   | (1 << VCPU_EXREG_CR3));
11431         vcpu->arch.regs_dirty = 0;
11432
11433         /*
11434          * eager fpu is enabled if PKEY is supported and CR4 is switched
11435          * back on host, so it is safe to read guest PKRU from current
11436          * XSAVE.
11437          */
11438         if (static_cpu_has(X86_FEATURE_PKU) &&
11439             kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
11440                 vcpu->arch.pkru = __read_pkru();
11441                 if (vcpu->arch.pkru != vmx->host_pkru)
11442                         __write_pkru(vmx->host_pkru);
11443         }
11444
11445         vmx->nested.nested_run_pending = 0;
11446         vmx->idt_vectoring_info = 0;
11447
11448         vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
11449         if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
11450                 return;
11451
11452         vmx->loaded_vmcs->launched = 1;
11453         vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
11454
11455         vmx_complete_atomic_exit(vmx);
11456         vmx_recover_nmi_blocking(vmx);
11457         vmx_complete_interrupts(vmx);
11458 }
11459 STACK_FRAME_NON_STANDARD(vmx_vcpu_run);
11460
11461 static struct kvm *vmx_vm_alloc(void)
11462 {
11463         struct kvm_vmx *kvm_vmx = vzalloc(sizeof(struct kvm_vmx));
11464         return &kvm_vmx->kvm;
11465 }
11466
11467 static void vmx_vm_free(struct kvm *kvm)
11468 {
11469         vfree(to_kvm_vmx(kvm));
11470 }
11471
11472 static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
11473 {
11474         struct vcpu_vmx *vmx = to_vmx(vcpu);
11475         int cpu;
11476
11477         if (vmx->loaded_vmcs == vmcs)
11478                 return;
11479
11480         cpu = get_cpu();
11481         vmx_vcpu_put(vcpu);
11482         vmx->loaded_vmcs = vmcs;
11483         vmx_vcpu_load(vcpu, cpu);
11484         put_cpu();
11485
11486         vm_entry_controls_reset_shadow(vmx);
11487         vm_exit_controls_reset_shadow(vmx);
11488         vmx_segment_cache_clear(vmx);
11489 }
11490
11491 /*
11492  * Ensure that the current vmcs of the logical processor is the
11493  * vmcs01 of the vcpu before calling free_nested().
11494  */
11495 static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu)
11496 {
11497         vcpu_load(vcpu);
11498         vmx_switch_vmcs(vcpu, &to_vmx(vcpu)->vmcs01);
11499         free_nested(vcpu);
11500         vcpu_put(vcpu);
11501 }
11502
11503 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
11504 {
11505         struct vcpu_vmx *vmx = to_vmx(vcpu);
11506
11507         if (enable_pml)
11508                 vmx_destroy_pml_buffer(vmx);
11509         free_vpid(vmx->vpid);
11510         leave_guest_mode(vcpu);
11511         vmx_free_vcpu_nested(vcpu);
11512         free_loaded_vmcs(vmx->loaded_vmcs);
11513         kfree(vmx->guest_msrs);
11514         kvm_vcpu_uninit(vcpu);
11515         kmem_cache_free(kvm_vcpu_cache, vmx);
11516 }
11517
11518 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
11519 {
11520         int err;
11521         struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
11522         unsigned long *msr_bitmap;
11523         int cpu;
11524
11525         if (!vmx)
11526                 return ERR_PTR(-ENOMEM);
11527
11528         vmx->vpid = allocate_vpid();
11529
11530         err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
11531         if (err)
11532                 goto free_vcpu;
11533
11534         err = -ENOMEM;
11535
11536         /*
11537          * If PML is turned on, failure on enabling PML just results in failure
11538          * of creating the vcpu, therefore we can simplify PML logic (by
11539          * avoiding dealing with cases, such as enabling PML partially on vcpus
11540          * for the guest, etc.
11541          */
11542         if (enable_pml) {
11543                 vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
11544                 if (!vmx->pml_pg)
11545                         goto uninit_vcpu;
11546         }
11547
11548         vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
11549         BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
11550                      > PAGE_SIZE);
11551
11552         if (!vmx->guest_msrs)
11553                 goto free_pml;
11554
11555         err = alloc_loaded_vmcs(&vmx->vmcs01);
11556         if (err < 0)
11557                 goto free_msrs;
11558
11559         msr_bitmap = vmx->vmcs01.msr_bitmap;
11560         vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
11561         vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
11562         vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
11563         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
11564         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
11565         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
11566         vmx->msr_bitmap_mode = 0;
11567
11568         vmx->loaded_vmcs = &vmx->vmcs01;
11569         cpu = get_cpu();
11570         vmx_vcpu_load(&vmx->vcpu, cpu);
11571         vmx->vcpu.cpu = cpu;
11572         vmx_vcpu_setup(vmx);
11573         vmx_vcpu_put(&vmx->vcpu);
11574         put_cpu();
11575         if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
11576                 err = alloc_apic_access_page(kvm);
11577                 if (err)
11578                         goto free_vmcs;
11579         }
11580
11581         if (enable_ept && !enable_unrestricted_guest) {
11582                 err = init_rmode_identity_map(kvm);
11583                 if (err)
11584                         goto free_vmcs;
11585         }
11586
11587         if (nested)
11588                 nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
11589                                            kvm_vcpu_apicv_active(&vmx->vcpu));
11590
11591         vmx->nested.posted_intr_nv = -1;
11592         vmx->nested.current_vmptr = -1ull;
11593
11594         vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
11595
11596         /*
11597          * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
11598          * or POSTED_INTR_WAKEUP_VECTOR.
11599          */
11600         vmx->pi_desc.nv = POSTED_INTR_VECTOR;
11601         vmx->pi_desc.sn = 1;
11602
11603         return &vmx->vcpu;
11604
11605 free_vmcs:
11606         free_loaded_vmcs(vmx->loaded_vmcs);
11607 free_msrs:
11608         kfree(vmx->guest_msrs);
11609 free_pml:
11610         vmx_destroy_pml_buffer(vmx);
11611 uninit_vcpu:
11612         kvm_vcpu_uninit(&vmx->vcpu);
11613 free_vcpu:
11614         free_vpid(vmx->vpid);
11615         kmem_cache_free(kvm_vcpu_cache, vmx);
11616         return ERR_PTR(err);
11617 }
11618
11619 #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"
11620 #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"
11621
11622 static int vmx_vm_init(struct kvm *kvm)
11623 {
11624         spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
11625
11626         if (!ple_gap)
11627                 kvm->arch.pause_in_guest = true;
11628
11629         if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
11630                 switch (l1tf_mitigation) {
11631                 case L1TF_MITIGATION_OFF:
11632                 case L1TF_MITIGATION_FLUSH_NOWARN:
11633                         /* 'I explicitly don't care' is set */
11634                         break;
11635                 case L1TF_MITIGATION_FLUSH:
11636                 case L1TF_MITIGATION_FLUSH_NOSMT:
11637                 case L1TF_MITIGATION_FULL:
11638                         /*
11639                          * Warn upon starting the first VM in a potentially
11640                          * insecure environment.
11641                          */
11642                         if (cpu_smt_control == CPU_SMT_ENABLED)
11643                                 pr_warn_once(L1TF_MSG_SMT);
11644                         if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
11645                                 pr_warn_once(L1TF_MSG_L1D);
11646                         break;
11647                 case L1TF_MITIGATION_FULL_FORCE:
11648                         /* Flush is enforced */
11649                         break;
11650                 }
11651         }
11652         return 0;
11653 }
11654
11655 static void __init vmx_check_processor_compat(void *rtn)
11656 {
11657         struct vmcs_config vmcs_conf;
11658
11659         *(int *)rtn = 0;
11660         if (setup_vmcs_config(&vmcs_conf) < 0)
11661                 *(int *)rtn = -EIO;
11662         nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, enable_apicv);
11663         if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
11664                 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
11665                                 smp_processor_id());
11666                 *(int *)rtn = -EIO;
11667         }
11668 }
11669
11670 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
11671 {
11672         u8 cache;
11673         u64 ipat = 0;
11674
11675         /* For VT-d and EPT combination
11676          * 1. MMIO: always map as UC
11677          * 2. EPT with VT-d:
11678          *   a. VT-d without snooping control feature: can't guarantee the
11679          *      result, try to trust guest.
11680          *   b. VT-d with snooping control feature: snooping control feature of
11681          *      VT-d engine can guarantee the cache correctness. Just set it
11682          *      to WB to keep consistent with host. So the same as item 3.
11683          * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
11684          *    consistent with host MTRR
11685          */
11686         if (is_mmio) {
11687                 cache = MTRR_TYPE_UNCACHABLE;
11688                 goto exit;
11689         }
11690
11691         if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
11692                 ipat = VMX_EPT_IPAT_BIT;
11693                 cache = MTRR_TYPE_WRBACK;
11694                 goto exit;
11695         }
11696
11697         if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
11698                 ipat = VMX_EPT_IPAT_BIT;
11699                 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
11700                         cache = MTRR_TYPE_WRBACK;
11701                 else
11702                         cache = MTRR_TYPE_UNCACHABLE;
11703                 goto exit;
11704         }
11705
11706         cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
11707
11708 exit:
11709         return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
11710 }
11711
11712 static int vmx_get_lpage_level(void)
11713 {
11714         if (enable_ept && !cpu_has_vmx_ept_1g_page())
11715                 return PT_DIRECTORY_LEVEL;
11716         else
11717                 /* For shadow and EPT supported 1GB page */
11718                 return PT_PDPE_LEVEL;
11719 }
11720
11721 static void vmcs_set_secondary_exec_control(u32 new_ctl)
11722 {
11723         /*
11724          * These bits in the secondary execution controls field
11725          * are dynamic, the others are mostly based on the hypervisor
11726          * architecture and the guest's CPUID.  Do not touch the
11727          * dynamic bits.
11728          */
11729         u32 mask =
11730                 SECONDARY_EXEC_SHADOW_VMCS |
11731                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
11732                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
11733                 SECONDARY_EXEC_DESC;
11734
11735         u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
11736
11737         vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
11738                      (new_ctl & ~mask) | (cur_ctl & mask));
11739 }
11740
11741 /*
11742  * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
11743  * (indicating "allowed-1") if they are supported in the guest's CPUID.
11744  */
11745 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
11746 {
11747         struct vcpu_vmx *vmx = to_vmx(vcpu);
11748         struct kvm_cpuid_entry2 *entry;
11749
11750         vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
11751         vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
11752
11753 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do {            \
11754         if (entry && (entry->_reg & (_cpuid_mask)))                     \
11755                 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask);     \
11756 } while (0)
11757
11758         entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
11759         cr4_fixed1_update(X86_CR4_VME,        edx, bit(X86_FEATURE_VME));
11760         cr4_fixed1_update(X86_CR4_PVI,        edx, bit(X86_FEATURE_VME));
11761         cr4_fixed1_update(X86_CR4_TSD,        edx, bit(X86_FEATURE_TSC));
11762         cr4_fixed1_update(X86_CR4_DE,         edx, bit(X86_FEATURE_DE));
11763         cr4_fixed1_update(X86_CR4_PSE,        edx, bit(X86_FEATURE_PSE));
11764         cr4_fixed1_update(X86_CR4_PAE,        edx, bit(X86_FEATURE_PAE));
11765         cr4_fixed1_update(X86_CR4_MCE,        edx, bit(X86_FEATURE_MCE));
11766         cr4_fixed1_update(X86_CR4_PGE,        edx, bit(X86_FEATURE_PGE));
11767         cr4_fixed1_update(X86_CR4_OSFXSR,     edx, bit(X86_FEATURE_FXSR));
11768         cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
11769         cr4_fixed1_update(X86_CR4_VMXE,       ecx, bit(X86_FEATURE_VMX));
11770         cr4_fixed1_update(X86_CR4_SMXE,       ecx, bit(X86_FEATURE_SMX));
11771         cr4_fixed1_update(X86_CR4_PCIDE,      ecx, bit(X86_FEATURE_PCID));
11772         cr4_fixed1_update(X86_CR4_OSXSAVE,    ecx, bit(X86_FEATURE_XSAVE));
11773
11774         entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
11775         cr4_fixed1_update(X86_CR4_FSGSBASE,   ebx, bit(X86_FEATURE_FSGSBASE));
11776         cr4_fixed1_update(X86_CR4_SMEP,       ebx, bit(X86_FEATURE_SMEP));
11777         cr4_fixed1_update(X86_CR4_SMAP,       ebx, bit(X86_FEATURE_SMAP));
11778         cr4_fixed1_update(X86_CR4_PKE,        ecx, bit(X86_FEATURE_PKU));
11779         cr4_fixed1_update(X86_CR4_UMIP,       ecx, bit(X86_FEATURE_UMIP));
11780
11781 #undef cr4_fixed1_update
11782 }
11783
11784 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
11785 {
11786         struct vcpu_vmx *vmx = to_vmx(vcpu);
11787
11788         if (kvm_mpx_supported()) {
11789                 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
11790
11791                 if (mpx_enabled) {
11792                         vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
11793                         vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
11794                 } else {
11795                         vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
11796                         vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
11797                 }
11798         }
11799 }
11800
11801 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
11802 {
11803         struct vcpu_vmx *vmx = to_vmx(vcpu);
11804
11805         if (cpu_has_secondary_exec_ctrls()) {
11806                 vmx_compute_secondary_exec_control(vmx);
11807                 vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
11808         }
11809
11810         if (nested_vmx_allowed(vcpu))
11811                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
11812                         FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
11813         else
11814                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
11815                         ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
11816
11817         if (nested_vmx_allowed(vcpu)) {
11818                 nested_vmx_cr_fixed1_bits_update(vcpu);
11819                 nested_vmx_entry_exit_ctls_update(vcpu);
11820         }
11821 }
11822
11823 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
11824 {
11825         if (func == 1 && nested)
11826                 entry->ecx |= bit(X86_FEATURE_VMX);
11827 }
11828
11829 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
11830                 struct x86_exception *fault)
11831 {
11832         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11833         struct vcpu_vmx *vmx = to_vmx(vcpu);
11834         u32 exit_reason;
11835         unsigned long exit_qualification = vcpu->arch.exit_qualification;
11836
11837         if (vmx->nested.pml_full) {
11838                 exit_reason = EXIT_REASON_PML_FULL;
11839                 vmx->nested.pml_full = false;
11840                 exit_qualification &= INTR_INFO_UNBLOCK_NMI;
11841         } else if (fault->error_code & PFERR_RSVD_MASK)
11842                 exit_reason = EXIT_REASON_EPT_MISCONFIG;
11843         else
11844                 exit_reason = EXIT_REASON_EPT_VIOLATION;
11845
11846         nested_vmx_vmexit(vcpu, exit_reason, 0, exit_qualification);
11847         vmcs12->guest_physical_address = fault->address;
11848 }
11849
11850 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu)
11851 {
11852         return nested_ept_get_cr3(vcpu) & VMX_EPTP_AD_ENABLE_BIT;
11853 }
11854
11855 /* Callbacks for nested_ept_init_mmu_context: */
11856
11857 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
11858 {
11859         /* return the page table to be shadowed - in our case, EPT12 */
11860         return get_vmcs12(vcpu)->ept_pointer;
11861 }
11862
11863 static void nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
11864 {
11865         WARN_ON(mmu_is_nested(vcpu));
11866
11867         vcpu->arch.mmu = &vcpu->arch.guest_mmu;
11868         kvm_init_shadow_ept_mmu(vcpu,
11869                         to_vmx(vcpu)->nested.msrs.ept_caps &
11870                         VMX_EPT_EXECUTE_ONLY_BIT,
11871                         nested_ept_ad_enabled(vcpu),
11872                         nested_ept_get_cr3(vcpu));
11873         vcpu->arch.mmu->set_cr3           = vmx_set_cr3;
11874         vcpu->arch.mmu->get_cr3           = nested_ept_get_cr3;
11875         vcpu->arch.mmu->inject_page_fault = nested_ept_inject_page_fault;
11876         vcpu->arch.mmu->get_pdptr         = kvm_pdptr_read;
11877
11878         vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
11879 }
11880
11881 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
11882 {
11883         vcpu->arch.mmu = &vcpu->arch.root_mmu;
11884         vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
11885 }
11886
11887 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
11888                                             u16 error_code)
11889 {
11890         bool inequality, bit;
11891
11892         bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
11893         inequality =
11894                 (error_code & vmcs12->page_fault_error_code_mask) !=
11895                  vmcs12->page_fault_error_code_match;
11896         return inequality ^ bit;
11897 }
11898
11899 static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
11900                 struct x86_exception *fault)
11901 {
11902         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11903
11904         WARN_ON(!is_guest_mode(vcpu));
11905
11906         if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code) &&
11907                 !to_vmx(vcpu)->nested.nested_run_pending) {
11908                 vmcs12->vm_exit_intr_error_code = fault->error_code;
11909                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
11910                                   PF_VECTOR | INTR_TYPE_HARD_EXCEPTION |
11911                                   INTR_INFO_DELIVER_CODE_MASK | INTR_INFO_VALID_MASK,
11912                                   fault->address);
11913         } else {
11914                 kvm_inject_page_fault(vcpu, fault);
11915         }
11916 }
11917
11918 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
11919                                                  struct vmcs12 *vmcs12);
11920
11921 static void nested_get_vmcs12_pages(struct kvm_vcpu *vcpu)
11922 {
11923         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11924         struct vcpu_vmx *vmx = to_vmx(vcpu);
11925         struct page *page;
11926         u64 hpa;
11927
11928         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
11929                 /*
11930                  * Translate L1 physical address to host physical
11931                  * address for vmcs02. Keep the page pinned, so this
11932                  * physical address remains valid. We keep a reference
11933                  * to it so we can release it later.
11934                  */
11935                 if (vmx->nested.apic_access_page) { /* shouldn't happen */
11936                         kvm_release_page_dirty(vmx->nested.apic_access_page);
11937                         vmx->nested.apic_access_page = NULL;
11938                 }
11939                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->apic_access_addr);
11940                 /*
11941                  * If translation failed, no matter: This feature asks
11942                  * to exit when accessing the given address, and if it
11943                  * can never be accessed, this feature won't do
11944                  * anything anyway.
11945                  */
11946                 if (!is_error_page(page)) {
11947                         vmx->nested.apic_access_page = page;
11948                         hpa = page_to_phys(vmx->nested.apic_access_page);
11949                         vmcs_write64(APIC_ACCESS_ADDR, hpa);
11950                 } else {
11951                         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
11952                                         SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
11953                 }
11954         }
11955
11956         if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
11957                 if (vmx->nested.virtual_apic_page) { /* shouldn't happen */
11958                         kvm_release_page_dirty(vmx->nested.virtual_apic_page);
11959                         vmx->nested.virtual_apic_page = NULL;
11960                 }
11961                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->virtual_apic_page_addr);
11962
11963                 /*
11964                  * If translation failed, VM entry will fail because
11965                  * prepare_vmcs02 set VIRTUAL_APIC_PAGE_ADDR to -1ull.
11966                  * Failing the vm entry is _not_ what the processor
11967                  * does but it's basically the only possibility we
11968                  * have.  We could still enter the guest if CR8 load
11969                  * exits are enabled, CR8 store exits are enabled, and
11970                  * virtualize APIC access is disabled; in this case
11971                  * the processor would never use the TPR shadow and we
11972                  * could simply clear the bit from the execution
11973                  * control.  But such a configuration is useless, so
11974                  * let's keep the code simple.
11975                  */
11976                 if (!is_error_page(page)) {
11977                         vmx->nested.virtual_apic_page = page;
11978                         hpa = page_to_phys(vmx->nested.virtual_apic_page);
11979                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, hpa);
11980                 }
11981         }
11982
11983         if (nested_cpu_has_posted_intr(vmcs12)) {
11984                 if (vmx->nested.pi_desc_page) { /* shouldn't happen */
11985                         kunmap(vmx->nested.pi_desc_page);
11986                         kvm_release_page_dirty(vmx->nested.pi_desc_page);
11987                         vmx->nested.pi_desc_page = NULL;
11988                 }
11989                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->posted_intr_desc_addr);
11990                 if (is_error_page(page))
11991                         return;
11992                 vmx->nested.pi_desc_page = page;
11993                 vmx->nested.pi_desc = kmap(vmx->nested.pi_desc_page);
11994                 vmx->nested.pi_desc =
11995                         (struct pi_desc *)((void *)vmx->nested.pi_desc +
11996                         (unsigned long)(vmcs12->posted_intr_desc_addr &
11997                         (PAGE_SIZE - 1)));
11998                 vmcs_write64(POSTED_INTR_DESC_ADDR,
11999                         page_to_phys(vmx->nested.pi_desc_page) +
12000                         (unsigned long)(vmcs12->posted_intr_desc_addr &
12001                         (PAGE_SIZE - 1)));
12002         }
12003         if (nested_vmx_prepare_msr_bitmap(vcpu, vmcs12))
12004                 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
12005                               CPU_BASED_USE_MSR_BITMAPS);
12006         else
12007                 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
12008                                 CPU_BASED_USE_MSR_BITMAPS);
12009 }
12010
12011 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
12012 {
12013         u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
12014         struct vcpu_vmx *vmx = to_vmx(vcpu);
12015
12016         /*
12017          * A timer value of zero is architecturally guaranteed to cause
12018          * a VMExit prior to executing any instructions in the guest.
12019          */
12020         if (preemption_timeout == 0) {
12021                 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
12022                 return;
12023         }
12024
12025         if (vcpu->arch.virtual_tsc_khz == 0)
12026                 return;
12027
12028         preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
12029         preemption_timeout *= 1000000;
12030         do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
12031         hrtimer_start(&vmx->nested.preemption_timer,
12032                       ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
12033 }
12034
12035 static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,
12036                                                struct vmcs12 *vmcs12)
12037 {
12038         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
12039                 return 0;
12040
12041         if (!page_address_valid(vcpu, vmcs12->io_bitmap_a) ||
12042             !page_address_valid(vcpu, vmcs12->io_bitmap_b))
12043                 return -EINVAL;
12044
12045         return 0;
12046 }
12047
12048 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
12049                                                 struct vmcs12 *vmcs12)
12050 {
12051         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
12052                 return 0;
12053
12054         if (!page_address_valid(vcpu, vmcs12->msr_bitmap))
12055                 return -EINVAL;
12056
12057         return 0;
12058 }
12059
12060 static int nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu *vcpu,
12061                                                 struct vmcs12 *vmcs12)
12062 {
12063         if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
12064                 return 0;
12065
12066         if (!page_address_valid(vcpu, vmcs12->virtual_apic_page_addr))
12067                 return -EINVAL;
12068
12069         return 0;
12070 }
12071
12072 /*
12073  * Merge L0's and L1's MSR bitmap, return false to indicate that
12074  * we do not use the hardware.
12075  */
12076 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
12077                                                  struct vmcs12 *vmcs12)
12078 {
12079         int msr;
12080         struct page *page;
12081         unsigned long *msr_bitmap_l1;
12082         unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.vmcs02.msr_bitmap;
12083         /*
12084          * pred_cmd & spec_ctrl are trying to verify two things:
12085          *
12086          * 1. L0 gave a permission to L1 to actually passthrough the MSR. This
12087          *    ensures that we do not accidentally generate an L02 MSR bitmap
12088          *    from the L12 MSR bitmap that is too permissive.
12089          * 2. That L1 or L2s have actually used the MSR. This avoids
12090          *    unnecessarily merging of the bitmap if the MSR is unused. This
12091          *    works properly because we only update the L01 MSR bitmap lazily.
12092          *    So even if L0 should pass L1 these MSRs, the L01 bitmap is only
12093          *    updated to reflect this when L1 (or its L2s) actually write to
12094          *    the MSR.
12095          */
12096         bool pred_cmd = !msr_write_intercepted_l01(vcpu, MSR_IA32_PRED_CMD);
12097         bool spec_ctrl = !msr_write_intercepted_l01(vcpu, MSR_IA32_SPEC_CTRL);
12098
12099         /* Nothing to do if the MSR bitmap is not in use.  */
12100         if (!cpu_has_vmx_msr_bitmap() ||
12101             !nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
12102                 return false;
12103
12104         if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
12105             !pred_cmd && !spec_ctrl)
12106                 return false;
12107
12108         page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->msr_bitmap);
12109         if (is_error_page(page))
12110                 return false;
12111
12112         msr_bitmap_l1 = (unsigned long *)kmap(page);
12113         if (nested_cpu_has_apic_reg_virt(vmcs12)) {
12114                 /*
12115                  * L0 need not intercept reads for MSRs between 0x800 and 0x8ff, it
12116                  * just lets the processor take the value from the virtual-APIC page;
12117                  * take those 256 bits directly from the L1 bitmap.
12118                  */
12119                 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
12120                         unsigned word = msr / BITS_PER_LONG;
12121                         msr_bitmap_l0[word] = msr_bitmap_l1[word];
12122                         msr_bitmap_l0[word + (0x800 / sizeof(long))] = ~0;
12123                 }
12124         } else {
12125                 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
12126                         unsigned word = msr / BITS_PER_LONG;
12127                         msr_bitmap_l0[word] = ~0;
12128                         msr_bitmap_l0[word + (0x800 / sizeof(long))] = ~0;
12129                 }
12130         }
12131
12132         nested_vmx_disable_intercept_for_msr(
12133                 msr_bitmap_l1, msr_bitmap_l0,
12134                 X2APIC_MSR(APIC_TASKPRI),
12135                 MSR_TYPE_W);
12136
12137         if (nested_cpu_has_vid(vmcs12)) {
12138                 nested_vmx_disable_intercept_for_msr(
12139                         msr_bitmap_l1, msr_bitmap_l0,
12140                         X2APIC_MSR(APIC_EOI),
12141                         MSR_TYPE_W);
12142                 nested_vmx_disable_intercept_for_msr(
12143                         msr_bitmap_l1, msr_bitmap_l0,
12144                         X2APIC_MSR(APIC_SELF_IPI),
12145                         MSR_TYPE_W);
12146         }
12147
12148         if (spec_ctrl)
12149                 nested_vmx_disable_intercept_for_msr(
12150                                         msr_bitmap_l1, msr_bitmap_l0,
12151                                         MSR_IA32_SPEC_CTRL,
12152                                         MSR_TYPE_R | MSR_TYPE_W);
12153
12154         if (pred_cmd)
12155                 nested_vmx_disable_intercept_for_msr(
12156                                         msr_bitmap_l1, msr_bitmap_l0,
12157                                         MSR_IA32_PRED_CMD,
12158                                         MSR_TYPE_W);
12159
12160         kunmap(page);
12161         kvm_release_page_clean(page);
12162
12163         return true;
12164 }
12165
12166 static void nested_cache_shadow_vmcs12(struct kvm_vcpu *vcpu,
12167                                        struct vmcs12 *vmcs12)
12168 {
12169         struct vmcs12 *shadow;
12170         struct page *page;
12171
12172         if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
12173             vmcs12->vmcs_link_pointer == -1ull)
12174                 return;
12175
12176         shadow = get_shadow_vmcs12(vcpu);
12177         page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->vmcs_link_pointer);
12178
12179         memcpy(shadow, kmap(page), VMCS12_SIZE);
12180
12181         kunmap(page);
12182         kvm_release_page_clean(page);
12183 }
12184
12185 static void nested_flush_cached_shadow_vmcs12(struct kvm_vcpu *vcpu,
12186                                               struct vmcs12 *vmcs12)
12187 {
12188         struct vcpu_vmx *vmx = to_vmx(vcpu);
12189
12190         if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
12191             vmcs12->vmcs_link_pointer == -1ull)
12192                 return;
12193
12194         kvm_write_guest(vmx->vcpu.kvm, vmcs12->vmcs_link_pointer,
12195                         get_shadow_vmcs12(vcpu), VMCS12_SIZE);
12196 }
12197
12198 static int nested_vmx_check_apic_access_controls(struct kvm_vcpu *vcpu,
12199                                           struct vmcs12 *vmcs12)
12200 {
12201         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
12202             !page_address_valid(vcpu, vmcs12->apic_access_addr))
12203                 return -EINVAL;
12204         else
12205                 return 0;
12206 }
12207
12208 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
12209                                            struct vmcs12 *vmcs12)
12210 {
12211         if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
12212             !nested_cpu_has_apic_reg_virt(vmcs12) &&
12213             !nested_cpu_has_vid(vmcs12) &&
12214             !nested_cpu_has_posted_intr(vmcs12))
12215                 return 0;
12216
12217         /*
12218          * If virtualize x2apic mode is enabled,
12219          * virtualize apic access must be disabled.
12220          */
12221         if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
12222             nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
12223                 return -EINVAL;
12224
12225         /*
12226          * If virtual interrupt delivery is enabled,
12227          * we must exit on external interrupts.
12228          */
12229         if (nested_cpu_has_vid(vmcs12) &&
12230            !nested_exit_on_intr(vcpu))
12231                 return -EINVAL;
12232
12233         /*
12234          * bits 15:8 should be zero in posted_intr_nv,
12235          * the descriptor address has been already checked
12236          * in nested_get_vmcs12_pages.
12237          *
12238          * bits 5:0 of posted_intr_desc_addr should be zero.
12239          */
12240         if (nested_cpu_has_posted_intr(vmcs12) &&
12241            (!nested_cpu_has_vid(vmcs12) ||
12242             !nested_exit_intr_ack_set(vcpu) ||
12243             (vmcs12->posted_intr_nv & 0xff00) ||
12244             (vmcs12->posted_intr_desc_addr & 0x3f) ||
12245             (vmcs12->posted_intr_desc_addr >> cpuid_maxphyaddr(vcpu))))
12246                 return -EINVAL;
12247
12248         /* tpr shadow is needed by all apicv features. */
12249         if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
12250                 return -EINVAL;
12251
12252         return 0;
12253 }
12254
12255 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
12256                                        unsigned long count_field,
12257                                        unsigned long addr_field)
12258 {
12259         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
12260         int maxphyaddr;
12261         u64 count, addr;
12262
12263         if (vmcs12_read_any(vmcs12, count_field, &count) ||
12264             vmcs12_read_any(vmcs12, addr_field, &addr)) {
12265                 WARN_ON(1);
12266                 return -EINVAL;
12267         }
12268         if (count == 0)
12269                 return 0;
12270         maxphyaddr = cpuid_maxphyaddr(vcpu);
12271         if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
12272             (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
12273                 pr_debug_ratelimited(
12274                         "nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
12275                         addr_field, maxphyaddr, count, addr);
12276                 return -EINVAL;
12277         }
12278         return 0;
12279 }
12280
12281 static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
12282                                                 struct vmcs12 *vmcs12)
12283 {
12284         if (vmcs12->vm_exit_msr_load_count == 0 &&
12285             vmcs12->vm_exit_msr_store_count == 0 &&
12286             vmcs12->vm_entry_msr_load_count == 0)
12287                 return 0; /* Fast path */
12288         if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
12289                                         VM_EXIT_MSR_LOAD_ADDR) ||
12290             nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
12291                                         VM_EXIT_MSR_STORE_ADDR) ||
12292             nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
12293                                         VM_ENTRY_MSR_LOAD_ADDR))
12294                 return -EINVAL;
12295         return 0;
12296 }
12297
12298 static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
12299                                          struct vmcs12 *vmcs12)
12300 {
12301         if (!nested_cpu_has_pml(vmcs12))
12302                 return 0;
12303
12304         if (!nested_cpu_has_ept(vmcs12) ||
12305             !page_address_valid(vcpu, vmcs12->pml_address))
12306                 return -EINVAL;
12307
12308         return 0;
12309 }
12310
12311 static int nested_vmx_check_shadow_vmcs_controls(struct kvm_vcpu *vcpu,
12312                                                  struct vmcs12 *vmcs12)
12313 {
12314         if (!nested_cpu_has_shadow_vmcs(vmcs12))
12315                 return 0;
12316
12317         if (!page_address_valid(vcpu, vmcs12->vmread_bitmap) ||
12318             !page_address_valid(vcpu, vmcs12->vmwrite_bitmap))
12319                 return -EINVAL;
12320
12321         return 0;
12322 }
12323
12324 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
12325                                        struct vmx_msr_entry *e)
12326 {
12327         /* x2APIC MSR accesses are not allowed */
12328         if (vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8)
12329                 return -EINVAL;
12330         if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
12331             e->index == MSR_IA32_UCODE_REV)
12332                 return -EINVAL;
12333         if (e->reserved != 0)
12334                 return -EINVAL;
12335         return 0;
12336 }
12337
12338 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
12339                                      struct vmx_msr_entry *e)
12340 {
12341         if (e->index == MSR_FS_BASE ||
12342             e->index == MSR_GS_BASE ||
12343             e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
12344             nested_vmx_msr_check_common(vcpu, e))
12345                 return -EINVAL;
12346         return 0;
12347 }
12348
12349 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
12350                                       struct vmx_msr_entry *e)
12351 {
12352         if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
12353             nested_vmx_msr_check_common(vcpu, e))
12354                 return -EINVAL;
12355         return 0;
12356 }
12357
12358 /*
12359  * Load guest's/host's msr at nested entry/exit.
12360  * return 0 for success, entry index for failure.
12361  */
12362 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
12363 {
12364         u32 i;
12365         struct vmx_msr_entry e;
12366         struct msr_data msr;
12367
12368         msr.host_initiated = false;
12369         for (i = 0; i < count; i++) {
12370                 if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
12371                                         &e, sizeof(e))) {
12372                         pr_debug_ratelimited(
12373                                 "%s cannot read MSR entry (%u, 0x%08llx)\n",
12374                                 __func__, i, gpa + i * sizeof(e));
12375                         goto fail;
12376                 }
12377                 if (nested_vmx_load_msr_check(vcpu, &e)) {
12378                         pr_debug_ratelimited(
12379                                 "%s check failed (%u, 0x%x, 0x%x)\n",
12380                                 __func__, i, e.index, e.reserved);
12381                         goto fail;
12382                 }
12383                 msr.index = e.index;
12384                 msr.data = e.value;
12385                 if (kvm_set_msr(vcpu, &msr)) {
12386                         pr_debug_ratelimited(
12387                                 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
12388                                 __func__, i, e.index, e.value);
12389                         goto fail;
12390                 }
12391         }
12392         return 0;
12393 fail:
12394         return i + 1;
12395 }
12396
12397 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
12398 {
12399         u32 i;
12400         struct vmx_msr_entry e;
12401
12402         for (i = 0; i < count; i++) {
12403                 struct msr_data msr_info;
12404                 if (kvm_vcpu_read_guest(vcpu,
12405                                         gpa + i * sizeof(e),
12406                                         &e, 2 * sizeof(u32))) {
12407                         pr_debug_ratelimited(
12408                                 "%s cannot read MSR entry (%u, 0x%08llx)\n",
12409                                 __func__, i, gpa + i * sizeof(e));
12410                         return -EINVAL;
12411                 }
12412                 if (nested_vmx_store_msr_check(vcpu, &e)) {
12413                         pr_debug_ratelimited(
12414                                 "%s check failed (%u, 0x%x, 0x%x)\n",
12415                                 __func__, i, e.index, e.reserved);
12416                         return -EINVAL;
12417                 }
12418                 msr_info.host_initiated = false;
12419                 msr_info.index = e.index;
12420                 if (kvm_get_msr(vcpu, &msr_info)) {
12421                         pr_debug_ratelimited(
12422                                 "%s cannot read MSR (%u, 0x%x)\n",
12423                                 __func__, i, e.index);
12424                         return -EINVAL;
12425                 }
12426                 if (kvm_vcpu_write_guest(vcpu,
12427                                          gpa + i * sizeof(e) +
12428                                              offsetof(struct vmx_msr_entry, value),
12429                                          &msr_info.data, sizeof(msr_info.data))) {
12430                         pr_debug_ratelimited(
12431                                 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
12432                                 __func__, i, e.index, msr_info.data);
12433                         return -EINVAL;
12434                 }
12435         }
12436         return 0;
12437 }
12438
12439 static bool nested_cr3_valid(struct kvm_vcpu *vcpu, unsigned long val)
12440 {
12441         unsigned long invalid_mask;
12442
12443         invalid_mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
12444         return (val & invalid_mask) == 0;
12445 }
12446
12447 /*
12448  * Load guest's/host's cr3 at nested entry/exit. nested_ept is true if we are
12449  * emulating VM entry into a guest with EPT enabled.
12450  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
12451  * is assigned to entry_failure_code on failure.
12452  */
12453 static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool nested_ept,
12454                                u32 *entry_failure_code)
12455 {
12456         if (cr3 != kvm_read_cr3(vcpu) || (!nested_ept && pdptrs_changed(vcpu))) {
12457                 if (!nested_cr3_valid(vcpu, cr3)) {
12458                         *entry_failure_code = ENTRY_FAIL_DEFAULT;
12459                         return 1;
12460                 }
12461
12462                 /*
12463                  * If PAE paging and EPT are both on, CR3 is not used by the CPU and
12464                  * must not be dereferenced.
12465                  */
12466                 if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu) &&
12467                     !nested_ept) {
12468                         if (!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)) {
12469                                 *entry_failure_code = ENTRY_FAIL_PDPTE;
12470                                 return 1;
12471                         }
12472                 }
12473         }
12474
12475         if (!nested_ept)
12476                 kvm_mmu_new_cr3(vcpu, cr3, false);
12477
12478         vcpu->arch.cr3 = cr3;
12479         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
12480
12481         kvm_init_mmu(vcpu, false);
12482
12483         return 0;
12484 }
12485
12486 /*
12487  * Returns if KVM is able to config CPU to tag TLB entries
12488  * populated by L2 differently than TLB entries populated
12489  * by L1.
12490  *
12491  * If L1 uses EPT, then TLB entries are tagged with different EPTP.
12492  *
12493  * If L1 uses VPID and we allocated a vpid02, TLB entries are tagged
12494  * with different VPID (L1 entries are tagged with vmx->vpid
12495  * while L2 entries are tagged with vmx->nested.vpid02).
12496  */
12497 static bool nested_has_guest_tlb_tag(struct kvm_vcpu *vcpu)
12498 {
12499         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
12500
12501         return nested_cpu_has_ept(vmcs12) ||
12502                (nested_cpu_has_vpid(vmcs12) && to_vmx(vcpu)->nested.vpid02);
12503 }
12504
12505 static u64 nested_vmx_calc_efer(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
12506 {
12507         if (vmx->nested.nested_run_pending &&
12508             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
12509                 return vmcs12->guest_ia32_efer;
12510         else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
12511                 return vmx->vcpu.arch.efer | (EFER_LMA | EFER_LME);
12512         else
12513                 return vmx->vcpu.arch.efer & ~(EFER_LMA | EFER_LME);
12514 }
12515
12516 static void prepare_vmcs02_constant_state(struct vcpu_vmx *vmx)
12517 {
12518         /*
12519          * If vmcs02 hasn't been initialized, set the constant vmcs02 state
12520          * according to L0's settings (vmcs12 is irrelevant here).  Host
12521          * fields that come from L0 and are not constant, e.g. HOST_CR3,
12522          * will be set as needed prior to VMLAUNCH/VMRESUME.
12523          */
12524         if (vmx->nested.vmcs02_initialized)
12525                 return;
12526         vmx->nested.vmcs02_initialized = true;
12527
12528         /*
12529          * We don't care what the EPTP value is we just need to guarantee
12530          * it's valid so we don't get a false positive when doing early
12531          * consistency checks.
12532          */
12533         if (enable_ept && nested_early_check)
12534                 vmcs_write64(EPT_POINTER, construct_eptp(&vmx->vcpu, 0));
12535
12536         /* All VMFUNCs are currently emulated through L0 vmexits.  */
12537         if (cpu_has_vmx_vmfunc())
12538                 vmcs_write64(VM_FUNCTION_CONTROL, 0);
12539
12540         if (cpu_has_vmx_posted_intr())
12541                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
12542
12543         if (cpu_has_vmx_msr_bitmap())
12544                 vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
12545
12546         if (enable_pml)
12547                 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
12548
12549         /*
12550          * Set the MSR load/store lists to match L0's settings.  Only the
12551          * addresses are constant (for vmcs02), the counts can change based
12552          * on L2's behavior, e.g. switching to/from long mode.
12553          */
12554         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
12555         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
12556         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
12557
12558         vmx_set_constant_host_state(vmx);
12559 }
12560
12561 static void prepare_vmcs02_early_full(struct vcpu_vmx *vmx,
12562                                       struct vmcs12 *vmcs12)
12563 {
12564         prepare_vmcs02_constant_state(vmx);
12565
12566         vmcs_write64(VMCS_LINK_POINTER, -1ull);
12567
12568         if (enable_vpid) {
12569                 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02)
12570                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
12571                 else
12572                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
12573         }
12574 }
12575
12576 static void prepare_vmcs02_early(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
12577 {
12578         u32 exec_control, vmcs12_exec_ctrl;
12579         u64 guest_efer = nested_vmx_calc_efer(vmx, vmcs12);
12580
12581         if (vmx->nested.dirty_vmcs12 || vmx->nested.hv_evmcs)
12582                 prepare_vmcs02_early_full(vmx, vmcs12);
12583
12584         /*
12585          * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
12586          * entry, but only if the current (host) sp changed from the value
12587          * we wrote last (vmx->host_rsp).  This cache is no longer relevant
12588          * if we switch vmcs, and rather than hold a separate cache per vmcs,
12589          * here we just force the write to happen on entry.  host_rsp will
12590          * also be written unconditionally by nested_vmx_check_vmentry_hw()
12591          * if we are doing early consistency checks via hardware.
12592          */
12593         vmx->host_rsp = 0;
12594
12595         /*
12596          * PIN CONTROLS
12597          */
12598         exec_control = vmcs12->pin_based_vm_exec_control;
12599
12600         /* Preemption timer setting is computed directly in vmx_vcpu_run.  */
12601         exec_control |= vmcs_config.pin_based_exec_ctrl;
12602         exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
12603         vmx->loaded_vmcs->hv_timer_armed = false;
12604
12605         /* Posted interrupts setting is only taken from vmcs12.  */
12606         if (nested_cpu_has_posted_intr(vmcs12)) {
12607                 vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
12608                 vmx->nested.pi_pending = false;
12609         } else {
12610                 exec_control &= ~PIN_BASED_POSTED_INTR;
12611         }
12612         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
12613
12614         /*
12615          * EXEC CONTROLS
12616          */
12617         exec_control = vmx_exec_control(vmx); /* L0's desires */
12618         exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
12619         exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
12620         exec_control &= ~CPU_BASED_TPR_SHADOW;
12621         exec_control |= vmcs12->cpu_based_vm_exec_control;
12622
12623         /*
12624          * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR. Later, if
12625          * nested_get_vmcs12_pages can't fix it up, the illegal value
12626          * will result in a VM entry failure.
12627          */
12628         if (exec_control & CPU_BASED_TPR_SHADOW) {
12629                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
12630                 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
12631         } else {
12632 #ifdef CONFIG_X86_64
12633                 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
12634                                 CPU_BASED_CR8_STORE_EXITING;
12635 #endif
12636         }
12637
12638         /*
12639          * A vmexit (to either L1 hypervisor or L0 userspace) is always needed
12640          * for I/O port accesses.
12641          */
12642         exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
12643         exec_control |= CPU_BASED_UNCOND_IO_EXITING;
12644         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
12645
12646         /*
12647          * SECONDARY EXEC CONTROLS
12648          */
12649         if (cpu_has_secondary_exec_ctrls()) {
12650                 exec_control = vmx->secondary_exec_control;
12651
12652                 /* Take the following fields only from vmcs12 */
12653                 exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
12654                                   SECONDARY_EXEC_ENABLE_INVPCID |
12655                                   SECONDARY_EXEC_RDTSCP |
12656                                   SECONDARY_EXEC_XSAVES |
12657                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
12658                                   SECONDARY_EXEC_APIC_REGISTER_VIRT |
12659                                   SECONDARY_EXEC_ENABLE_VMFUNC);
12660                 if (nested_cpu_has(vmcs12,
12661                                    CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
12662                         vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
12663                                 ~SECONDARY_EXEC_ENABLE_PML;
12664                         exec_control |= vmcs12_exec_ctrl;
12665                 }
12666
12667                 /* VMCS shadowing for L2 is emulated for now */
12668                 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
12669
12670                 if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
12671                         vmcs_write16(GUEST_INTR_STATUS,
12672                                 vmcs12->guest_intr_status);
12673
12674                 /*
12675                  * Write an illegal value to APIC_ACCESS_ADDR. Later,
12676                  * nested_get_vmcs12_pages will either fix it up or
12677                  * remove the VM execution control.
12678                  */
12679                 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
12680                         vmcs_write64(APIC_ACCESS_ADDR, -1ull);
12681
12682                 if (exec_control & SECONDARY_EXEC_ENCLS_EXITING)
12683                         vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
12684
12685                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
12686         }
12687
12688         /*
12689          * ENTRY CONTROLS
12690          *
12691          * vmcs12's VM_{ENTRY,EXIT}_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE
12692          * are emulated by vmx_set_efer() in prepare_vmcs02(), but speculate
12693          * on the related bits (if supported by the CPU) in the hope that
12694          * we can avoid VMWrites during vmx_set_efer().
12695          */
12696         exec_control = (vmcs12->vm_entry_controls | vmcs_config.vmentry_ctrl) &
12697                         ~VM_ENTRY_IA32E_MODE & ~VM_ENTRY_LOAD_IA32_EFER;
12698         if (cpu_has_load_ia32_efer) {
12699                 if (guest_efer & EFER_LMA)
12700                         exec_control |= VM_ENTRY_IA32E_MODE;
12701                 if (guest_efer != host_efer)
12702                         exec_control |= VM_ENTRY_LOAD_IA32_EFER;
12703         }
12704         vm_entry_controls_init(vmx, exec_control);
12705
12706         /*
12707          * EXIT CONTROLS
12708          *
12709          * L2->L1 exit controls are emulated - the hardware exit is to L0 so
12710          * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
12711          * bits may be modified by vmx_set_efer() in prepare_vmcs02().
12712          */
12713         exec_control = vmcs_config.vmexit_ctrl;
12714         if (cpu_has_load_ia32_efer && guest_efer != host_efer)
12715                 exec_control |= VM_EXIT_LOAD_IA32_EFER;
12716         vm_exit_controls_init(vmx, exec_control);
12717
12718         /*
12719          * Conceptually we want to copy the PML address and index from
12720          * vmcs01 here, and then back to vmcs01 on nested vmexit. But,
12721          * since we always flush the log on each vmexit and never change
12722          * the PML address (once set), this happens to be equivalent to
12723          * simply resetting the index in vmcs02.
12724          */
12725         if (enable_pml)
12726                 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
12727
12728         /*
12729          * Interrupt/Exception Fields
12730          */
12731         if (vmx->nested.nested_run_pending) {
12732                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
12733                              vmcs12->vm_entry_intr_info_field);
12734                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
12735                              vmcs12->vm_entry_exception_error_code);
12736                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
12737                              vmcs12->vm_entry_instruction_len);
12738                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
12739                              vmcs12->guest_interruptibility_info);
12740                 vmx->loaded_vmcs->nmi_known_unmasked =
12741                         !(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
12742         } else {
12743                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
12744         }
12745 }
12746
12747 static void prepare_vmcs02_full(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
12748 {
12749         struct hv_enlightened_vmcs *hv_evmcs = vmx->nested.hv_evmcs;
12750
12751         if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
12752                            HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2)) {
12753                 vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
12754                 vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
12755                 vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
12756                 vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
12757                 vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
12758                 vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
12759                 vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
12760                 vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
12761                 vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
12762                 vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
12763                 vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
12764                 vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
12765                 vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
12766                 vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
12767                 vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
12768                 vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
12769                 vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
12770                 vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
12771                 vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
12772                 vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
12773                 vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
12774                 vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
12775                 vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
12776                 vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
12777                 vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
12778                 vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
12779                 vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
12780                 vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
12781                 vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
12782                 vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
12783                 vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
12784                 vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
12785                 vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
12786                 vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
12787         }
12788
12789         if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
12790                            HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1)) {
12791                 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
12792                 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
12793                             vmcs12->guest_pending_dbg_exceptions);
12794                 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
12795                 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
12796
12797                 /*
12798                  * L1 may access the L2's PDPTR, so save them to construct
12799                  * vmcs12
12800                  */
12801                 if (enable_ept) {
12802                         vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
12803                         vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
12804                         vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
12805                         vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
12806                 }
12807         }
12808
12809         if (nested_cpu_has_xsaves(vmcs12))
12810                 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
12811
12812         /*
12813          * Whether page-faults are trapped is determined by a combination of
12814          * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
12815          * If enable_ept, L0 doesn't care about page faults and we should
12816          * set all of these to L1's desires. However, if !enable_ept, L0 does
12817          * care about (at least some) page faults, and because it is not easy
12818          * (if at all possible?) to merge L0 and L1's desires, we simply ask
12819          * to exit on each and every L2 page fault. This is done by setting
12820          * MASK=MATCH=0 and (see below) EB.PF=1.
12821          * Note that below we don't need special code to set EB.PF beyond the
12822          * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
12823          * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
12824          * !enable_ept, EB.PF is 1, so the "or" will always be 1.
12825          */
12826         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
12827                 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
12828         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
12829                 enable_ept ? vmcs12->page_fault_error_code_match : 0);
12830
12831         if (cpu_has_vmx_apicv()) {
12832                 vmcs_write64(EOI_EXIT_BITMAP0, vmcs12->eoi_exit_bitmap0);
12833                 vmcs_write64(EOI_EXIT_BITMAP1, vmcs12->eoi_exit_bitmap1);
12834                 vmcs_write64(EOI_EXIT_BITMAP2, vmcs12->eoi_exit_bitmap2);
12835                 vmcs_write64(EOI_EXIT_BITMAP3, vmcs12->eoi_exit_bitmap3);
12836         }
12837
12838         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
12839         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
12840
12841         set_cr4_guest_host_mask(vmx);
12842
12843         if (kvm_mpx_supported()) {
12844                 if (vmx->nested.nested_run_pending &&
12845                         (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
12846                         vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
12847                 else
12848                         vmcs_write64(GUEST_BNDCFGS, vmx->nested.vmcs01_guest_bndcfgs);
12849         }
12850 }
12851
12852 /*
12853  * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
12854  * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
12855  * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
12856  * guest in a way that will both be appropriate to L1's requests, and our
12857  * needs. In addition to modifying the active vmcs (which is vmcs02), this
12858  * function also has additional necessary side-effects, like setting various
12859  * vcpu->arch fields.
12860  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
12861  * is assigned to entry_failure_code on failure.
12862  */
12863 static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12864                           u32 *entry_failure_code)
12865 {
12866         struct vcpu_vmx *vmx = to_vmx(vcpu);
12867         struct hv_enlightened_vmcs *hv_evmcs = vmx->nested.hv_evmcs;
12868
12869         if (vmx->nested.dirty_vmcs12 || vmx->nested.hv_evmcs) {
12870                 prepare_vmcs02_full(vmx, vmcs12);
12871                 vmx->nested.dirty_vmcs12 = false;
12872         }
12873
12874         /*
12875          * First, the fields that are shadowed.  This must be kept in sync
12876          * with vmx_shadow_fields.h.
12877          */
12878         if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
12879                            HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2)) {
12880                 vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
12881                 vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
12882         }
12883
12884         if (vmx->nested.nested_run_pending &&
12885             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
12886                 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
12887                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
12888         } else {
12889                 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
12890                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
12891         }
12892         vmx_set_rflags(vcpu, vmcs12->guest_rflags);
12893
12894         vmx->nested.preemption_timer_expired = false;
12895         if (nested_cpu_has_preemption_timer(vmcs12))
12896                 vmx_start_preemption_timer(vcpu);
12897
12898         /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
12899          * bitwise-or of what L1 wants to trap for L2, and what we want to
12900          * trap. Note that CR0.TS also needs updating - we do this later.
12901          */
12902         update_exception_bitmap(vcpu);
12903         vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
12904         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
12905
12906         if (vmx->nested.nested_run_pending &&
12907             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
12908                 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
12909                 vcpu->arch.pat = vmcs12->guest_ia32_pat;
12910         } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
12911                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
12912         }
12913
12914         vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
12915
12916         if (kvm_has_tsc_control)
12917                 decache_tsc_multiplier(vmx);
12918
12919         if (enable_vpid) {
12920                 /*
12921                  * There is no direct mapping between vpid02 and vpid12, the
12922                  * vpid02 is per-vCPU for L0 and reused while the value of
12923                  * vpid12 is changed w/ one invvpid during nested vmentry.
12924                  * The vpid12 is allocated by L1 for L2, so it will not
12925                  * influence global bitmap(for vpid01 and vpid02 allocation)
12926                  * even if spawn a lot of nested vCPUs.
12927                  */
12928                 if (nested_cpu_has_vpid(vmcs12) && nested_has_guest_tlb_tag(vcpu)) {
12929                         if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
12930                                 vmx->nested.last_vpid = vmcs12->virtual_processor_id;
12931                                 __vmx_flush_tlb(vcpu, nested_get_vpid02(vcpu), false);
12932                         }
12933                 } else {
12934                         /*
12935                          * If L1 use EPT, then L0 needs to execute INVEPT on
12936                          * EPTP02 instead of EPTP01. Therefore, delay TLB
12937                          * flush until vmcs02->eptp is fully updated by
12938                          * KVM_REQ_LOAD_CR3. Note that this assumes
12939                          * KVM_REQ_TLB_FLUSH is evaluated after
12940                          * KVM_REQ_LOAD_CR3 in vcpu_enter_guest().
12941                          */
12942                         kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
12943                 }
12944         }
12945
12946         if (nested_cpu_has_ept(vmcs12))
12947                 nested_ept_init_mmu_context(vcpu);
12948         else if (nested_cpu_has2(vmcs12,
12949                                  SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
12950                 vmx_flush_tlb(vcpu, true);
12951
12952         /*
12953          * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
12954          * bits which we consider mandatory enabled.
12955          * The CR0_READ_SHADOW is what L2 should have expected to read given
12956          * the specifications by L1; It's not enough to take
12957          * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
12958          * have more bits than L1 expected.
12959          */
12960         vmx_set_cr0(vcpu, vmcs12->guest_cr0);
12961         vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
12962
12963         vmx_set_cr4(vcpu, vmcs12->guest_cr4);
12964         vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
12965
12966         vcpu->arch.efer = nested_vmx_calc_efer(vmx, vmcs12);
12967         /* Note: may modify VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
12968         vmx_set_efer(vcpu, vcpu->arch.efer);
12969
12970         /*
12971          * Guest state is invalid and unrestricted guest is disabled,
12972          * which means L1 attempted VMEntry to L2 with invalid state.
12973          * Fail the VMEntry.
12974          */
12975         if (vmx->emulation_required) {
12976                 *entry_failure_code = ENTRY_FAIL_DEFAULT;
12977                 return 1;
12978         }
12979
12980         /* Shadow page tables on either EPT or shadow page tables. */
12981         if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
12982                                 entry_failure_code))
12983                 return 1;
12984
12985         if (!enable_ept)
12986                 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
12987
12988         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
12989         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
12990         return 0;
12991 }
12992
12993 static int nested_vmx_check_nmi_controls(struct vmcs12 *vmcs12)
12994 {
12995         if (!nested_cpu_has_nmi_exiting(vmcs12) &&
12996             nested_cpu_has_virtual_nmis(vmcs12))
12997                 return -EINVAL;
12998
12999         if (!nested_cpu_has_virtual_nmis(vmcs12) &&
13000             nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING))
13001                 return -EINVAL;
13002
13003         return 0;
13004 }
13005
13006 static int check_vmentry_prereqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
13007 {
13008         struct vcpu_vmx *vmx = to_vmx(vcpu);
13009         bool ia32e;
13010
13011         if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
13012             vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT)
13013                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13014
13015         if (nested_cpu_has_vpid(vmcs12) && !vmcs12->virtual_processor_id)
13016                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13017
13018         if (nested_vmx_check_io_bitmap_controls(vcpu, vmcs12))
13019                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13020
13021         if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12))
13022                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13023
13024         if (nested_vmx_check_apic_access_controls(vcpu, vmcs12))
13025                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13026
13027         if (nested_vmx_check_tpr_shadow_controls(vcpu, vmcs12))
13028                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13029
13030         if (nested_vmx_check_apicv_controls(vcpu, vmcs12))
13031                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13032
13033         if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12))
13034                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13035
13036         if (nested_vmx_check_pml_controls(vcpu, vmcs12))
13037                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13038
13039         if (nested_vmx_check_shadow_vmcs_controls(vcpu, vmcs12))
13040                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13041
13042         if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
13043                                 vmx->nested.msrs.procbased_ctls_low,
13044                                 vmx->nested.msrs.procbased_ctls_high) ||
13045             (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
13046              !vmx_control_verify(vmcs12->secondary_vm_exec_control,
13047                                  vmx->nested.msrs.secondary_ctls_low,
13048                                  vmx->nested.msrs.secondary_ctls_high)) ||
13049             !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
13050                                 vmx->nested.msrs.pinbased_ctls_low,
13051                                 vmx->nested.msrs.pinbased_ctls_high) ||
13052             !vmx_control_verify(vmcs12->vm_exit_controls,
13053                                 vmx->nested.msrs.exit_ctls_low,
13054                                 vmx->nested.msrs.exit_ctls_high) ||
13055             !vmx_control_verify(vmcs12->vm_entry_controls,
13056                                 vmx->nested.msrs.entry_ctls_low,
13057                                 vmx->nested.msrs.entry_ctls_high))
13058                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13059
13060         if (nested_vmx_check_nmi_controls(vmcs12))
13061                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13062
13063         if (nested_cpu_has_vmfunc(vmcs12)) {
13064                 if (vmcs12->vm_function_control &
13065                     ~vmx->nested.msrs.vmfunc_controls)
13066                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13067
13068                 if (nested_cpu_has_eptp_switching(vmcs12)) {
13069                         if (!nested_cpu_has_ept(vmcs12) ||
13070                             !page_address_valid(vcpu, vmcs12->eptp_list_address))
13071                                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13072                 }
13073         }
13074
13075         if (vmcs12->cr3_target_count > nested_cpu_vmx_misc_cr3_count(vcpu))
13076                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13077
13078         if (!nested_host_cr0_valid(vcpu, vmcs12->host_cr0) ||
13079             !nested_host_cr4_valid(vcpu, vmcs12->host_cr4) ||
13080             !nested_cr3_valid(vcpu, vmcs12->host_cr3))
13081                 return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
13082
13083         /*
13084          * If the load IA32_EFER VM-exit control is 1, bits reserved in the
13085          * IA32_EFER MSR must be 0 in the field for that register. In addition,
13086          * the values of the LMA and LME bits in the field must each be that of
13087          * the host address-space size VM-exit control.
13088          */
13089         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
13090                 ia32e = (vmcs12->vm_exit_controls &
13091                          VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
13092                 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
13093                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
13094                     ia32e != !!(vmcs12->host_ia32_efer & EFER_LME))
13095                         return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
13096         }
13097
13098         /*
13099          * From the Intel SDM, volume 3:
13100          * Fields relevant to VM-entry event injection must be set properly.
13101          * These fields are the VM-entry interruption-information field, the
13102          * VM-entry exception error code, and the VM-entry instruction length.
13103          */
13104         if (vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) {
13105                 u32 intr_info = vmcs12->vm_entry_intr_info_field;
13106                 u8 vector = intr_info & INTR_INFO_VECTOR_MASK;
13107                 u32 intr_type = intr_info & INTR_INFO_INTR_TYPE_MASK;
13108                 bool has_error_code = intr_info & INTR_INFO_DELIVER_CODE_MASK;
13109                 bool should_have_error_code;
13110                 bool urg = nested_cpu_has2(vmcs12,
13111                                            SECONDARY_EXEC_UNRESTRICTED_GUEST);
13112                 bool prot_mode = !urg || vmcs12->guest_cr0 & X86_CR0_PE;
13113
13114                 /* VM-entry interruption-info field: interruption type */
13115                 if (intr_type == INTR_TYPE_RESERVED ||
13116                     (intr_type == INTR_TYPE_OTHER_EVENT &&
13117                      !nested_cpu_supports_monitor_trap_flag(vcpu)))
13118                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13119
13120                 /* VM-entry interruption-info field: vector */
13121                 if ((intr_type == INTR_TYPE_NMI_INTR && vector != NMI_VECTOR) ||
13122                     (intr_type == INTR_TYPE_HARD_EXCEPTION && vector > 31) ||
13123                     (intr_type == INTR_TYPE_OTHER_EVENT && vector != 0))
13124                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13125
13126                 /* VM-entry interruption-info field: deliver error code */
13127                 should_have_error_code =
13128                         intr_type == INTR_TYPE_HARD_EXCEPTION && prot_mode &&
13129                         x86_exception_has_error_code(vector);
13130                 if (has_error_code != should_have_error_code)
13131                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13132
13133                 /* VM-entry exception error code */
13134                 if (has_error_code &&
13135                     vmcs12->vm_entry_exception_error_code & GENMASK(31, 15))
13136                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13137
13138                 /* VM-entry interruption-info field: reserved bits */
13139                 if (intr_info & INTR_INFO_RESVD_BITS_MASK)
13140                         return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13141
13142                 /* VM-entry instruction length */
13143                 switch (intr_type) {
13144                 case INTR_TYPE_SOFT_EXCEPTION:
13145                 case INTR_TYPE_SOFT_INTR:
13146                 case INTR_TYPE_PRIV_SW_EXCEPTION:
13147                         if ((vmcs12->vm_entry_instruction_len > 15) ||
13148                             (vmcs12->vm_entry_instruction_len == 0 &&
13149                              !nested_cpu_has_zero_length_injection(vcpu)))
13150                                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13151                 }
13152         }
13153
13154         if (nested_cpu_has_ept(vmcs12) &&
13155             !valid_ept_address(vcpu, vmcs12->ept_pointer))
13156                 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
13157
13158         return 0;
13159 }
13160
13161 static int nested_vmx_check_vmcs_link_ptr(struct kvm_vcpu *vcpu,
13162                                           struct vmcs12 *vmcs12)
13163 {
13164         int r;
13165         struct page *page;
13166         struct vmcs12 *shadow;
13167
13168         if (vmcs12->vmcs_link_pointer == -1ull)
13169                 return 0;
13170
13171         if (!page_address_valid(vcpu, vmcs12->vmcs_link_pointer))
13172                 return -EINVAL;
13173
13174         page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->vmcs_link_pointer);
13175         if (is_error_page(page))
13176                 return -EINVAL;
13177
13178         r = 0;
13179         shadow = kmap(page);
13180         if (shadow->hdr.revision_id != VMCS12_REVISION ||
13181             shadow->hdr.shadow_vmcs != nested_cpu_has_shadow_vmcs(vmcs12))
13182                 r = -EINVAL;
13183         kunmap(page);
13184         kvm_release_page_clean(page);
13185         return r;
13186 }
13187
13188 static int check_vmentry_postreqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
13189                                   u32 *exit_qual)
13190 {
13191         bool ia32e;
13192
13193         *exit_qual = ENTRY_FAIL_DEFAULT;
13194
13195         if (!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0) ||
13196             !nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4))
13197                 return 1;
13198
13199         if (nested_vmx_check_vmcs_link_ptr(vcpu, vmcs12)) {
13200                 *exit_qual = ENTRY_FAIL_VMCS_LINK_PTR;
13201                 return 1;
13202         }
13203
13204         /*
13205          * If the load IA32_EFER VM-entry control is 1, the following checks
13206          * are performed on the field for the IA32_EFER MSR:
13207          * - Bits reserved in the IA32_EFER MSR must be 0.
13208          * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
13209          *   the IA-32e mode guest VM-exit control. It must also be identical
13210          *   to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
13211          *   CR0.PG) is 1.
13212          */
13213         if (to_vmx(vcpu)->nested.nested_run_pending &&
13214             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {
13215                 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
13216                 if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
13217                     ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
13218                     ((vmcs12->guest_cr0 & X86_CR0_PG) &&
13219                      ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME)))
13220                         return 1;
13221         }
13222
13223         if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS) &&
13224                 (is_noncanonical_address(vmcs12->guest_bndcfgs & PAGE_MASK, vcpu) ||
13225                 (vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD)))
13226                         return 1;
13227
13228         return 0;
13229 }
13230
13231 static int __noclone nested_vmx_check_vmentry_hw(struct kvm_vcpu *vcpu)
13232 {
13233         struct vcpu_vmx *vmx = to_vmx(vcpu);
13234         unsigned long cr3, cr4;
13235
13236         if (!nested_early_check)
13237                 return 0;
13238
13239         if (vmx->msr_autoload.host.nr)
13240                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
13241         if (vmx->msr_autoload.guest.nr)
13242                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
13243
13244         preempt_disable();
13245
13246         vmx_prepare_switch_to_guest(vcpu);
13247
13248         /*
13249          * Induce a consistency check VMExit by clearing bit 1 in GUEST_RFLAGS,
13250          * which is reserved to '1' by hardware.  GUEST_RFLAGS is guaranteed to
13251          * be written (by preparve_vmcs02()) before the "real" VMEnter, i.e.
13252          * there is no need to preserve other bits or save/restore the field.
13253          */
13254         vmcs_writel(GUEST_RFLAGS, 0);
13255
13256         vmcs_writel(HOST_RIP, vmx_early_consistency_check_return);
13257
13258         cr3 = __get_current_cr3_fast();
13259         if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
13260                 vmcs_writel(HOST_CR3, cr3);
13261                 vmx->loaded_vmcs->host_state.cr3 = cr3;
13262         }
13263
13264         cr4 = cr4_read_shadow();
13265         if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
13266                 vmcs_writel(HOST_CR4, cr4);
13267                 vmx->loaded_vmcs->host_state.cr4 = cr4;
13268         }
13269
13270         vmx->__launched = vmx->loaded_vmcs->launched;
13271
13272         asm(
13273                 /* Set HOST_RSP */
13274                 __ex("vmwrite %%" _ASM_SP ", %%" _ASM_DX) "\n\t"
13275                 "mov %%" _ASM_SP ", %c[host_rsp](%0)\n\t"
13276
13277                 /* Check if vmlaunch of vmresume is needed */
13278                 "cmpl $0, %c[launched](%0)\n\t"
13279                 "je 1f\n\t"
13280                 __ex("vmresume") "\n\t"
13281                 "jmp 2f\n\t"
13282                 "1: " __ex("vmlaunch") "\n\t"
13283                 "jmp 2f\n\t"
13284                 "2: "
13285
13286                 /* Set vmx->fail accordingly */
13287                 "setbe %c[fail](%0)\n\t"
13288
13289                 ".pushsection .rodata\n\t"
13290                 ".global vmx_early_consistency_check_return\n\t"
13291                 "vmx_early_consistency_check_return: " _ASM_PTR " 2b\n\t"
13292                 ".popsection"
13293               :
13294               : "c"(vmx), "d"((unsigned long)HOST_RSP),
13295                 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
13296                 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
13297                 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp))
13298               : "rax", "cc", "memory"
13299         );
13300
13301         vmcs_writel(HOST_RIP, vmx_return);
13302
13303         preempt_enable();
13304
13305         if (vmx->msr_autoload.host.nr)
13306                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
13307         if (vmx->msr_autoload.guest.nr)
13308                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
13309
13310         if (vmx->fail) {
13311                 WARN_ON_ONCE(vmcs_read32(VM_INSTRUCTION_ERROR) !=
13312                              VMXERR_ENTRY_INVALID_CONTROL_FIELD);
13313                 vmx->fail = 0;
13314                 return 1;
13315         }
13316
13317         /*
13318          * VMExit clears RFLAGS.IF and DR7, even on a consistency check.
13319          */
13320         local_irq_enable();
13321         if (hw_breakpoint_active())
13322                 set_debugreg(__this_cpu_read(cpu_dr7), 7);
13323
13324         /*
13325          * A non-failing VMEntry means we somehow entered guest mode with
13326          * an illegal RIP, and that's just the tip of the iceberg.  There
13327          * is no telling what memory has been modified or what state has
13328          * been exposed to unknown code.  Hitting this all but guarantees
13329          * a (very critical) hardware issue.
13330          */
13331         WARN_ON(!(vmcs_read32(VM_EXIT_REASON) &
13332                 VMX_EXIT_REASONS_FAILED_VMENTRY));
13333
13334         return 0;
13335 }
13336 STACK_FRAME_NON_STANDARD(nested_vmx_check_vmentry_hw);
13337
13338 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
13339                                    struct vmcs12 *vmcs12);
13340
13341 /*
13342  * If from_vmentry is false, this is being called from state restore (either RSM
13343  * or KVM_SET_NESTED_STATE).  Otherwise it's called from vmlaunch/vmresume.
13344 + *
13345 + * Returns:
13346 + *   0 - success, i.e. proceed with actual VMEnter
13347 + *   1 - consistency check VMExit
13348 + *  -1 - consistency check VMFail
13349  */
13350 static int nested_vmx_enter_non_root_mode(struct kvm_vcpu *vcpu,
13351                                           bool from_vmentry)
13352 {
13353         struct vcpu_vmx *vmx = to_vmx(vcpu);
13354         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
13355         bool evaluate_pending_interrupts;
13356         u32 exit_reason = EXIT_REASON_INVALID_STATE;
13357         u32 exit_qual;
13358
13359         evaluate_pending_interrupts = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
13360                 (CPU_BASED_VIRTUAL_INTR_PENDING | CPU_BASED_VIRTUAL_NMI_PENDING);
13361         if (likely(!evaluate_pending_interrupts) && kvm_vcpu_apicv_active(vcpu))
13362                 evaluate_pending_interrupts |= vmx_has_apicv_interrupt(vcpu);
13363
13364         if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
13365                 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
13366         if (kvm_mpx_supported() &&
13367                 !(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
13368                 vmx->nested.vmcs01_guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
13369
13370         vmx_switch_vmcs(vcpu, &vmx->nested.vmcs02);
13371
13372         prepare_vmcs02_early(vmx, vmcs12);
13373
13374         if (from_vmentry) {
13375                 nested_get_vmcs12_pages(vcpu);
13376
13377                 if (nested_vmx_check_vmentry_hw(vcpu)) {
13378                         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
13379                         return -1;
13380                 }
13381
13382                 if (check_vmentry_postreqs(vcpu, vmcs12, &exit_qual))
13383                         goto vmentry_fail_vmexit;
13384         }
13385
13386         enter_guest_mode(vcpu);
13387         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
13388                 vcpu->arch.tsc_offset += vmcs12->tsc_offset;
13389
13390         if (prepare_vmcs02(vcpu, vmcs12, &exit_qual))
13391                 goto vmentry_fail_vmexit_guest_mode;
13392
13393         if (from_vmentry) {
13394                 exit_reason = EXIT_REASON_MSR_LOAD_FAIL;
13395                 exit_qual = nested_vmx_load_msr(vcpu,
13396                                                 vmcs12->vm_entry_msr_load_addr,
13397                                                 vmcs12->vm_entry_msr_load_count);
13398                 if (exit_qual)
13399                         goto vmentry_fail_vmexit_guest_mode;
13400         } else {
13401                 /*
13402                  * The MMU is not initialized to point at the right entities yet and
13403                  * "get pages" would need to read data from the guest (i.e. we will
13404                  * need to perform gpa to hpa translation). Request a call
13405                  * to nested_get_vmcs12_pages before the next VM-entry.  The MSRs
13406                  * have already been set at vmentry time and should not be reset.
13407                  */
13408                 kvm_make_request(KVM_REQ_GET_VMCS12_PAGES, vcpu);
13409         }
13410
13411         /*
13412          * If L1 had a pending IRQ/NMI until it executed
13413          * VMLAUNCH/VMRESUME which wasn't delivered because it was
13414          * disallowed (e.g. interrupts disabled), L0 needs to
13415          * evaluate if this pending event should cause an exit from L2
13416          * to L1 or delivered directly to L2 (e.g. In case L1 don't
13417          * intercept EXTERNAL_INTERRUPT).
13418          *
13419          * Usually this would be handled by the processor noticing an
13420          * IRQ/NMI window request, or checking RVI during evaluation of
13421          * pending virtual interrupts.  However, this setting was done
13422          * on VMCS01 and now VMCS02 is active instead. Thus, we force L0
13423          * to perform pending event evaluation by requesting a KVM_REQ_EVENT.
13424          */
13425         if (unlikely(evaluate_pending_interrupts))
13426                 kvm_make_request(KVM_REQ_EVENT, vcpu);
13427
13428         /*
13429          * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
13430          * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
13431          * returned as far as L1 is concerned. It will only return (and set
13432          * the success flag) when L2 exits (see nested_vmx_vmexit()).
13433          */
13434         return 0;
13435
13436         /*
13437          * A failed consistency check that leads to a VMExit during L1's
13438          * VMEnter to L2 is a variation of a normal VMexit, as explained in
13439          * 26.7 "VM-entry failures during or after loading guest state".
13440          */
13441 vmentry_fail_vmexit_guest_mode:
13442         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
13443                 vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
13444         leave_guest_mode(vcpu);
13445
13446 vmentry_fail_vmexit:
13447         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
13448
13449         if (!from_vmentry)
13450                 return 1;
13451
13452         load_vmcs12_host_state(vcpu, vmcs12);
13453         vmcs12->vm_exit_reason = exit_reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
13454         vmcs12->exit_qualification = exit_qual;
13455         if (enable_shadow_vmcs || vmx->nested.hv_evmcs)
13456                 vmx->nested.need_vmcs12_sync = true;
13457         return 1;
13458 }
13459
13460 /*
13461  * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
13462  * for running an L2 nested guest.
13463  */
13464 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
13465 {
13466         struct vmcs12 *vmcs12;
13467         struct vcpu_vmx *vmx = to_vmx(vcpu);
13468         u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
13469         int ret;
13470
13471         if (!nested_vmx_check_permission(vcpu))
13472                 return 1;
13473
13474         if (!nested_vmx_handle_enlightened_vmptrld(vcpu, true))
13475                 return 1;
13476
13477         if (!vmx->nested.hv_evmcs && vmx->nested.current_vmptr == -1ull)
13478                 return nested_vmx_failInvalid(vcpu);
13479
13480         vmcs12 = get_vmcs12(vcpu);
13481
13482         /*
13483          * Can't VMLAUNCH or VMRESUME a shadow VMCS. Despite the fact
13484          * that there *is* a valid VMCS pointer, RFLAGS.CF is set
13485          * rather than RFLAGS.ZF, and no error number is stored to the
13486          * VM-instruction error field.
13487          */
13488         if (vmcs12->hdr.shadow_vmcs)
13489                 return nested_vmx_failInvalid(vcpu);
13490
13491         if (vmx->nested.hv_evmcs) {
13492                 copy_enlightened_to_vmcs12(vmx);
13493                 /* Enlightened VMCS doesn't have launch state */
13494                 vmcs12->launch_state = !launch;
13495         } else if (enable_shadow_vmcs) {
13496                 copy_shadow_to_vmcs12(vmx);
13497         }
13498
13499         /*
13500          * The nested entry process starts with enforcing various prerequisites
13501          * on vmcs12 as required by the Intel SDM, and act appropriately when
13502          * they fail: As the SDM explains, some conditions should cause the
13503          * instruction to fail, while others will cause the instruction to seem
13504          * to succeed, but return an EXIT_REASON_INVALID_STATE.
13505          * To speed up the normal (success) code path, we should avoid checking
13506          * for misconfigurations which will anyway be caught by the processor
13507          * when using the merged vmcs02.
13508          */
13509         if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS)
13510                 return nested_vmx_failValid(vcpu,
13511                         VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
13512
13513         if (vmcs12->launch_state == launch)
13514                 return nested_vmx_failValid(vcpu,
13515                         launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
13516                                : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
13517
13518         ret = check_vmentry_prereqs(vcpu, vmcs12);
13519         if (ret)
13520                 return nested_vmx_failValid(vcpu, ret);
13521
13522         /*
13523          * We're finally done with prerequisite checking, and can start with
13524          * the nested entry.
13525          */
13526         vmx->nested.nested_run_pending = 1;
13527         ret = nested_vmx_enter_non_root_mode(vcpu, true);
13528         vmx->nested.nested_run_pending = !ret;
13529         if (ret > 0)
13530                 return 1;
13531         else if (ret)
13532                 return nested_vmx_failValid(vcpu,
13533                         VMXERR_ENTRY_INVALID_CONTROL_FIELD);
13534
13535         /* Hide L1D cache contents from the nested guest.  */
13536         vmx->vcpu.arch.l1tf_flush_l1d = true;
13537
13538         /*
13539          * Must happen outside of nested_vmx_enter_non_root_mode() as it will
13540          * also be used as part of restoring nVMX state for
13541          * snapshot restore (migration).
13542          *
13543          * In this flow, it is assumed that vmcs12 cache was
13544          * trasferred as part of captured nVMX state and should
13545          * therefore not be read from guest memory (which may not
13546          * exist on destination host yet).
13547          */
13548         nested_cache_shadow_vmcs12(vcpu, vmcs12);
13549
13550         /*
13551          * If we're entering a halted L2 vcpu and the L2 vcpu won't be woken
13552          * by event injection, halt vcpu.
13553          */
13554         if ((vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT) &&
13555             !(vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK)) {
13556                 vmx->nested.nested_run_pending = 0;
13557                 return kvm_vcpu_halt(vcpu);
13558         }
13559         return 1;
13560 }
13561
13562 /*
13563  * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
13564  * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
13565  * This function returns the new value we should put in vmcs12.guest_cr0.
13566  * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
13567  *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
13568  *     available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
13569  *     didn't trap the bit, because if L1 did, so would L0).
13570  *  2. Bits that L1 asked to trap (and therefore L0 also did) could not have
13571  *     been modified by L2, and L1 knows it. So just leave the old value of
13572  *     the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
13573  *     isn't relevant, because if L0 traps this bit it can set it to anything.
13574  *  3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
13575  *     changed these bits, and therefore they need to be updated, but L0
13576  *     didn't necessarily allow them to be changed in GUEST_CR0 - and rather
13577  *     put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
13578  */
13579 static inline unsigned long
13580 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
13581 {
13582         return
13583         /*1*/   (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
13584         /*2*/   (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
13585         /*3*/   (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
13586                         vcpu->arch.cr0_guest_owned_bits));
13587 }
13588
13589 static inline unsigned long
13590 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
13591 {
13592         return
13593         /*1*/   (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
13594         /*2*/   (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
13595         /*3*/   (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
13596                         vcpu->arch.cr4_guest_owned_bits));
13597 }
13598
13599 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
13600                                        struct vmcs12 *vmcs12)
13601 {
13602         u32 idt_vectoring;
13603         unsigned int nr;
13604
13605         if (vcpu->arch.exception.injected) {
13606                 nr = vcpu->arch.exception.nr;
13607                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
13608
13609                 if (kvm_exception_is_soft(nr)) {
13610                         vmcs12->vm_exit_instruction_len =
13611                                 vcpu->arch.event_exit_inst_len;
13612                         idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
13613                 } else
13614                         idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
13615
13616                 if (vcpu->arch.exception.has_error_code) {
13617                         idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
13618                         vmcs12->idt_vectoring_error_code =
13619                                 vcpu->arch.exception.error_code;
13620                 }
13621
13622                 vmcs12->idt_vectoring_info_field = idt_vectoring;
13623         } else if (vcpu->arch.nmi_injected) {
13624                 vmcs12->idt_vectoring_info_field =
13625                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
13626         } else if (vcpu->arch.interrupt.injected) {
13627                 nr = vcpu->arch.interrupt.nr;
13628                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
13629
13630                 if (vcpu->arch.interrupt.soft) {
13631                         idt_vectoring |= INTR_TYPE_SOFT_INTR;
13632                         vmcs12->vm_entry_instruction_len =
13633                                 vcpu->arch.event_exit_inst_len;
13634                 } else
13635                         idt_vectoring |= INTR_TYPE_EXT_INTR;
13636
13637                 vmcs12->idt_vectoring_info_field = idt_vectoring;
13638         }
13639 }
13640
13641 static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
13642 {
13643         struct vcpu_vmx *vmx = to_vmx(vcpu);
13644         unsigned long exit_qual;
13645         bool block_nested_events =
13646             vmx->nested.nested_run_pending || kvm_event_needs_reinjection(vcpu);
13647
13648         if (vcpu->arch.exception.pending &&
13649                 nested_vmx_check_exception(vcpu, &exit_qual)) {
13650                 if (block_nested_events)
13651                         return -EBUSY;
13652                 nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
13653                 return 0;
13654         }
13655
13656         if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
13657             vmx->nested.preemption_timer_expired) {
13658                 if (block_nested_events)
13659                         return -EBUSY;
13660                 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
13661                 return 0;
13662         }
13663
13664         if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
13665                 if (block_nested_events)
13666                         return -EBUSY;
13667                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
13668                                   NMI_VECTOR | INTR_TYPE_NMI_INTR |
13669                                   INTR_INFO_VALID_MASK, 0);
13670                 /*
13671                  * The NMI-triggered VM exit counts as injection:
13672                  * clear this one and block further NMIs.
13673                  */
13674                 vcpu->arch.nmi_pending = 0;
13675                 vmx_set_nmi_mask(vcpu, true);
13676                 return 0;
13677         }
13678
13679         if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
13680             nested_exit_on_intr(vcpu)) {
13681                 if (block_nested_events)
13682                         return -EBUSY;
13683                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
13684                 return 0;
13685         }
13686
13687         vmx_complete_nested_posted_interrupt(vcpu);
13688         return 0;
13689 }
13690
13691 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
13692 {
13693         to_vmx(vcpu)->req_immediate_exit = true;
13694 }
13695
13696 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
13697 {
13698         ktime_t remaining =
13699                 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
13700         u64 value;
13701
13702         if (ktime_to_ns(remaining) <= 0)
13703                 return 0;
13704
13705         value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
13706         do_div(value, 1000000);
13707         return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
13708 }
13709
13710 /*
13711  * Update the guest state fields of vmcs12 to reflect changes that
13712  * occurred while L2 was running. (The "IA-32e mode guest" bit of the
13713  * VM-entry controls is also updated, since this is really a guest
13714  * state bit.)
13715  */
13716 static void sync_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
13717 {
13718         vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
13719         vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
13720
13721         vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
13722         vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
13723         vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
13724
13725         vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
13726         vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
13727         vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
13728         vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
13729         vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
13730         vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
13731         vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
13732         vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
13733         vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
13734         vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
13735         vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
13736         vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
13737         vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
13738         vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
13739         vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
13740         vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
13741         vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
13742         vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
13743         vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
13744         vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
13745         vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
13746         vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
13747         vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
13748         vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
13749         vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
13750         vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
13751         vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
13752         vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
13753         vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
13754         vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
13755         vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
13756         vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
13757         vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
13758         vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
13759         vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
13760         vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
13761
13762         vmcs12->guest_interruptibility_info =
13763                 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
13764         vmcs12->guest_pending_dbg_exceptions =
13765                 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
13766         if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
13767                 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
13768         else
13769                 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
13770
13771         if (nested_cpu_has_preemption_timer(vmcs12)) {
13772                 if (vmcs12->vm_exit_controls &
13773                     VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
13774                         vmcs12->vmx_preemption_timer_value =
13775                                 vmx_get_preemption_timer_value(vcpu);
13776                 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
13777         }
13778
13779         /*
13780          * In some cases (usually, nested EPT), L2 is allowed to change its
13781          * own CR3 without exiting. If it has changed it, we must keep it.
13782          * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
13783          * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
13784          *
13785          * Additionally, restore L2's PDPTR to vmcs12.
13786          */
13787         if (enable_ept) {
13788                 vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
13789                 vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
13790                 vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
13791                 vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
13792                 vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
13793         }
13794
13795         vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
13796
13797         if (nested_cpu_has_vid(vmcs12))
13798                 vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
13799
13800         vmcs12->vm_entry_controls =
13801                 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
13802                 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
13803
13804         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
13805                 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
13806                 vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
13807         }
13808
13809         /* TODO: These cannot have changed unless we have MSR bitmaps and
13810          * the relevant bit asks not to trap the change */
13811         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
13812                 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
13813         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
13814                 vmcs12->guest_ia32_efer = vcpu->arch.efer;
13815         vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
13816         vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
13817         vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
13818         if (kvm_mpx_supported())
13819                 vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
13820 }
13821
13822 /*
13823  * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
13824  * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
13825  * and this function updates it to reflect the changes to the guest state while
13826  * L2 was running (and perhaps made some exits which were handled directly by L0
13827  * without going back to L1), and to reflect the exit reason.
13828  * Note that we do not have to copy here all VMCS fields, just those that
13829  * could have changed by the L2 guest or the exit - i.e., the guest-state and
13830  * exit-information fields only. Other fields are modified by L1 with VMWRITE,
13831  * which already writes to vmcs12 directly.
13832  */
13833 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
13834                            u32 exit_reason, u32 exit_intr_info,
13835                            unsigned long exit_qualification)
13836 {
13837         /* update guest state fields: */
13838         sync_vmcs12(vcpu, vmcs12);
13839
13840         /* update exit information fields: */
13841
13842         vmcs12->vm_exit_reason = exit_reason;
13843         vmcs12->exit_qualification = exit_qualification;
13844         vmcs12->vm_exit_intr_info = exit_intr_info;
13845
13846         vmcs12->idt_vectoring_info_field = 0;
13847         vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
13848         vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
13849
13850         if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
13851                 vmcs12->launch_state = 1;
13852
13853                 /* vm_entry_intr_info_field is cleared on exit. Emulate this
13854                  * instead of reading the real value. */
13855                 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
13856
13857                 /*
13858                  * Transfer the event that L0 or L1 may wanted to inject into
13859                  * L2 to IDT_VECTORING_INFO_FIELD.
13860                  */
13861                 vmcs12_save_pending_event(vcpu, vmcs12);
13862         }
13863
13864         /*
13865          * Drop what we picked up for L2 via vmx_complete_interrupts. It is
13866          * preserved above and would only end up incorrectly in L1.
13867          */
13868         vcpu->arch.nmi_injected = false;
13869         kvm_clear_exception_queue(vcpu);
13870         kvm_clear_interrupt_queue(vcpu);
13871 }
13872
13873 /*
13874  * A part of what we need to when the nested L2 guest exits and we want to
13875  * run its L1 parent, is to reset L1's guest state to the host state specified
13876  * in vmcs12.
13877  * This function is to be called not only on normal nested exit, but also on
13878  * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
13879  * Failures During or After Loading Guest State").
13880  * This function should be called when the active VMCS is L1's (vmcs01).
13881  */
13882 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
13883                                    struct vmcs12 *vmcs12)
13884 {
13885         struct kvm_segment seg;
13886         u32 entry_failure_code;
13887
13888         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
13889                 vcpu->arch.efer = vmcs12->host_ia32_efer;
13890         else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
13891                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
13892         else
13893                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
13894         vmx_set_efer(vcpu, vcpu->arch.efer);
13895
13896         kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
13897         kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
13898         vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
13899         vmx_set_interrupt_shadow(vcpu, 0);
13900
13901         /*
13902          * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
13903          * actually changed, because vmx_set_cr0 refers to efer set above.
13904          *
13905          * CR0_GUEST_HOST_MASK is already set in the original vmcs01
13906          * (KVM doesn't change it);
13907          */
13908         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
13909         vmx_set_cr0(vcpu, vmcs12->host_cr0);
13910
13911         /* Same as above - no reason to call set_cr4_guest_host_mask().  */
13912         vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
13913         vmx_set_cr4(vcpu, vmcs12->host_cr4);
13914
13915         nested_ept_uninit_mmu_context(vcpu);
13916
13917         /*
13918          * Only PDPTE load can fail as the value of cr3 was checked on entry and
13919          * couldn't have changed.
13920          */
13921         if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
13922                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
13923
13924         if (!enable_ept)
13925                 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
13926
13927         /*
13928          * If vmcs01 doesn't use VPID, CPU flushes TLB on every
13929          * VMEntry/VMExit. Thus, no need to flush TLB.
13930          *
13931          * If vmcs12 doesn't use VPID, L1 expects TLB to be
13932          * flushed on every VMEntry/VMExit.
13933          *
13934          * Otherwise, we can preserve TLB entries as long as we are
13935          * able to tag L1 TLB entries differently than L2 TLB entries.
13936          *
13937          * If vmcs12 uses EPT, we need to execute this flush on EPTP01
13938          * and therefore we request the TLB flush to happen only after VMCS EPTP
13939          * has been set by KVM_REQ_LOAD_CR3.
13940          */
13941         if (enable_vpid &&
13942             (!nested_cpu_has_vpid(vmcs12) || !nested_has_guest_tlb_tag(vcpu))) {
13943                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
13944         }
13945
13946         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
13947         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
13948         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
13949         vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
13950         vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
13951         vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
13952         vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
13953
13954         /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1.  */
13955         if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
13956                 vmcs_write64(GUEST_BNDCFGS, 0);
13957
13958         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
13959                 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
13960                 vcpu->arch.pat = vmcs12->host_ia32_pat;
13961         }
13962         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
13963                 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
13964                         vmcs12->host_ia32_perf_global_ctrl);
13965
13966         /* Set L1 segment info according to Intel SDM
13967             27.5.2 Loading Host Segment and Descriptor-Table Registers */
13968         seg = (struct kvm_segment) {
13969                 .base = 0,
13970                 .limit = 0xFFFFFFFF,
13971                 .selector = vmcs12->host_cs_selector,
13972                 .type = 11,
13973                 .present = 1,
13974                 .s = 1,
13975                 .g = 1
13976         };
13977         if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
13978                 seg.l = 1;
13979         else
13980                 seg.db = 1;
13981         vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
13982         seg = (struct kvm_segment) {
13983                 .base = 0,
13984                 .limit = 0xFFFFFFFF,
13985                 .type = 3,
13986                 .present = 1,
13987                 .s = 1,
13988                 .db = 1,
13989                 .g = 1
13990         };
13991         seg.selector = vmcs12->host_ds_selector;
13992         vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
13993         seg.selector = vmcs12->host_es_selector;
13994         vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
13995         seg.selector = vmcs12->host_ss_selector;
13996         vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
13997         seg.selector = vmcs12->host_fs_selector;
13998         seg.base = vmcs12->host_fs_base;
13999         vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
14000         seg.selector = vmcs12->host_gs_selector;
14001         seg.base = vmcs12->host_gs_base;
14002         vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
14003         seg = (struct kvm_segment) {
14004                 .base = vmcs12->host_tr_base,
14005                 .limit = 0x67,
14006                 .selector = vmcs12->host_tr_selector,
14007                 .type = 11,
14008                 .present = 1
14009         };
14010         vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
14011
14012         kvm_set_dr(vcpu, 7, 0x400);
14013         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
14014
14015         if (cpu_has_vmx_msr_bitmap())
14016                 vmx_update_msr_bitmap(vcpu);
14017
14018         if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
14019                                 vmcs12->vm_exit_msr_load_count))
14020                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
14021 }
14022
14023 static inline u64 nested_vmx_get_vmcs01_guest_efer(struct vcpu_vmx *vmx)
14024 {
14025         struct shared_msr_entry *efer_msr;
14026         unsigned int i;
14027
14028         if (vm_entry_controls_get(vmx) & VM_ENTRY_LOAD_IA32_EFER)
14029                 return vmcs_read64(GUEST_IA32_EFER);
14030
14031         if (cpu_has_load_ia32_efer)
14032                 return host_efer;
14033
14034         for (i = 0; i < vmx->msr_autoload.guest.nr; ++i) {
14035                 if (vmx->msr_autoload.guest.val[i].index == MSR_EFER)
14036                         return vmx->msr_autoload.guest.val[i].value;
14037         }
14038
14039         efer_msr = find_msr_entry(vmx, MSR_EFER);
14040         if (efer_msr)
14041                 return efer_msr->data;
14042
14043         return host_efer;
14044 }
14045
14046 static void nested_vmx_restore_host_state(struct kvm_vcpu *vcpu)
14047 {
14048         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
14049         struct vcpu_vmx *vmx = to_vmx(vcpu);
14050         struct vmx_msr_entry g, h;
14051         struct msr_data msr;
14052         gpa_t gpa;
14053         u32 i, j;
14054
14055         vcpu->arch.pat = vmcs_read64(GUEST_IA32_PAT);
14056
14057         if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
14058                 /*
14059                  * L1's host DR7 is lost if KVM_GUESTDBG_USE_HW_BP is set
14060                  * as vmcs01.GUEST_DR7 contains a userspace defined value
14061                  * and vcpu->arch.dr7 is not squirreled away before the
14062                  * nested VMENTER (not worth adding a variable in nested_vmx).
14063                  */
14064                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
14065                         kvm_set_dr(vcpu, 7, DR7_FIXED_1);
14066                 else
14067                         WARN_ON(kvm_set_dr(vcpu, 7, vmcs_readl(GUEST_DR7)));
14068         }
14069
14070         /*
14071          * Note that calling vmx_set_{efer,cr0,cr4} is important as they
14072          * handle a variety of side effects to KVM's software model.
14073          */
14074         vmx_set_efer(vcpu, nested_vmx_get_vmcs01_guest_efer(vmx));
14075
14076         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
14077         vmx_set_cr0(vcpu, vmcs_readl(CR0_READ_SHADOW));
14078
14079         vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
14080         vmx_set_cr4(vcpu, vmcs_readl(CR4_READ_SHADOW));
14081
14082         nested_ept_uninit_mmu_context(vcpu);
14083         vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
14084         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
14085
14086         /*
14087          * Use ept_save_pdptrs(vcpu) to load the MMU's cached PDPTRs
14088          * from vmcs01 (if necessary).  The PDPTRs are not loaded on
14089          * VMFail, like everything else we just need to ensure our
14090          * software model is up-to-date.
14091          */
14092         ept_save_pdptrs(vcpu);
14093
14094         kvm_mmu_reset_context(vcpu);
14095
14096         if (cpu_has_vmx_msr_bitmap())
14097                 vmx_update_msr_bitmap(vcpu);
14098
14099         /*
14100          * This nasty bit of open coding is a compromise between blindly
14101          * loading L1's MSRs using the exit load lists (incorrect emulation
14102          * of VMFail), leaving the nested VM's MSRs in the software model
14103          * (incorrect behavior) and snapshotting the modified MSRs (too
14104          * expensive since the lists are unbound by hardware).  For each
14105          * MSR that was (prematurely) loaded from the nested VMEntry load
14106          * list, reload it from the exit load list if it exists and differs
14107          * from the guest value.  The intent is to stuff host state as
14108          * silently as possible, not to fully process the exit load list.
14109          */
14110         msr.host_initiated = false;
14111         for (i = 0; i < vmcs12->vm_entry_msr_load_count; i++) {
14112                 gpa = vmcs12->vm_entry_msr_load_addr + (i * sizeof(g));
14113                 if (kvm_vcpu_read_guest(vcpu, gpa, &g, sizeof(g))) {
14114                         pr_debug_ratelimited(
14115                                 "%s read MSR index failed (%u, 0x%08llx)\n",
14116                                 __func__, i, gpa);
14117                         goto vmabort;
14118                 }
14119
14120                 for (j = 0; j < vmcs12->vm_exit_msr_load_count; j++) {
14121                         gpa = vmcs12->vm_exit_msr_load_addr + (j * sizeof(h));
14122                         if (kvm_vcpu_read_guest(vcpu, gpa, &h, sizeof(h))) {
14123                                 pr_debug_ratelimited(
14124                                         "%s read MSR failed (%u, 0x%08llx)\n",
14125                                         __func__, j, gpa);
14126                                 goto vmabort;
14127                         }
14128                         if (h.index != g.index)
14129                                 continue;
14130                         if (h.value == g.value)
14131                                 break;
14132
14133                         if (nested_vmx_load_msr_check(vcpu, &h)) {
14134                                 pr_debug_ratelimited(
14135                                         "%s check failed (%u, 0x%x, 0x%x)\n",
14136                                         __func__, j, h.index, h.reserved);
14137                                 goto vmabort;
14138                         }
14139
14140                         msr.index = h.index;
14141                         msr.data = h.value;
14142                         if (kvm_set_msr(vcpu, &msr)) {
14143                                 pr_debug_ratelimited(
14144                                         "%s WRMSR failed (%u, 0x%x, 0x%llx)\n",
14145                                         __func__, j, h.index, h.value);
14146                                 goto vmabort;
14147                         }
14148                 }
14149         }
14150
14151         return;
14152
14153 vmabort:
14154         nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
14155 }
14156
14157 /*
14158  * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
14159  * and modify vmcs12 to make it see what it would expect to see there if
14160  * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
14161  */
14162 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
14163                               u32 exit_intr_info,
14164                               unsigned long exit_qualification)
14165 {
14166         struct vcpu_vmx *vmx = to_vmx(vcpu);
14167         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
14168
14169         /* trying to cancel vmlaunch/vmresume is a bug */
14170         WARN_ON_ONCE(vmx->nested.nested_run_pending);
14171
14172         leave_guest_mode(vcpu);
14173
14174         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
14175                 vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
14176
14177         if (likely(!vmx->fail)) {
14178                 if (exit_reason == -1)
14179                         sync_vmcs12(vcpu, vmcs12);
14180                 else
14181                         prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
14182                                        exit_qualification);
14183
14184                 /*
14185                  * Must happen outside of sync_vmcs12() as it will
14186                  * also be used to capture vmcs12 cache as part of
14187                  * capturing nVMX state for snapshot (migration).
14188                  *
14189                  * Otherwise, this flush will dirty guest memory at a
14190                  * point it is already assumed by user-space to be
14191                  * immutable.
14192                  */
14193                 nested_flush_cached_shadow_vmcs12(vcpu, vmcs12);
14194
14195                 if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
14196                                          vmcs12->vm_exit_msr_store_count))
14197                         nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
14198         } else {
14199                 /*
14200                  * The only expected VM-instruction error is "VM entry with
14201                  * invalid control field(s)." Anything else indicates a
14202                  * problem with L0.  And we should never get here with a
14203                  * VMFail of any type if early consistency checks are enabled.
14204                  */
14205                 WARN_ON_ONCE(vmcs_read32(VM_INSTRUCTION_ERROR) !=
14206                              VMXERR_ENTRY_INVALID_CONTROL_FIELD);
14207                 WARN_ON_ONCE(nested_early_check);
14208         }
14209
14210         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
14211
14212         /* Update any VMCS fields that might have changed while L2 ran */
14213         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
14214         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
14215         vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
14216
14217         if (kvm_has_tsc_control)
14218                 decache_tsc_multiplier(vmx);
14219
14220         if (vmx->nested.change_vmcs01_virtual_apic_mode) {
14221                 vmx->nested.change_vmcs01_virtual_apic_mode = false;
14222                 vmx_set_virtual_apic_mode(vcpu);
14223         } else if (!nested_cpu_has_ept(vmcs12) &&
14224                    nested_cpu_has2(vmcs12,
14225                                    SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
14226                 vmx_flush_tlb(vcpu, true);
14227         }
14228
14229         /* This is needed for same reason as it was needed in prepare_vmcs02 */
14230         vmx->host_rsp = 0;
14231
14232         /* Unpin physical memory we referred to in vmcs02 */
14233         if (vmx->nested.apic_access_page) {
14234                 kvm_release_page_dirty(vmx->nested.apic_access_page);
14235                 vmx->nested.apic_access_page = NULL;
14236         }
14237         if (vmx->nested.virtual_apic_page) {
14238                 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
14239                 vmx->nested.virtual_apic_page = NULL;
14240         }
14241         if (vmx->nested.pi_desc_page) {
14242                 kunmap(vmx->nested.pi_desc_page);
14243                 kvm_release_page_dirty(vmx->nested.pi_desc_page);
14244                 vmx->nested.pi_desc_page = NULL;
14245                 vmx->nested.pi_desc = NULL;
14246         }
14247
14248         /*
14249          * We are now running in L2, mmu_notifier will force to reload the
14250          * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
14251          */
14252         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
14253
14254         if ((exit_reason != -1) && (enable_shadow_vmcs || vmx->nested.hv_evmcs))
14255                 vmx->nested.need_vmcs12_sync = true;
14256
14257         /* in case we halted in L2 */
14258         vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
14259
14260         if (likely(!vmx->fail)) {
14261                 /*
14262                  * TODO: SDM says that with acknowledge interrupt on
14263                  * exit, bit 31 of the VM-exit interrupt information
14264                  * (valid interrupt) is always set to 1 on
14265                  * EXIT_REASON_EXTERNAL_INTERRUPT, so we shouldn't
14266                  * need kvm_cpu_has_interrupt().  See the commit
14267                  * message for details.
14268                  */
14269                 if (nested_exit_intr_ack_set(vcpu) &&
14270                     exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT &&
14271                     kvm_cpu_has_interrupt(vcpu)) {
14272                         int irq = kvm_cpu_get_interrupt(vcpu);
14273                         WARN_ON(irq < 0);
14274                         vmcs12->vm_exit_intr_info = irq |
14275                                 INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
14276                 }
14277
14278                 if (exit_reason != -1)
14279                         trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
14280                                                        vmcs12->exit_qualification,
14281                                                        vmcs12->idt_vectoring_info_field,
14282                                                        vmcs12->vm_exit_intr_info,
14283                                                        vmcs12->vm_exit_intr_error_code,
14284                                                        KVM_ISA_VMX);
14285
14286                 load_vmcs12_host_state(vcpu, vmcs12);
14287
14288                 return;
14289         }
14290
14291         /*
14292          * After an early L2 VM-entry failure, we're now back
14293          * in L1 which thinks it just finished a VMLAUNCH or
14294          * VMRESUME instruction, so we need to set the failure
14295          * flag and the VM-instruction error field of the VMCS
14296          * accordingly, and skip the emulated instruction.
14297          */
14298         (void)nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
14299
14300         /*
14301          * Restore L1's host state to KVM's software model.  We're here
14302          * because a consistency check was caught by hardware, which
14303          * means some amount of guest state has been propagated to KVM's
14304          * model and needs to be unwound to the host's state.
14305          */
14306         nested_vmx_restore_host_state(vcpu);
14307
14308         vmx->fail = 0;
14309 }
14310
14311 /*
14312  * Forcibly leave nested mode in order to be able to reset the VCPU later on.
14313  */
14314 static void vmx_leave_nested(struct kvm_vcpu *vcpu)
14315 {
14316         if (is_guest_mode(vcpu)) {
14317                 to_vmx(vcpu)->nested.nested_run_pending = 0;
14318                 nested_vmx_vmexit(vcpu, -1, 0, 0);
14319         }
14320         free_nested(vcpu);
14321 }
14322
14323 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
14324                                struct x86_instruction_info *info,
14325                                enum x86_intercept_stage stage)
14326 {
14327         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
14328         struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
14329
14330         /*
14331          * RDPID causes #UD if disabled through secondary execution controls.
14332          * Because it is marked as EmulateOnUD, we need to intercept it here.
14333          */
14334         if (info->intercept == x86_intercept_rdtscp &&
14335             !nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
14336                 ctxt->exception.vector = UD_VECTOR;
14337                 ctxt->exception.error_code_valid = false;
14338                 return X86EMUL_PROPAGATE_FAULT;
14339         }
14340
14341         /* TODO: check more intercepts... */
14342         return X86EMUL_CONTINUE;
14343 }
14344
14345 #ifdef CONFIG_X86_64
14346 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
14347 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
14348                                   u64 divisor, u64 *result)
14349 {
14350         u64 low = a << shift, high = a >> (64 - shift);
14351
14352         /* To avoid the overflow on divq */
14353         if (high >= divisor)
14354                 return 1;
14355
14356         /* Low hold the result, high hold rem which is discarded */
14357         asm("divq %2\n\t" : "=a" (low), "=d" (high) :
14358             "rm" (divisor), "0" (low), "1" (high));
14359         *result = low;
14360
14361         return 0;
14362 }
14363
14364 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
14365 {
14366         struct vcpu_vmx *vmx;
14367         u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
14368
14369         if (kvm_mwait_in_guest(vcpu->kvm))
14370                 return -EOPNOTSUPP;
14371
14372         vmx = to_vmx(vcpu);
14373         tscl = rdtsc();
14374         guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
14375         delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
14376         lapic_timer_advance_cycles = nsec_to_cycles(vcpu, lapic_timer_advance_ns);
14377
14378         if (delta_tsc > lapic_timer_advance_cycles)
14379                 delta_tsc -= lapic_timer_advance_cycles;
14380         else
14381                 delta_tsc = 0;
14382
14383         /* Convert to host delta tsc if tsc scaling is enabled */
14384         if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
14385                         u64_shl_div_u64(delta_tsc,
14386                                 kvm_tsc_scaling_ratio_frac_bits,
14387                                 vcpu->arch.tsc_scaling_ratio,
14388                                 &delta_tsc))
14389                 return -ERANGE;
14390
14391         /*
14392          * If the delta tsc can't fit in the 32 bit after the multi shift,
14393          * we can't use the preemption timer.
14394          * It's possible that it fits on later vmentries, but checking
14395          * on every vmentry is costly so we just use an hrtimer.
14396          */
14397         if (delta_tsc >> (cpu_preemption_timer_multi + 32))
14398                 return -ERANGE;
14399
14400         vmx->hv_deadline_tsc = tscl + delta_tsc;
14401         return delta_tsc == 0;
14402 }
14403
14404 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
14405 {
14406         to_vmx(vcpu)->hv_deadline_tsc = -1;
14407 }
14408 #endif
14409
14410 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
14411 {
14412         if (!kvm_pause_in_guest(vcpu->kvm))
14413                 shrink_ple_window(vcpu);
14414 }
14415
14416 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
14417                                      struct kvm_memory_slot *slot)
14418 {
14419         kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
14420         kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
14421 }
14422
14423 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
14424                                        struct kvm_memory_slot *slot)
14425 {
14426         kvm_mmu_slot_set_dirty(kvm, slot);
14427 }
14428
14429 static void vmx_flush_log_dirty(struct kvm *kvm)
14430 {
14431         kvm_flush_pml_buffers(kvm);
14432 }
14433
14434 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
14435 {
14436         struct vmcs12 *vmcs12;
14437         struct vcpu_vmx *vmx = to_vmx(vcpu);
14438         gpa_t gpa;
14439         struct page *page = NULL;
14440         u64 *pml_address;
14441
14442         if (is_guest_mode(vcpu)) {
14443                 WARN_ON_ONCE(vmx->nested.pml_full);
14444
14445                 /*
14446                  * Check if PML is enabled for the nested guest.
14447                  * Whether eptp bit 6 is set is already checked
14448                  * as part of A/D emulation.
14449                  */
14450                 vmcs12 = get_vmcs12(vcpu);
14451                 if (!nested_cpu_has_pml(vmcs12))
14452                         return 0;
14453
14454                 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
14455                         vmx->nested.pml_full = true;
14456                         return 1;
14457                 }
14458
14459                 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
14460
14461                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->pml_address);
14462                 if (is_error_page(page))
14463                         return 0;
14464
14465                 pml_address = kmap(page);
14466                 pml_address[vmcs12->guest_pml_index--] = gpa;
14467                 kunmap(page);
14468                 kvm_release_page_clean(page);
14469         }
14470
14471         return 0;
14472 }
14473
14474 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
14475                                            struct kvm_memory_slot *memslot,
14476                                            gfn_t offset, unsigned long mask)
14477 {
14478         kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
14479 }
14480
14481 static void __pi_post_block(struct kvm_vcpu *vcpu)
14482 {
14483         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
14484         struct pi_desc old, new;
14485         unsigned int dest;
14486
14487         do {
14488                 old.control = new.control = pi_desc->control;
14489                 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
14490                      "Wakeup handler not enabled while the VCPU is blocked\n");
14491
14492                 dest = cpu_physical_id(vcpu->cpu);
14493
14494                 if (x2apic_enabled())
14495                         new.ndst = dest;
14496                 else
14497                         new.ndst = (dest << 8) & 0xFF00;
14498
14499                 /* set 'NV' to 'notification vector' */
14500                 new.nv = POSTED_INTR_VECTOR;
14501         } while (cmpxchg64(&pi_desc->control, old.control,
14502                            new.control) != old.control);
14503
14504         if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
14505                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
14506                 list_del(&vcpu->blocked_vcpu_list);
14507                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
14508                 vcpu->pre_pcpu = -1;
14509         }
14510 }
14511
14512 /*
14513  * This routine does the following things for vCPU which is going
14514  * to be blocked if VT-d PI is enabled.
14515  * - Store the vCPU to the wakeup list, so when interrupts happen
14516  *   we can find the right vCPU to wake up.
14517  * - Change the Posted-interrupt descriptor as below:
14518  *      'NDST' <-- vcpu->pre_pcpu
14519  *      'NV' <-- POSTED_INTR_WAKEUP_VECTOR
14520  * - If 'ON' is set during this process, which means at least one
14521  *   interrupt is posted for this vCPU, we cannot block it, in
14522  *   this case, return 1, otherwise, return 0.
14523  *
14524  */
14525 static int pi_pre_block(struct kvm_vcpu *vcpu)
14526 {
14527         unsigned int dest;
14528         struct pi_desc old, new;
14529         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
14530
14531         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
14532                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
14533                 !kvm_vcpu_apicv_active(vcpu))
14534                 return 0;
14535
14536         WARN_ON(irqs_disabled());
14537         local_irq_disable();
14538         if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
14539                 vcpu->pre_pcpu = vcpu->cpu;
14540                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
14541                 list_add_tail(&vcpu->blocked_vcpu_list,
14542                               &per_cpu(blocked_vcpu_on_cpu,
14543                                        vcpu->pre_pcpu));
14544                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
14545         }
14546
14547         do {
14548                 old.control = new.control = pi_desc->control;
14549
14550                 WARN((pi_desc->sn == 1),
14551                      "Warning: SN field of posted-interrupts "
14552                      "is set before blocking\n");
14553
14554                 /*
14555                  * Since vCPU can be preempted during this process,
14556                  * vcpu->cpu could be different with pre_pcpu, we
14557                  * need to set pre_pcpu as the destination of wakeup
14558                  * notification event, then we can find the right vCPU
14559                  * to wakeup in wakeup handler if interrupts happen
14560                  * when the vCPU is in blocked state.
14561                  */
14562                 dest = cpu_physical_id(vcpu->pre_pcpu);
14563
14564                 if (x2apic_enabled())
14565                         new.ndst = dest;
14566                 else
14567                         new.ndst = (dest << 8) & 0xFF00;
14568
14569                 /* set 'NV' to 'wakeup vector' */
14570                 new.nv = POSTED_INTR_WAKEUP_VECTOR;
14571         } while (cmpxchg64(&pi_desc->control, old.control,
14572                            new.control) != old.control);
14573
14574         /* We should not block the vCPU if an interrupt is posted for it.  */
14575         if (pi_test_on(pi_desc) == 1)
14576                 __pi_post_block(vcpu);
14577
14578         local_irq_enable();
14579         return (vcpu->pre_pcpu == -1);
14580 }
14581
14582 static int vmx_pre_block(struct kvm_vcpu *vcpu)
14583 {
14584         if (pi_pre_block(vcpu))
14585                 return 1;
14586
14587         if (kvm_lapic_hv_timer_in_use(vcpu))
14588                 kvm_lapic_switch_to_sw_timer(vcpu);
14589
14590         return 0;
14591 }
14592
14593 static void pi_post_block(struct kvm_vcpu *vcpu)
14594 {
14595         if (vcpu->pre_pcpu == -1)
14596                 return;
14597
14598         WARN_ON(irqs_disabled());
14599         local_irq_disable();
14600         __pi_post_block(vcpu);
14601         local_irq_enable();
14602 }
14603
14604 static void vmx_post_block(struct kvm_vcpu *vcpu)
14605 {
14606         if (kvm_x86_ops->set_hv_timer)
14607                 kvm_lapic_switch_to_hv_timer(vcpu);
14608
14609         pi_post_block(vcpu);
14610 }
14611
14612 /*
14613  * vmx_update_pi_irte - set IRTE for Posted-Interrupts
14614  *
14615  * @kvm: kvm
14616  * @host_irq: host irq of the interrupt
14617  * @guest_irq: gsi of the interrupt
14618  * @set: set or unset PI
14619  * returns 0 on success, < 0 on failure
14620  */
14621 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
14622                               uint32_t guest_irq, bool set)
14623 {
14624         struct kvm_kernel_irq_routing_entry *e;
14625         struct kvm_irq_routing_table *irq_rt;
14626         struct kvm_lapic_irq irq;
14627         struct kvm_vcpu *vcpu;
14628         struct vcpu_data vcpu_info;
14629         int idx, ret = 0;
14630
14631         if (!kvm_arch_has_assigned_device(kvm) ||
14632                 !irq_remapping_cap(IRQ_POSTING_CAP) ||
14633                 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
14634                 return 0;
14635
14636         idx = srcu_read_lock(&kvm->irq_srcu);
14637         irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
14638         if (guest_irq >= irq_rt->nr_rt_entries ||
14639             hlist_empty(&irq_rt->map[guest_irq])) {
14640                 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
14641                              guest_irq, irq_rt->nr_rt_entries);
14642                 goto out;
14643         }
14644
14645         hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
14646                 if (e->type != KVM_IRQ_ROUTING_MSI)
14647                         continue;
14648                 /*
14649                  * VT-d PI cannot support posting multicast/broadcast
14650                  * interrupts to a vCPU, we still use interrupt remapping
14651                  * for these kind of interrupts.
14652                  *
14653                  * For lowest-priority interrupts, we only support
14654                  * those with single CPU as the destination, e.g. user
14655                  * configures the interrupts via /proc/irq or uses
14656                  * irqbalance to make the interrupts single-CPU.
14657                  *
14658                  * We will support full lowest-priority interrupt later.
14659                  */
14660
14661                 kvm_set_msi_irq(kvm, e, &irq);
14662                 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
14663                         /*
14664                          * Make sure the IRTE is in remapped mode if
14665                          * we don't handle it in posted mode.
14666                          */
14667                         ret = irq_set_vcpu_affinity(host_irq, NULL);
14668                         if (ret < 0) {
14669                                 printk(KERN_INFO
14670                                    "failed to back to remapped mode, irq: %u\n",
14671                                    host_irq);
14672                                 goto out;
14673                         }
14674
14675                         continue;
14676                 }
14677
14678                 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
14679                 vcpu_info.vector = irq.vector;
14680
14681                 trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
14682                                 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
14683
14684                 if (set)
14685                         ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
14686                 else
14687                         ret = irq_set_vcpu_affinity(host_irq, NULL);
14688
14689                 if (ret < 0) {
14690                         printk(KERN_INFO "%s: failed to update PI IRTE\n",
14691                                         __func__);
14692                         goto out;
14693                 }
14694         }
14695
14696         ret = 0;
14697 out:
14698         srcu_read_unlock(&kvm->irq_srcu, idx);
14699         return ret;
14700 }
14701
14702 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
14703 {
14704         if (vcpu->arch.mcg_cap & MCG_LMCE_P)
14705                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
14706                         FEATURE_CONTROL_LMCE;
14707         else
14708                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
14709                         ~FEATURE_CONTROL_LMCE;
14710 }
14711
14712 static int vmx_smi_allowed(struct kvm_vcpu *vcpu)
14713 {
14714         /* we need a nested vmexit to enter SMM, postpone if run is pending */
14715         if (to_vmx(vcpu)->nested.nested_run_pending)
14716                 return 0;
14717         return 1;
14718 }
14719
14720 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
14721 {
14722         struct vcpu_vmx *vmx = to_vmx(vcpu);
14723
14724         vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
14725         if (vmx->nested.smm.guest_mode)
14726                 nested_vmx_vmexit(vcpu, -1, 0, 0);
14727
14728         vmx->nested.smm.vmxon = vmx->nested.vmxon;
14729         vmx->nested.vmxon = false;
14730         vmx_clear_hlt(vcpu);
14731         return 0;
14732 }
14733
14734 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
14735 {
14736         struct vcpu_vmx *vmx = to_vmx(vcpu);
14737         int ret;
14738
14739         if (vmx->nested.smm.vmxon) {
14740                 vmx->nested.vmxon = true;
14741                 vmx->nested.smm.vmxon = false;
14742         }
14743
14744         if (vmx->nested.smm.guest_mode) {
14745                 vcpu->arch.hflags &= ~HF_SMM_MASK;
14746                 ret = nested_vmx_enter_non_root_mode(vcpu, false);
14747                 vcpu->arch.hflags |= HF_SMM_MASK;
14748                 if (ret)
14749                         return ret;
14750
14751                 vmx->nested.smm.guest_mode = false;
14752         }
14753         return 0;
14754 }
14755
14756 static int enable_smi_window(struct kvm_vcpu *vcpu)
14757 {
14758         return 0;
14759 }
14760
14761 static inline int vmx_has_valid_vmcs12(struct kvm_vcpu *vcpu)
14762 {
14763         struct vcpu_vmx *vmx = to_vmx(vcpu);
14764
14765         /*
14766          * In case we do two consecutive get/set_nested_state()s while L2 was
14767          * running hv_evmcs may end up not being mapped (we map it from
14768          * nested_vmx_run()/vmx_vcpu_run()). Check is_guest_mode() as we always
14769          * have vmcs12 if it is true.
14770          */
14771         return is_guest_mode(vcpu) || vmx->nested.current_vmptr != -1ull ||
14772                 vmx->nested.hv_evmcs;
14773 }
14774
14775 static int vmx_get_nested_state(struct kvm_vcpu *vcpu,
14776                                 struct kvm_nested_state __user *user_kvm_nested_state,
14777                                 u32 user_data_size)
14778 {
14779         struct vcpu_vmx *vmx;
14780         struct vmcs12 *vmcs12;
14781         struct kvm_nested_state kvm_state = {
14782                 .flags = 0,
14783                 .format = 0,
14784                 .size = sizeof(kvm_state),
14785                 .vmx.vmxon_pa = -1ull,
14786                 .vmx.vmcs_pa = -1ull,
14787         };
14788
14789         if (!vcpu)
14790                 return kvm_state.size + 2 * VMCS12_SIZE;
14791
14792         vmx = to_vmx(vcpu);
14793         vmcs12 = get_vmcs12(vcpu);
14794
14795         if (nested_vmx_allowed(vcpu) && vmx->nested.enlightened_vmcs_enabled)
14796                 kvm_state.flags |= KVM_STATE_NESTED_EVMCS;
14797
14798         if (nested_vmx_allowed(vcpu) &&
14799             (vmx->nested.vmxon || vmx->nested.smm.vmxon)) {
14800                 kvm_state.vmx.vmxon_pa = vmx->nested.vmxon_ptr;
14801                 kvm_state.vmx.vmcs_pa = vmx->nested.current_vmptr;
14802
14803                 if (vmx_has_valid_vmcs12(vcpu)) {
14804                         kvm_state.size += VMCS12_SIZE;
14805
14806                         if (is_guest_mode(vcpu) &&
14807                             nested_cpu_has_shadow_vmcs(vmcs12) &&
14808                             vmcs12->vmcs_link_pointer != -1ull)
14809                                 kvm_state.size += VMCS12_SIZE;
14810                 }
14811
14812                 if (vmx->nested.smm.vmxon)
14813                         kvm_state.vmx.smm.flags |= KVM_STATE_NESTED_SMM_VMXON;
14814
14815                 if (vmx->nested.smm.guest_mode)
14816                         kvm_state.vmx.smm.flags |= KVM_STATE_NESTED_SMM_GUEST_MODE;
14817
14818                 if (is_guest_mode(vcpu)) {
14819                         kvm_state.flags |= KVM_STATE_NESTED_GUEST_MODE;
14820
14821                         if (vmx->nested.nested_run_pending)
14822                                 kvm_state.flags |= KVM_STATE_NESTED_RUN_PENDING;
14823                 }
14824         }
14825
14826         if (user_data_size < kvm_state.size)
14827                 goto out;
14828
14829         if (copy_to_user(user_kvm_nested_state, &kvm_state, sizeof(kvm_state)))
14830                 return -EFAULT;
14831
14832         if (!vmx_has_valid_vmcs12(vcpu))
14833                 goto out;
14834
14835         /*
14836          * When running L2, the authoritative vmcs12 state is in the
14837          * vmcs02. When running L1, the authoritative vmcs12 state is
14838          * in the shadow or enlightened vmcs linked to vmcs01, unless
14839          * need_vmcs12_sync is set, in which case, the authoritative
14840          * vmcs12 state is in the vmcs12 already.
14841          */
14842         if (is_guest_mode(vcpu)) {
14843                 sync_vmcs12(vcpu, vmcs12);
14844         } else if (!vmx->nested.need_vmcs12_sync) {
14845                 if (vmx->nested.hv_evmcs)
14846                         copy_enlightened_to_vmcs12(vmx);
14847                 else if (enable_shadow_vmcs)
14848                         copy_shadow_to_vmcs12(vmx);
14849         }
14850
14851         if (copy_to_user(user_kvm_nested_state->data, vmcs12, sizeof(*vmcs12)))
14852                 return -EFAULT;
14853
14854         if (nested_cpu_has_shadow_vmcs(vmcs12) &&
14855             vmcs12->vmcs_link_pointer != -1ull) {
14856                 if (copy_to_user(user_kvm_nested_state->data + VMCS12_SIZE,
14857                                  get_shadow_vmcs12(vcpu), sizeof(*vmcs12)))
14858                         return -EFAULT;
14859         }
14860
14861 out:
14862         return kvm_state.size;
14863 }
14864
14865 static int vmx_set_nested_state(struct kvm_vcpu *vcpu,
14866                                 struct kvm_nested_state __user *user_kvm_nested_state,
14867                                 struct kvm_nested_state *kvm_state)
14868 {
14869         struct vcpu_vmx *vmx = to_vmx(vcpu);
14870         struct vmcs12 *vmcs12;
14871         u32 exit_qual;
14872         int ret;
14873
14874         if (kvm_state->format != 0)
14875                 return -EINVAL;
14876
14877         if (kvm_state->flags & KVM_STATE_NESTED_EVMCS)
14878                 nested_enable_evmcs(vcpu, NULL);
14879
14880         if (!nested_vmx_allowed(vcpu))
14881                 return kvm_state->vmx.vmxon_pa == -1ull ? 0 : -EINVAL;
14882
14883         if (kvm_state->vmx.vmxon_pa == -1ull) {
14884                 if (kvm_state->vmx.smm.flags)
14885                         return -EINVAL;
14886
14887                 if (kvm_state->vmx.vmcs_pa != -1ull)
14888                         return -EINVAL;
14889
14890                 vmx_leave_nested(vcpu);
14891                 return 0;
14892         }
14893
14894         if (!page_address_valid(vcpu, kvm_state->vmx.vmxon_pa))
14895                 return -EINVAL;
14896
14897         if ((kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
14898             (kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
14899                 return -EINVAL;
14900
14901         if (kvm_state->vmx.smm.flags &
14902             ~(KVM_STATE_NESTED_SMM_GUEST_MODE | KVM_STATE_NESTED_SMM_VMXON))
14903                 return -EINVAL;
14904
14905         /*
14906          * SMM temporarily disables VMX, so we cannot be in guest mode,
14907          * nor can VMLAUNCH/VMRESUME be pending.  Outside SMM, SMM flags
14908          * must be zero.
14909          */
14910         if (is_smm(vcpu) ? kvm_state->flags : kvm_state->vmx.smm.flags)
14911                 return -EINVAL;
14912
14913         if ((kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
14914             !(kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON))
14915                 return -EINVAL;
14916
14917         vmx_leave_nested(vcpu);
14918         if (kvm_state->vmx.vmxon_pa == -1ull)
14919                 return 0;
14920
14921         vmx->nested.vmxon_ptr = kvm_state->vmx.vmxon_pa;
14922         ret = enter_vmx_operation(vcpu);
14923         if (ret)
14924                 return ret;
14925
14926         /* Empty 'VMXON' state is permitted */
14927         if (kvm_state->size < sizeof(kvm_state) + sizeof(*vmcs12))
14928                 return 0;
14929
14930         if (kvm_state->vmx.vmcs_pa != -1ull) {
14931                 if (kvm_state->vmx.vmcs_pa == kvm_state->vmx.vmxon_pa ||
14932                     !page_address_valid(vcpu, kvm_state->vmx.vmcs_pa))
14933                         return -EINVAL;
14934
14935                 set_current_vmptr(vmx, kvm_state->vmx.vmcs_pa);
14936         } else if (kvm_state->flags & KVM_STATE_NESTED_EVMCS) {
14937                 /*
14938                  * Sync eVMCS upon entry as we may not have
14939                  * HV_X64_MSR_VP_ASSIST_PAGE set up yet.
14940                  */
14941                 vmx->nested.need_vmcs12_sync = true;
14942         } else {
14943                 return -EINVAL;
14944         }
14945
14946         if (kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON) {
14947                 vmx->nested.smm.vmxon = true;
14948                 vmx->nested.vmxon = false;
14949
14950                 if (kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE)
14951                         vmx->nested.smm.guest_mode = true;
14952         }
14953
14954         vmcs12 = get_vmcs12(vcpu);
14955         if (copy_from_user(vmcs12, user_kvm_nested_state->data, sizeof(*vmcs12)))
14956                 return -EFAULT;
14957
14958         if (vmcs12->hdr.revision_id != VMCS12_REVISION)
14959                 return -EINVAL;
14960
14961         if (!(kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
14962                 return 0;
14963
14964         vmx->nested.nested_run_pending =
14965                 !!(kvm_state->flags & KVM_STATE_NESTED_RUN_PENDING);
14966
14967         if (nested_cpu_has_shadow_vmcs(vmcs12) &&
14968             vmcs12->vmcs_link_pointer != -1ull) {
14969                 struct vmcs12 *shadow_vmcs12 = get_shadow_vmcs12(vcpu);
14970                 if (kvm_state->size < sizeof(kvm_state) + 2 * sizeof(*vmcs12))
14971                         return -EINVAL;
14972
14973                 if (copy_from_user(shadow_vmcs12,
14974                                    user_kvm_nested_state->data + VMCS12_SIZE,
14975                                    sizeof(*vmcs12)))
14976                         return -EFAULT;
14977
14978                 if (shadow_vmcs12->hdr.revision_id != VMCS12_REVISION ||
14979                     !shadow_vmcs12->hdr.shadow_vmcs)
14980                         return -EINVAL;
14981         }
14982
14983         if (check_vmentry_prereqs(vcpu, vmcs12) ||
14984             check_vmentry_postreqs(vcpu, vmcs12, &exit_qual))
14985                 return -EINVAL;
14986
14987         vmx->nested.dirty_vmcs12 = true;
14988         ret = nested_vmx_enter_non_root_mode(vcpu, false);
14989         if (ret)
14990                 return -EINVAL;
14991
14992         return 0;
14993 }
14994
14995 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
14996         .cpu_has_kvm_support = cpu_has_kvm_support,
14997         .disabled_by_bios = vmx_disabled_by_bios,
14998         .hardware_setup = hardware_setup,
14999         .hardware_unsetup = hardware_unsetup,
15000         .check_processor_compatibility = vmx_check_processor_compat,
15001         .hardware_enable = hardware_enable,
15002         .hardware_disable = hardware_disable,
15003         .cpu_has_accelerated_tpr = report_flexpriority,
15004         .has_emulated_msr = vmx_has_emulated_msr,
15005
15006         .vm_init = vmx_vm_init,
15007         .vm_alloc = vmx_vm_alloc,
15008         .vm_free = vmx_vm_free,
15009
15010         .vcpu_create = vmx_create_vcpu,
15011         .vcpu_free = vmx_free_vcpu,
15012         .vcpu_reset = vmx_vcpu_reset,
15013
15014         .prepare_guest_switch = vmx_prepare_switch_to_guest,
15015         .vcpu_load = vmx_vcpu_load,
15016         .vcpu_put = vmx_vcpu_put,
15017
15018         .update_bp_intercept = update_exception_bitmap,
15019         .get_msr_feature = vmx_get_msr_feature,
15020         .get_msr = vmx_get_msr,
15021         .set_msr = vmx_set_msr,
15022         .get_segment_base = vmx_get_segment_base,
15023         .get_segment = vmx_get_segment,
15024         .set_segment = vmx_set_segment,
15025         .get_cpl = vmx_get_cpl,
15026         .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
15027         .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
15028         .decache_cr3 = vmx_decache_cr3,
15029         .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
15030         .set_cr0 = vmx_set_cr0,
15031         .set_cr3 = vmx_set_cr3,
15032         .set_cr4 = vmx_set_cr4,
15033         .set_efer = vmx_set_efer,
15034         .get_idt = vmx_get_idt,
15035         .set_idt = vmx_set_idt,
15036         .get_gdt = vmx_get_gdt,
15037         .set_gdt = vmx_set_gdt,
15038         .get_dr6 = vmx_get_dr6,
15039         .set_dr6 = vmx_set_dr6,
15040         .set_dr7 = vmx_set_dr7,
15041         .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
15042         .cache_reg = vmx_cache_reg,
15043         .get_rflags = vmx_get_rflags,
15044         .set_rflags = vmx_set_rflags,
15045
15046         .tlb_flush = vmx_flush_tlb,
15047         .tlb_flush_gva = vmx_flush_tlb_gva,
15048
15049         .run = vmx_vcpu_run,
15050         .handle_exit = vmx_handle_exit,
15051         .skip_emulated_instruction = skip_emulated_instruction,
15052         .set_interrupt_shadow = vmx_set_interrupt_shadow,
15053         .get_interrupt_shadow = vmx_get_interrupt_shadow,
15054         .patch_hypercall = vmx_patch_hypercall,
15055         .set_irq = vmx_inject_irq,
15056         .set_nmi = vmx_inject_nmi,
15057         .queue_exception = vmx_queue_exception,
15058         .cancel_injection = vmx_cancel_injection,
15059         .interrupt_allowed = vmx_interrupt_allowed,
15060         .nmi_allowed = vmx_nmi_allowed,
15061         .get_nmi_mask = vmx_get_nmi_mask,
15062         .set_nmi_mask = vmx_set_nmi_mask,
15063         .enable_nmi_window = enable_nmi_window,
15064         .enable_irq_window = enable_irq_window,
15065         .update_cr8_intercept = update_cr8_intercept,
15066         .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
15067         .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
15068         .get_enable_apicv = vmx_get_enable_apicv,
15069         .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
15070         .load_eoi_exitmap = vmx_load_eoi_exitmap,
15071         .apicv_post_state_restore = vmx_apicv_post_state_restore,
15072         .hwapic_irr_update = vmx_hwapic_irr_update,
15073         .hwapic_isr_update = vmx_hwapic_isr_update,
15074         .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
15075         .sync_pir_to_irr = vmx_sync_pir_to_irr,
15076         .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
15077
15078         .set_tss_addr = vmx_set_tss_addr,
15079         .set_identity_map_addr = vmx_set_identity_map_addr,
15080         .get_tdp_level = get_ept_level,
15081         .get_mt_mask = vmx_get_mt_mask,
15082
15083         .get_exit_info = vmx_get_exit_info,
15084
15085         .get_lpage_level = vmx_get_lpage_level,
15086
15087         .cpuid_update = vmx_cpuid_update,
15088
15089         .rdtscp_supported = vmx_rdtscp_supported,
15090         .invpcid_supported = vmx_invpcid_supported,
15091
15092         .set_supported_cpuid = vmx_set_supported_cpuid,
15093
15094         .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
15095
15096         .read_l1_tsc_offset = vmx_read_l1_tsc_offset,
15097         .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
15098
15099         .set_tdp_cr3 = vmx_set_cr3,
15100
15101         .check_intercept = vmx_check_intercept,
15102         .handle_external_intr = vmx_handle_external_intr,
15103         .mpx_supported = vmx_mpx_supported,
15104         .xsaves_supported = vmx_xsaves_supported,
15105         .umip_emulated = vmx_umip_emulated,
15106
15107         .check_nested_events = vmx_check_nested_events,
15108         .request_immediate_exit = vmx_request_immediate_exit,
15109
15110         .sched_in = vmx_sched_in,
15111
15112         .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
15113         .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
15114         .flush_log_dirty = vmx_flush_log_dirty,
15115         .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
15116         .write_log_dirty = vmx_write_pml_buffer,
15117
15118         .pre_block = vmx_pre_block,
15119         .post_block = vmx_post_block,
15120
15121         .pmu_ops = &intel_pmu_ops,
15122
15123         .update_pi_irte = vmx_update_pi_irte,
15124
15125 #ifdef CONFIG_X86_64
15126         .set_hv_timer = vmx_set_hv_timer,
15127         .cancel_hv_timer = vmx_cancel_hv_timer,
15128 #endif
15129
15130         .setup_mce = vmx_setup_mce,
15131
15132         .get_nested_state = vmx_get_nested_state,
15133         .set_nested_state = vmx_set_nested_state,
15134         .get_vmcs12_pages = nested_get_vmcs12_pages,
15135
15136         .smi_allowed = vmx_smi_allowed,
15137         .pre_enter_smm = vmx_pre_enter_smm,
15138         .pre_leave_smm = vmx_pre_leave_smm,
15139         .enable_smi_window = enable_smi_window,
15140
15141         .nested_enable_evmcs = nested_enable_evmcs,
15142 };
15143
15144 static void vmx_cleanup_l1d_flush(void)
15145 {
15146         if (vmx_l1d_flush_pages) {
15147                 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
15148                 vmx_l1d_flush_pages = NULL;
15149         }
15150         /* Restore state so sysfs ignores VMX */
15151         l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
15152 }
15153
15154 static void vmx_exit(void)
15155 {
15156 #ifdef CONFIG_KEXEC_CORE
15157         RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
15158         synchronize_rcu();
15159 #endif
15160
15161         kvm_exit();
15162
15163 #if IS_ENABLED(CONFIG_HYPERV)
15164         if (static_branch_unlikely(&enable_evmcs)) {
15165                 int cpu;
15166                 struct hv_vp_assist_page *vp_ap;
15167                 /*
15168                  * Reset everything to support using non-enlightened VMCS
15169                  * access later (e.g. when we reload the module with
15170                  * enlightened_vmcs=0)
15171                  */
15172                 for_each_online_cpu(cpu) {
15173                         vp_ap = hv_get_vp_assist_page(cpu);
15174
15175                         if (!vp_ap)
15176                                 continue;
15177
15178                         vp_ap->current_nested_vmcs = 0;
15179                         vp_ap->enlighten_vmentry = 0;
15180                 }
15181
15182                 static_branch_disable(&enable_evmcs);
15183         }
15184 #endif
15185         vmx_cleanup_l1d_flush();
15186 }
15187 module_exit(vmx_exit);
15188
15189 static int __init vmx_init(void)
15190 {
15191         int r;
15192
15193 #if IS_ENABLED(CONFIG_HYPERV)
15194         /*
15195          * Enlightened VMCS usage should be recommended and the host needs
15196          * to support eVMCS v1 or above. We can also disable eVMCS support
15197          * with module parameter.
15198          */
15199         if (enlightened_vmcs &&
15200             ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
15201             (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
15202             KVM_EVMCS_VERSION) {
15203                 int cpu;
15204
15205                 /* Check that we have assist pages on all online CPUs */
15206                 for_each_online_cpu(cpu) {
15207                         if (!hv_get_vp_assist_page(cpu)) {
15208                                 enlightened_vmcs = false;
15209                                 break;
15210                         }
15211                 }
15212
15213                 if (enlightened_vmcs) {
15214                         pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
15215                         static_branch_enable(&enable_evmcs);
15216                 }
15217         } else {
15218                 enlightened_vmcs = false;
15219         }
15220 #endif
15221
15222         r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
15223                      __alignof__(struct vcpu_vmx), THIS_MODULE);
15224         if (r)
15225                 return r;
15226
15227         /*
15228          * Must be called after kvm_init() so enable_ept is properly set
15229          * up. Hand the parameter mitigation value in which was stored in
15230          * the pre module init parser. If no parameter was given, it will
15231          * contain 'auto' which will be turned into the default 'cond'
15232          * mitigation mode.
15233          */
15234         if (boot_cpu_has(X86_BUG_L1TF)) {
15235                 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
15236                 if (r) {
15237                         vmx_exit();
15238                         return r;
15239                 }
15240         }
15241
15242 #ifdef CONFIG_KEXEC_CORE
15243         rcu_assign_pointer(crash_vmclear_loaded_vmcss,
15244                            crash_vmclear_local_loaded_vmcss);
15245 #endif
15246         vmx_check_vmcs12_offsets();
15247
15248         return 0;
15249 }
15250 module_init(vmx_init);