6f303ccd478d729a38329b900a1cc9c21c9e6551
[linux-2.6-microblaze.git] / arch / x86 / kvm / vmx / nested.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 #include <linux/frame.h>
4 #include <linux/percpu.h>
5
6 #include <asm/debugreg.h>
7 #include <asm/mmu_context.h>
8
9 #include "cpuid.h"
10 #include "hyperv.h"
11 #include "mmu.h"
12 #include "nested.h"
13 #include "pmu.h"
14 #include "trace.h"
15 #include "x86.h"
16
17 static bool __read_mostly enable_shadow_vmcs = 1;
18 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
19
20 static bool __read_mostly nested_early_check = 0;
21 module_param(nested_early_check, bool, S_IRUGO);
22
23 #define CC(consistency_check)                                           \
24 ({                                                                      \
25         bool failed = (consistency_check);                              \
26         if (failed)                                                     \
27                 trace_kvm_nested_vmenter_failed(#consistency_check, 0); \
28         failed;                                                         \
29 })
30
31 /*
32  * Hyper-V requires all of these, so mark them as supported even though
33  * they are just treated the same as all-context.
34  */
35 #define VMX_VPID_EXTENT_SUPPORTED_MASK          \
36         (VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT |  \
37         VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT |    \
38         VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT |    \
39         VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
40
41 #define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
42
43 enum {
44         VMX_VMREAD_BITMAP,
45         VMX_VMWRITE_BITMAP,
46         VMX_BITMAP_NR
47 };
48 static unsigned long *vmx_bitmap[VMX_BITMAP_NR];
49
50 #define vmx_vmread_bitmap                    (vmx_bitmap[VMX_VMREAD_BITMAP])
51 #define vmx_vmwrite_bitmap                   (vmx_bitmap[VMX_VMWRITE_BITMAP])
52
53 struct shadow_vmcs_field {
54         u16     encoding;
55         u16     offset;
56 };
57 static struct shadow_vmcs_field shadow_read_only_fields[] = {
58 #define SHADOW_FIELD_RO(x, y) { x, offsetof(struct vmcs12, y) },
59 #include "vmcs_shadow_fields.h"
60 };
61 static int max_shadow_read_only_fields =
62         ARRAY_SIZE(shadow_read_only_fields);
63
64 static struct shadow_vmcs_field shadow_read_write_fields[] = {
65 #define SHADOW_FIELD_RW(x, y) { x, offsetof(struct vmcs12, y) },
66 #include "vmcs_shadow_fields.h"
67 };
68 static int max_shadow_read_write_fields =
69         ARRAY_SIZE(shadow_read_write_fields);
70
71 static void init_vmcs_shadow_fields(void)
72 {
73         int i, j;
74
75         memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
76         memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
77
78         for (i = j = 0; i < max_shadow_read_only_fields; i++) {
79                 struct shadow_vmcs_field entry = shadow_read_only_fields[i];
80                 u16 field = entry.encoding;
81
82                 if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
83                     (i + 1 == max_shadow_read_only_fields ||
84                      shadow_read_only_fields[i + 1].encoding != field + 1))
85                         pr_err("Missing field from shadow_read_only_field %x\n",
86                                field + 1);
87
88                 clear_bit(field, vmx_vmread_bitmap);
89                 if (field & 1)
90 #ifdef CONFIG_X86_64
91                         continue;
92 #else
93                         entry.offset += sizeof(u32);
94 #endif
95                 shadow_read_only_fields[j++] = entry;
96         }
97         max_shadow_read_only_fields = j;
98
99         for (i = j = 0; i < max_shadow_read_write_fields; i++) {
100                 struct shadow_vmcs_field entry = shadow_read_write_fields[i];
101                 u16 field = entry.encoding;
102
103                 if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
104                     (i + 1 == max_shadow_read_write_fields ||
105                      shadow_read_write_fields[i + 1].encoding != field + 1))
106                         pr_err("Missing field from shadow_read_write_field %x\n",
107                                field + 1);
108
109                 WARN_ONCE(field >= GUEST_ES_AR_BYTES &&
110                           field <= GUEST_TR_AR_BYTES,
111                           "Update vmcs12_write_any() to drop reserved bits from AR_BYTES");
112
113                 /*
114                  * PML and the preemption timer can be emulated, but the
115                  * processor cannot vmwrite to fields that don't exist
116                  * on bare metal.
117                  */
118                 switch (field) {
119                 case GUEST_PML_INDEX:
120                         if (!cpu_has_vmx_pml())
121                                 continue;
122                         break;
123                 case VMX_PREEMPTION_TIMER_VALUE:
124                         if (!cpu_has_vmx_preemption_timer())
125                                 continue;
126                         break;
127                 case GUEST_INTR_STATUS:
128                         if (!cpu_has_vmx_apicv())
129                                 continue;
130                         break;
131                 default:
132                         break;
133                 }
134
135                 clear_bit(field, vmx_vmwrite_bitmap);
136                 clear_bit(field, vmx_vmread_bitmap);
137                 if (field & 1)
138 #ifdef CONFIG_X86_64
139                         continue;
140 #else
141                         entry.offset += sizeof(u32);
142 #endif
143                 shadow_read_write_fields[j++] = entry;
144         }
145         max_shadow_read_write_fields = j;
146 }
147
148 /*
149  * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
150  * set the success or error code of an emulated VMX instruction (as specified
151  * by Vol 2B, VMX Instruction Reference, "Conventions"), and skip the emulated
152  * instruction.
153  */
154 static int nested_vmx_succeed(struct kvm_vcpu *vcpu)
155 {
156         vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
157                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
158                             X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
159         return kvm_skip_emulated_instruction(vcpu);
160 }
161
162 static int nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
163 {
164         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
165                         & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
166                             X86_EFLAGS_SF | X86_EFLAGS_OF))
167                         | X86_EFLAGS_CF);
168         return kvm_skip_emulated_instruction(vcpu);
169 }
170
171 static int nested_vmx_failValid(struct kvm_vcpu *vcpu,
172                                 u32 vm_instruction_error)
173 {
174         struct vcpu_vmx *vmx = to_vmx(vcpu);
175
176         /*
177          * failValid writes the error number to the current VMCS, which
178          * can't be done if there isn't a current VMCS.
179          */
180         if (vmx->nested.current_vmptr == -1ull && !vmx->nested.hv_evmcs)
181                 return nested_vmx_failInvalid(vcpu);
182
183         vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
184                         & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
185                             X86_EFLAGS_SF | X86_EFLAGS_OF))
186                         | X86_EFLAGS_ZF);
187         get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
188         /*
189          * We don't need to force a shadow sync because
190          * VM_INSTRUCTION_ERROR is not shadowed
191          */
192         return kvm_skip_emulated_instruction(vcpu);
193 }
194
195 static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
196 {
197         /* TODO: not to reset guest simply here. */
198         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
199         pr_debug_ratelimited("kvm: nested vmx abort, indicator %d\n", indicator);
200 }
201
202 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
203 {
204         return fixed_bits_valid(control, low, high);
205 }
206
207 static inline u64 vmx_control_msr(u32 low, u32 high)
208 {
209         return low | ((u64)high << 32);
210 }
211
212 static void vmx_disable_shadow_vmcs(struct vcpu_vmx *vmx)
213 {
214         secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_SHADOW_VMCS);
215         vmcs_write64(VMCS_LINK_POINTER, -1ull);
216         vmx->nested.need_vmcs12_to_shadow_sync = false;
217 }
218
219 static inline void nested_release_evmcs(struct kvm_vcpu *vcpu)
220 {
221         struct vcpu_vmx *vmx = to_vmx(vcpu);
222
223         if (!vmx->nested.hv_evmcs)
224                 return;
225
226         kvm_vcpu_unmap(vcpu, &vmx->nested.hv_evmcs_map, true);
227         vmx->nested.hv_evmcs_vmptr = 0;
228         vmx->nested.hv_evmcs = NULL;
229 }
230
231 /*
232  * Free whatever needs to be freed from vmx->nested when L1 goes down, or
233  * just stops using VMX.
234  */
235 static void free_nested(struct kvm_vcpu *vcpu)
236 {
237         struct vcpu_vmx *vmx = to_vmx(vcpu);
238
239         if (!vmx->nested.vmxon && !vmx->nested.smm.vmxon)
240                 return;
241
242         kvm_clear_request(KVM_REQ_GET_VMCS12_PAGES, vcpu);
243
244         vmx->nested.vmxon = false;
245         vmx->nested.smm.vmxon = false;
246         free_vpid(vmx->nested.vpid02);
247         vmx->nested.posted_intr_nv = -1;
248         vmx->nested.current_vmptr = -1ull;
249         if (enable_shadow_vmcs) {
250                 vmx_disable_shadow_vmcs(vmx);
251                 vmcs_clear(vmx->vmcs01.shadow_vmcs);
252                 free_vmcs(vmx->vmcs01.shadow_vmcs);
253                 vmx->vmcs01.shadow_vmcs = NULL;
254         }
255         kfree(vmx->nested.cached_vmcs12);
256         vmx->nested.cached_vmcs12 = NULL;
257         kfree(vmx->nested.cached_shadow_vmcs12);
258         vmx->nested.cached_shadow_vmcs12 = NULL;
259         /* Unpin physical memory we referred to in the vmcs02 */
260         if (vmx->nested.apic_access_page) {
261                 kvm_release_page_clean(vmx->nested.apic_access_page);
262                 vmx->nested.apic_access_page = NULL;
263         }
264         kvm_vcpu_unmap(vcpu, &vmx->nested.virtual_apic_map, true);
265         kvm_vcpu_unmap(vcpu, &vmx->nested.pi_desc_map, true);
266         vmx->nested.pi_desc = NULL;
267
268         kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
269
270         nested_release_evmcs(vcpu);
271
272         free_loaded_vmcs(&vmx->nested.vmcs02);
273 }
274
275 static void vmx_sync_vmcs_host_state(struct vcpu_vmx *vmx,
276                                      struct loaded_vmcs *prev)
277 {
278         struct vmcs_host_state *dest, *src;
279
280         if (unlikely(!vmx->guest_state_loaded))
281                 return;
282
283         src = &prev->host_state;
284         dest = &vmx->loaded_vmcs->host_state;
285
286         vmx_set_host_fs_gs(dest, src->fs_sel, src->gs_sel, src->fs_base, src->gs_base);
287         dest->ldt_sel = src->ldt_sel;
288 #ifdef CONFIG_X86_64
289         dest->ds_sel = src->ds_sel;
290         dest->es_sel = src->es_sel;
291 #endif
292 }
293
294 static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
295 {
296         struct vcpu_vmx *vmx = to_vmx(vcpu);
297         struct loaded_vmcs *prev;
298         int cpu;
299
300         if (vmx->loaded_vmcs == vmcs)
301                 return;
302
303         cpu = get_cpu();
304         prev = vmx->loaded_vmcs;
305         vmx->loaded_vmcs = vmcs;
306         vmx_vcpu_load_vmcs(vcpu, cpu);
307         vmx_sync_vmcs_host_state(vmx, prev);
308         put_cpu();
309
310         vmx_segment_cache_clear(vmx);
311 }
312
313 /*
314  * Ensure that the current vmcs of the logical processor is the
315  * vmcs01 of the vcpu before calling free_nested().
316  */
317 void nested_vmx_free_vcpu(struct kvm_vcpu *vcpu)
318 {
319         vcpu_load(vcpu);
320         vmx_leave_nested(vcpu);
321         vmx_switch_vmcs(vcpu, &to_vmx(vcpu)->vmcs01);
322         free_nested(vcpu);
323         vcpu_put(vcpu);
324 }
325
326 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
327                 struct x86_exception *fault)
328 {
329         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
330         struct vcpu_vmx *vmx = to_vmx(vcpu);
331         u32 vm_exit_reason;
332         unsigned long exit_qualification = vcpu->arch.exit_qualification;
333
334         if (vmx->nested.pml_full) {
335                 vm_exit_reason = EXIT_REASON_PML_FULL;
336                 vmx->nested.pml_full = false;
337                 exit_qualification &= INTR_INFO_UNBLOCK_NMI;
338         } else if (fault->error_code & PFERR_RSVD_MASK)
339                 vm_exit_reason = EXIT_REASON_EPT_MISCONFIG;
340         else
341                 vm_exit_reason = EXIT_REASON_EPT_VIOLATION;
342
343         nested_vmx_vmexit(vcpu, vm_exit_reason, 0, exit_qualification);
344         vmcs12->guest_physical_address = fault->address;
345 }
346
347 static void nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
348 {
349         WARN_ON(mmu_is_nested(vcpu));
350
351         vcpu->arch.mmu = &vcpu->arch.guest_mmu;
352         kvm_init_shadow_ept_mmu(vcpu,
353                         to_vmx(vcpu)->nested.msrs.ept_caps &
354                         VMX_EPT_EXECUTE_ONLY_BIT,
355                         nested_ept_ad_enabled(vcpu),
356                         nested_ept_get_eptp(vcpu));
357         vcpu->arch.mmu->get_guest_pgd     = nested_ept_get_eptp;
358         vcpu->arch.mmu->inject_page_fault = nested_ept_inject_page_fault;
359         vcpu->arch.mmu->get_pdptr         = kvm_pdptr_read;
360
361         vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
362 }
363
364 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
365 {
366         vcpu->arch.mmu = &vcpu->arch.root_mmu;
367         vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
368 }
369
370 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
371                                             u16 error_code)
372 {
373         bool inequality, bit;
374
375         bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
376         inequality =
377                 (error_code & vmcs12->page_fault_error_code_mask) !=
378                  vmcs12->page_fault_error_code_match;
379         return inequality ^ bit;
380 }
381
382
383 /*
384  * KVM wants to inject page-faults which it got to the guest. This function
385  * checks whether in a nested guest, we need to inject them to L1 or L2.
386  */
387 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned long *exit_qual)
388 {
389         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
390         unsigned int nr = vcpu->arch.exception.nr;
391         bool has_payload = vcpu->arch.exception.has_payload;
392         unsigned long payload = vcpu->arch.exception.payload;
393
394         if (nr == PF_VECTOR) {
395                 if (vcpu->arch.exception.nested_apf) {
396                         *exit_qual = vcpu->arch.apf.nested_apf_token;
397                         return 1;
398                 }
399                 if (nested_vmx_is_page_fault_vmexit(vmcs12,
400                                                     vcpu->arch.exception.error_code)) {
401                         *exit_qual = has_payload ? payload : vcpu->arch.cr2;
402                         return 1;
403                 }
404         } else if (vmcs12->exception_bitmap & (1u << nr)) {
405                 if (nr == DB_VECTOR) {
406                         if (!has_payload) {
407                                 payload = vcpu->arch.dr6;
408                                 payload &= ~(DR6_FIXED_1 | DR6_BT);
409                                 payload ^= DR6_RTM;
410                         }
411                         *exit_qual = payload;
412                 } else
413                         *exit_qual = 0;
414                 return 1;
415         }
416
417         return 0;
418 }
419
420
421 static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
422                 struct x86_exception *fault)
423 {
424         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
425
426         WARN_ON(!is_guest_mode(vcpu));
427
428         if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code) &&
429                 !to_vmx(vcpu)->nested.nested_run_pending) {
430                 vmcs12->vm_exit_intr_error_code = fault->error_code;
431                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
432                                   PF_VECTOR | INTR_TYPE_HARD_EXCEPTION |
433                                   INTR_INFO_DELIVER_CODE_MASK | INTR_INFO_VALID_MASK,
434                                   fault->address);
435         } else {
436                 kvm_inject_page_fault(vcpu, fault);
437         }
438 }
439
440 static bool page_address_valid(struct kvm_vcpu *vcpu, gpa_t gpa)
441 {
442         return PAGE_ALIGNED(gpa) && !(gpa >> cpuid_maxphyaddr(vcpu));
443 }
444
445 static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,
446                                                struct vmcs12 *vmcs12)
447 {
448         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
449                 return 0;
450
451         if (CC(!page_address_valid(vcpu, vmcs12->io_bitmap_a)) ||
452             CC(!page_address_valid(vcpu, vmcs12->io_bitmap_b)))
453                 return -EINVAL;
454
455         return 0;
456 }
457
458 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
459                                                 struct vmcs12 *vmcs12)
460 {
461         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
462                 return 0;
463
464         if (CC(!page_address_valid(vcpu, vmcs12->msr_bitmap)))
465                 return -EINVAL;
466
467         return 0;
468 }
469
470 static int nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu *vcpu,
471                                                 struct vmcs12 *vmcs12)
472 {
473         if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
474                 return 0;
475
476         if (CC(!page_address_valid(vcpu, vmcs12->virtual_apic_page_addr)))
477                 return -EINVAL;
478
479         return 0;
480 }
481
482 /*
483  * Check if MSR is intercepted for L01 MSR bitmap.
484  */
485 static bool msr_write_intercepted_l01(struct kvm_vcpu *vcpu, u32 msr)
486 {
487         unsigned long *msr_bitmap;
488         int f = sizeof(unsigned long);
489
490         if (!cpu_has_vmx_msr_bitmap())
491                 return true;
492
493         msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
494
495         if (msr <= 0x1fff) {
496                 return !!test_bit(msr, msr_bitmap + 0x800 / f);
497         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
498                 msr &= 0x1fff;
499                 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
500         }
501
502         return true;
503 }
504
505 /*
506  * If a msr is allowed by L0, we should check whether it is allowed by L1.
507  * The corresponding bit will be cleared unless both of L0 and L1 allow it.
508  */
509 static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
510                                                unsigned long *msr_bitmap_nested,
511                                                u32 msr, int type)
512 {
513         int f = sizeof(unsigned long);
514
515         /*
516          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
517          * have the write-low and read-high bitmap offsets the wrong way round.
518          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
519          */
520         if (msr <= 0x1fff) {
521                 if (type & MSR_TYPE_R &&
522                    !test_bit(msr, msr_bitmap_l1 + 0x000 / f))
523                         /* read-low */
524                         __clear_bit(msr, msr_bitmap_nested + 0x000 / f);
525
526                 if (type & MSR_TYPE_W &&
527                    !test_bit(msr, msr_bitmap_l1 + 0x800 / f))
528                         /* write-low */
529                         __clear_bit(msr, msr_bitmap_nested + 0x800 / f);
530
531         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
532                 msr &= 0x1fff;
533                 if (type & MSR_TYPE_R &&
534                    !test_bit(msr, msr_bitmap_l1 + 0x400 / f))
535                         /* read-high */
536                         __clear_bit(msr, msr_bitmap_nested + 0x400 / f);
537
538                 if (type & MSR_TYPE_W &&
539                    !test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
540                         /* write-high */
541                         __clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
542
543         }
544 }
545
546 static inline void enable_x2apic_msr_intercepts(unsigned long *msr_bitmap)
547 {
548         int msr;
549
550         for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
551                 unsigned word = msr / BITS_PER_LONG;
552
553                 msr_bitmap[word] = ~0;
554                 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
555         }
556 }
557
558 /*
559  * Merge L0's and L1's MSR bitmap, return false to indicate that
560  * we do not use the hardware.
561  */
562 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
563                                                  struct vmcs12 *vmcs12)
564 {
565         int msr;
566         unsigned long *msr_bitmap_l1;
567         unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.vmcs02.msr_bitmap;
568         struct kvm_host_map *map = &to_vmx(vcpu)->nested.msr_bitmap_map;
569
570         /* Nothing to do if the MSR bitmap is not in use.  */
571         if (!cpu_has_vmx_msr_bitmap() ||
572             !nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
573                 return false;
574
575         if (kvm_vcpu_map(vcpu, gpa_to_gfn(vmcs12->msr_bitmap), map))
576                 return false;
577
578         msr_bitmap_l1 = (unsigned long *)map->hva;
579
580         /*
581          * To keep the control flow simple, pay eight 8-byte writes (sixteen
582          * 4-byte writes on 32-bit systems) up front to enable intercepts for
583          * the x2APIC MSR range and selectively disable them below.
584          */
585         enable_x2apic_msr_intercepts(msr_bitmap_l0);
586
587         if (nested_cpu_has_virt_x2apic_mode(vmcs12)) {
588                 if (nested_cpu_has_apic_reg_virt(vmcs12)) {
589                         /*
590                          * L0 need not intercept reads for MSRs between 0x800
591                          * and 0x8ff, it just lets the processor take the value
592                          * from the virtual-APIC page; take those 256 bits
593                          * directly from the L1 bitmap.
594                          */
595                         for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
596                                 unsigned word = msr / BITS_PER_LONG;
597
598                                 msr_bitmap_l0[word] = msr_bitmap_l1[word];
599                         }
600                 }
601
602                 nested_vmx_disable_intercept_for_msr(
603                         msr_bitmap_l1, msr_bitmap_l0,
604                         X2APIC_MSR(APIC_TASKPRI),
605                         MSR_TYPE_R | MSR_TYPE_W);
606
607                 if (nested_cpu_has_vid(vmcs12)) {
608                         nested_vmx_disable_intercept_for_msr(
609                                 msr_bitmap_l1, msr_bitmap_l0,
610                                 X2APIC_MSR(APIC_EOI),
611                                 MSR_TYPE_W);
612                         nested_vmx_disable_intercept_for_msr(
613                                 msr_bitmap_l1, msr_bitmap_l0,
614                                 X2APIC_MSR(APIC_SELF_IPI),
615                                 MSR_TYPE_W);
616                 }
617         }
618
619         /* KVM unconditionally exposes the FS/GS base MSRs to L1. */
620         nested_vmx_disable_intercept_for_msr(msr_bitmap_l1, msr_bitmap_l0,
621                                              MSR_FS_BASE, MSR_TYPE_RW);
622
623         nested_vmx_disable_intercept_for_msr(msr_bitmap_l1, msr_bitmap_l0,
624                                              MSR_GS_BASE, MSR_TYPE_RW);
625
626         nested_vmx_disable_intercept_for_msr(msr_bitmap_l1, msr_bitmap_l0,
627                                              MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
628
629         /*
630          * Checking the L0->L1 bitmap is trying to verify two things:
631          *
632          * 1. L0 gave a permission to L1 to actually passthrough the MSR. This
633          *    ensures that we do not accidentally generate an L02 MSR bitmap
634          *    from the L12 MSR bitmap that is too permissive.
635          * 2. That L1 or L2s have actually used the MSR. This avoids
636          *    unnecessarily merging of the bitmap if the MSR is unused. This
637          *    works properly because we only update the L01 MSR bitmap lazily.
638          *    So even if L0 should pass L1 these MSRs, the L01 bitmap is only
639          *    updated to reflect this when L1 (or its L2s) actually write to
640          *    the MSR.
641          */
642         if (!msr_write_intercepted_l01(vcpu, MSR_IA32_SPEC_CTRL))
643                 nested_vmx_disable_intercept_for_msr(
644                                         msr_bitmap_l1, msr_bitmap_l0,
645                                         MSR_IA32_SPEC_CTRL,
646                                         MSR_TYPE_R | MSR_TYPE_W);
647
648         if (!msr_write_intercepted_l01(vcpu, MSR_IA32_PRED_CMD))
649                 nested_vmx_disable_intercept_for_msr(
650                                         msr_bitmap_l1, msr_bitmap_l0,
651                                         MSR_IA32_PRED_CMD,
652                                         MSR_TYPE_W);
653
654         kvm_vcpu_unmap(vcpu, &to_vmx(vcpu)->nested.msr_bitmap_map, false);
655
656         return true;
657 }
658
659 static void nested_cache_shadow_vmcs12(struct kvm_vcpu *vcpu,
660                                        struct vmcs12 *vmcs12)
661 {
662         struct kvm_host_map map;
663         struct vmcs12 *shadow;
664
665         if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
666             vmcs12->vmcs_link_pointer == -1ull)
667                 return;
668
669         shadow = get_shadow_vmcs12(vcpu);
670
671         if (kvm_vcpu_map(vcpu, gpa_to_gfn(vmcs12->vmcs_link_pointer), &map))
672                 return;
673
674         memcpy(shadow, map.hva, VMCS12_SIZE);
675         kvm_vcpu_unmap(vcpu, &map, false);
676 }
677
678 static void nested_flush_cached_shadow_vmcs12(struct kvm_vcpu *vcpu,
679                                               struct vmcs12 *vmcs12)
680 {
681         struct vcpu_vmx *vmx = to_vmx(vcpu);
682
683         if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
684             vmcs12->vmcs_link_pointer == -1ull)
685                 return;
686
687         kvm_write_guest(vmx->vcpu.kvm, vmcs12->vmcs_link_pointer,
688                         get_shadow_vmcs12(vcpu), VMCS12_SIZE);
689 }
690
691 /*
692  * In nested virtualization, check if L1 has set
693  * VM_EXIT_ACK_INTR_ON_EXIT
694  */
695 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
696 {
697         return get_vmcs12(vcpu)->vm_exit_controls &
698                 VM_EXIT_ACK_INTR_ON_EXIT;
699 }
700
701 static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
702 {
703         return nested_cpu_has_nmi_exiting(get_vmcs12(vcpu));
704 }
705
706 static int nested_vmx_check_apic_access_controls(struct kvm_vcpu *vcpu,
707                                           struct vmcs12 *vmcs12)
708 {
709         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
710             CC(!page_address_valid(vcpu, vmcs12->apic_access_addr)))
711                 return -EINVAL;
712         else
713                 return 0;
714 }
715
716 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
717                                            struct vmcs12 *vmcs12)
718 {
719         if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
720             !nested_cpu_has_apic_reg_virt(vmcs12) &&
721             !nested_cpu_has_vid(vmcs12) &&
722             !nested_cpu_has_posted_intr(vmcs12))
723                 return 0;
724
725         /*
726          * If virtualize x2apic mode is enabled,
727          * virtualize apic access must be disabled.
728          */
729         if (CC(nested_cpu_has_virt_x2apic_mode(vmcs12) &&
730                nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)))
731                 return -EINVAL;
732
733         /*
734          * If virtual interrupt delivery is enabled,
735          * we must exit on external interrupts.
736          */
737         if (CC(nested_cpu_has_vid(vmcs12) && !nested_exit_on_intr(vcpu)))
738                 return -EINVAL;
739
740         /*
741          * bits 15:8 should be zero in posted_intr_nv,
742          * the descriptor address has been already checked
743          * in nested_get_vmcs12_pages.
744          *
745          * bits 5:0 of posted_intr_desc_addr should be zero.
746          */
747         if (nested_cpu_has_posted_intr(vmcs12) &&
748            (CC(!nested_cpu_has_vid(vmcs12)) ||
749             CC(!nested_exit_intr_ack_set(vcpu)) ||
750             CC((vmcs12->posted_intr_nv & 0xff00)) ||
751             CC((vmcs12->posted_intr_desc_addr & 0x3f)) ||
752             CC((vmcs12->posted_intr_desc_addr >> cpuid_maxphyaddr(vcpu)))))
753                 return -EINVAL;
754
755         /* tpr shadow is needed by all apicv features. */
756         if (CC(!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)))
757                 return -EINVAL;
758
759         return 0;
760 }
761
762 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
763                                        u32 count, u64 addr)
764 {
765         int maxphyaddr;
766
767         if (count == 0)
768                 return 0;
769         maxphyaddr = cpuid_maxphyaddr(vcpu);
770         if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
771             (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr)
772                 return -EINVAL;
773
774         return 0;
775 }
776
777 static int nested_vmx_check_exit_msr_switch_controls(struct kvm_vcpu *vcpu,
778                                                      struct vmcs12 *vmcs12)
779 {
780         if (CC(nested_vmx_check_msr_switch(vcpu,
781                                            vmcs12->vm_exit_msr_load_count,
782                                            vmcs12->vm_exit_msr_load_addr)) ||
783             CC(nested_vmx_check_msr_switch(vcpu,
784                                            vmcs12->vm_exit_msr_store_count,
785                                            vmcs12->vm_exit_msr_store_addr)))
786                 return -EINVAL;
787
788         return 0;
789 }
790
791 static int nested_vmx_check_entry_msr_switch_controls(struct kvm_vcpu *vcpu,
792                                                       struct vmcs12 *vmcs12)
793 {
794         if (CC(nested_vmx_check_msr_switch(vcpu,
795                                            vmcs12->vm_entry_msr_load_count,
796                                            vmcs12->vm_entry_msr_load_addr)))
797                 return -EINVAL;
798
799         return 0;
800 }
801
802 static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
803                                          struct vmcs12 *vmcs12)
804 {
805         if (!nested_cpu_has_pml(vmcs12))
806                 return 0;
807
808         if (CC(!nested_cpu_has_ept(vmcs12)) ||
809             CC(!page_address_valid(vcpu, vmcs12->pml_address)))
810                 return -EINVAL;
811
812         return 0;
813 }
814
815 static int nested_vmx_check_unrestricted_guest_controls(struct kvm_vcpu *vcpu,
816                                                         struct vmcs12 *vmcs12)
817 {
818         if (CC(nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST) &&
819                !nested_cpu_has_ept(vmcs12)))
820                 return -EINVAL;
821         return 0;
822 }
823
824 static int nested_vmx_check_mode_based_ept_exec_controls(struct kvm_vcpu *vcpu,
825                                                          struct vmcs12 *vmcs12)
826 {
827         if (CC(nested_cpu_has2(vmcs12, SECONDARY_EXEC_MODE_BASED_EPT_EXEC) &&
828                !nested_cpu_has_ept(vmcs12)))
829                 return -EINVAL;
830         return 0;
831 }
832
833 static int nested_vmx_check_shadow_vmcs_controls(struct kvm_vcpu *vcpu,
834                                                  struct vmcs12 *vmcs12)
835 {
836         if (!nested_cpu_has_shadow_vmcs(vmcs12))
837                 return 0;
838
839         if (CC(!page_address_valid(vcpu, vmcs12->vmread_bitmap)) ||
840             CC(!page_address_valid(vcpu, vmcs12->vmwrite_bitmap)))
841                 return -EINVAL;
842
843         return 0;
844 }
845
846 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
847                                        struct vmx_msr_entry *e)
848 {
849         /* x2APIC MSR accesses are not allowed */
850         if (CC(vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8))
851                 return -EINVAL;
852         if (CC(e->index == MSR_IA32_UCODE_WRITE) || /* SDM Table 35-2 */
853             CC(e->index == MSR_IA32_UCODE_REV))
854                 return -EINVAL;
855         if (CC(e->reserved != 0))
856                 return -EINVAL;
857         return 0;
858 }
859
860 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
861                                      struct vmx_msr_entry *e)
862 {
863         if (CC(e->index == MSR_FS_BASE) ||
864             CC(e->index == MSR_GS_BASE) ||
865             CC(e->index == MSR_IA32_SMM_MONITOR_CTL) || /* SMM is not supported */
866             nested_vmx_msr_check_common(vcpu, e))
867                 return -EINVAL;
868         return 0;
869 }
870
871 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
872                                       struct vmx_msr_entry *e)
873 {
874         if (CC(e->index == MSR_IA32_SMBASE) || /* SMM is not supported */
875             nested_vmx_msr_check_common(vcpu, e))
876                 return -EINVAL;
877         return 0;
878 }
879
880 static u32 nested_vmx_max_atomic_switch_msrs(struct kvm_vcpu *vcpu)
881 {
882         struct vcpu_vmx *vmx = to_vmx(vcpu);
883         u64 vmx_misc = vmx_control_msr(vmx->nested.msrs.misc_low,
884                                        vmx->nested.msrs.misc_high);
885
886         return (vmx_misc_max_msr(vmx_misc) + 1) * VMX_MISC_MSR_LIST_MULTIPLIER;
887 }
888
889 /*
890  * Load guest's/host's msr at nested entry/exit.
891  * return 0 for success, entry index for failure.
892  *
893  * One of the failure modes for MSR load/store is when a list exceeds the
894  * virtual hardware's capacity. To maintain compatibility with hardware inasmuch
895  * as possible, process all valid entries before failing rather than precheck
896  * for a capacity violation.
897  */
898 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
899 {
900         u32 i;
901         struct vmx_msr_entry e;
902         u32 max_msr_list_size = nested_vmx_max_atomic_switch_msrs(vcpu);
903
904         for (i = 0; i < count; i++) {
905                 if (unlikely(i >= max_msr_list_size))
906                         goto fail;
907
908                 if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
909                                         &e, sizeof(e))) {
910                         pr_debug_ratelimited(
911                                 "%s cannot read MSR entry (%u, 0x%08llx)\n",
912                                 __func__, i, gpa + i * sizeof(e));
913                         goto fail;
914                 }
915                 if (nested_vmx_load_msr_check(vcpu, &e)) {
916                         pr_debug_ratelimited(
917                                 "%s check failed (%u, 0x%x, 0x%x)\n",
918                                 __func__, i, e.index, e.reserved);
919                         goto fail;
920                 }
921                 if (kvm_set_msr(vcpu, e.index, e.value)) {
922                         pr_debug_ratelimited(
923                                 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
924                                 __func__, i, e.index, e.value);
925                         goto fail;
926                 }
927         }
928         return 0;
929 fail:
930         return i + 1;
931 }
932
933 static bool nested_vmx_get_vmexit_msr_value(struct kvm_vcpu *vcpu,
934                                             u32 msr_index,
935                                             u64 *data)
936 {
937         struct vcpu_vmx *vmx = to_vmx(vcpu);
938
939         /*
940          * If the L0 hypervisor stored a more accurate value for the TSC that
941          * does not include the time taken for emulation of the L2->L1
942          * VM-exit in L0, use the more accurate value.
943          */
944         if (msr_index == MSR_IA32_TSC) {
945                 int index = vmx_find_msr_index(&vmx->msr_autostore.guest,
946                                                MSR_IA32_TSC);
947
948                 if (index >= 0) {
949                         u64 val = vmx->msr_autostore.guest.val[index].value;
950
951                         *data = kvm_read_l1_tsc(vcpu, val);
952                         return true;
953                 }
954         }
955
956         if (kvm_get_msr(vcpu, msr_index, data)) {
957                 pr_debug_ratelimited("%s cannot read MSR (0x%x)\n", __func__,
958                         msr_index);
959                 return false;
960         }
961         return true;
962 }
963
964 static bool read_and_check_msr_entry(struct kvm_vcpu *vcpu, u64 gpa, int i,
965                                      struct vmx_msr_entry *e)
966 {
967         if (kvm_vcpu_read_guest(vcpu,
968                                 gpa + i * sizeof(*e),
969                                 e, 2 * sizeof(u32))) {
970                 pr_debug_ratelimited(
971                         "%s cannot read MSR entry (%u, 0x%08llx)\n",
972                         __func__, i, gpa + i * sizeof(*e));
973                 return false;
974         }
975         if (nested_vmx_store_msr_check(vcpu, e)) {
976                 pr_debug_ratelimited(
977                         "%s check failed (%u, 0x%x, 0x%x)\n",
978                         __func__, i, e->index, e->reserved);
979                 return false;
980         }
981         return true;
982 }
983
984 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
985 {
986         u64 data;
987         u32 i;
988         struct vmx_msr_entry e;
989         u32 max_msr_list_size = nested_vmx_max_atomic_switch_msrs(vcpu);
990
991         for (i = 0; i < count; i++) {
992                 if (unlikely(i >= max_msr_list_size))
993                         return -EINVAL;
994
995                 if (!read_and_check_msr_entry(vcpu, gpa, i, &e))
996                         return -EINVAL;
997
998                 if (!nested_vmx_get_vmexit_msr_value(vcpu, e.index, &data))
999                         return -EINVAL;
1000
1001                 if (kvm_vcpu_write_guest(vcpu,
1002                                          gpa + i * sizeof(e) +
1003                                              offsetof(struct vmx_msr_entry, value),
1004                                          &data, sizeof(data))) {
1005                         pr_debug_ratelimited(
1006                                 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
1007                                 __func__, i, e.index, data);
1008                         return -EINVAL;
1009                 }
1010         }
1011         return 0;
1012 }
1013
1014 static bool nested_msr_store_list_has_msr(struct kvm_vcpu *vcpu, u32 msr_index)
1015 {
1016         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1017         u32 count = vmcs12->vm_exit_msr_store_count;
1018         u64 gpa = vmcs12->vm_exit_msr_store_addr;
1019         struct vmx_msr_entry e;
1020         u32 i;
1021
1022         for (i = 0; i < count; i++) {
1023                 if (!read_and_check_msr_entry(vcpu, gpa, i, &e))
1024                         return false;
1025
1026                 if (e.index == msr_index)
1027                         return true;
1028         }
1029         return false;
1030 }
1031
1032 static void prepare_vmx_msr_autostore_list(struct kvm_vcpu *vcpu,
1033                                            u32 msr_index)
1034 {
1035         struct vcpu_vmx *vmx = to_vmx(vcpu);
1036         struct vmx_msrs *autostore = &vmx->msr_autostore.guest;
1037         bool in_vmcs12_store_list;
1038         int msr_autostore_index;
1039         bool in_autostore_list;
1040         int last;
1041
1042         msr_autostore_index = vmx_find_msr_index(autostore, msr_index);
1043         in_autostore_list = msr_autostore_index >= 0;
1044         in_vmcs12_store_list = nested_msr_store_list_has_msr(vcpu, msr_index);
1045
1046         if (in_vmcs12_store_list && !in_autostore_list) {
1047                 if (autostore->nr == NR_LOADSTORE_MSRS) {
1048                         /*
1049                          * Emulated VMEntry does not fail here.  Instead a less
1050                          * accurate value will be returned by
1051                          * nested_vmx_get_vmexit_msr_value() using kvm_get_msr()
1052                          * instead of reading the value from the vmcs02 VMExit
1053                          * MSR-store area.
1054                          */
1055                         pr_warn_ratelimited(
1056                                 "Not enough msr entries in msr_autostore.  Can't add msr %x\n",
1057                                 msr_index);
1058                         return;
1059                 }
1060                 last = autostore->nr++;
1061                 autostore->val[last].index = msr_index;
1062         } else if (!in_vmcs12_store_list && in_autostore_list) {
1063                 last = --autostore->nr;
1064                 autostore->val[msr_autostore_index] = autostore->val[last];
1065         }
1066 }
1067
1068 static bool nested_cr3_valid(struct kvm_vcpu *vcpu, unsigned long val)
1069 {
1070         unsigned long invalid_mask;
1071
1072         invalid_mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
1073         return (val & invalid_mask) == 0;
1074 }
1075
1076 /*
1077  * Returns true if the MMU needs to be sync'd on nested VM-Enter/VM-Exit.
1078  * tl;dr: the MMU needs a sync if L0 is using shadow paging and L1 didn't
1079  * enable VPID for L2 (implying it expects a TLB flush on VMX transitions).
1080  * Here's why.
1081  *
1082  * If EPT is enabled by L0 a sync is never needed:
1083  * - if it is disabled by L1, then L0 is not shadowing L1 or L2 PTEs, there
1084  *   cannot be unsync'd SPTEs for either L1 or L2.
1085  *
1086  * - if it is also enabled by L1, then L0 doesn't need to sync on VM-Enter
1087  *   VM-Enter as VM-Enter isn't required to invalidate guest-physical mappings
1088  *   (irrespective of VPID), i.e. L1 can't rely on the (virtual) CPU to flush
1089  *   stale guest-physical mappings for L2 from the TLB.  And as above, L0 isn't
1090  *   shadowing L1 PTEs so there are no unsync'd SPTEs to sync on VM-Exit.
1091  *
1092  * If EPT is disabled by L0:
1093  * - if VPID is enabled by L1 (for L2), the situation is similar to when L1
1094  *   enables EPT: L0 doesn't need to sync as VM-Enter and VM-Exit aren't
1095  *   required to invalidate linear mappings (EPT is disabled so there are
1096  *   no combined or guest-physical mappings), i.e. L1 can't rely on the
1097  *   (virtual) CPU to flush stale linear mappings for either L2 or itself (L1).
1098  *
1099  * - however if VPID is disabled by L1, then a sync is needed as L1 expects all
1100  *   linear mappings (EPT is disabled so there are no combined or guest-physical
1101  *   mappings) to be invalidated on both VM-Enter and VM-Exit.
1102  *
1103  * Note, this logic is subtly different than nested_has_guest_tlb_tag(), which
1104  * additionally checks that L2 has been assigned a VPID (when EPT is disabled).
1105  * Whether or not L2 has been assigned a VPID by L0 is irrelevant with respect
1106  * to L1's expectations, e.g. L0 needs to invalidate hardware TLB entries if L2
1107  * doesn't have a unique VPID to prevent reusing L1's entries (assuming L1 has
1108  * been assigned a VPID), but L0 doesn't need to do a MMU sync because L1
1109  * doesn't expect stale (virtual) TLB entries to be flushed, i.e. L1 doesn't
1110  * know that L0 will flush the TLB and so L1 will do INVVPID as needed to flush
1111  * stale TLB entries, at which point L0 will sync L2's MMU.
1112  */
1113 static bool nested_vmx_transition_mmu_sync(struct kvm_vcpu *vcpu)
1114 {
1115         return !enable_ept && !nested_cpu_has_vpid(get_vmcs12(vcpu));
1116 }
1117
1118 /*
1119  * Load guest's/host's cr3 at nested entry/exit.  @nested_ept is true if we are
1120  * emulating VM-Entry into a guest with EPT enabled.  On failure, the expected
1121  * Exit Qualification (for a VM-Entry consistency check VM-Exit) is assigned to
1122  * @entry_failure_code.
1123  */
1124 static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool nested_ept,
1125                                u32 *entry_failure_code)
1126 {
1127         if (cr3 != kvm_read_cr3(vcpu) || (!nested_ept && pdptrs_changed(vcpu))) {
1128                 if (CC(!nested_cr3_valid(vcpu, cr3))) {
1129                         *entry_failure_code = ENTRY_FAIL_DEFAULT;
1130                         return -EINVAL;
1131                 }
1132
1133                 /*
1134                  * If PAE paging and EPT are both on, CR3 is not used by the CPU and
1135                  * must not be dereferenced.
1136                  */
1137                 if (is_pae_paging(vcpu) && !nested_ept) {
1138                         if (CC(!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))) {
1139                                 *entry_failure_code = ENTRY_FAIL_PDPTE;
1140                                 return -EINVAL;
1141                         }
1142                 }
1143         }
1144
1145         /*
1146          * Unconditionally skip the TLB flush on fast CR3 switch, all TLB
1147          * flushes are handled by nested_vmx_transition_tlb_flush().  See
1148          * nested_vmx_transition_mmu_sync for details on skipping the MMU sync.
1149          */
1150         if (!nested_ept)
1151                 kvm_mmu_new_pgd(vcpu, cr3, true,
1152                                 !nested_vmx_transition_mmu_sync(vcpu));
1153
1154         vcpu->arch.cr3 = cr3;
1155         kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
1156
1157         kvm_init_mmu(vcpu, false);
1158
1159         return 0;
1160 }
1161
1162 /*
1163  * Returns if KVM is able to config CPU to tag TLB entries
1164  * populated by L2 differently than TLB entries populated
1165  * by L1.
1166  *
1167  * If L0 uses EPT, L1 and L2 run with different EPTP because
1168  * guest_mode is part of kvm_mmu_page_role. Thus, TLB entries
1169  * are tagged with different EPTP.
1170  *
1171  * If L1 uses VPID and we allocated a vpid02, TLB entries are tagged
1172  * with different VPID (L1 entries are tagged with vmx->vpid
1173  * while L2 entries are tagged with vmx->nested.vpid02).
1174  */
1175 static bool nested_has_guest_tlb_tag(struct kvm_vcpu *vcpu)
1176 {
1177         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1178
1179         return enable_ept ||
1180                (nested_cpu_has_vpid(vmcs12) && to_vmx(vcpu)->nested.vpid02);
1181 }
1182
1183 static void nested_vmx_transition_tlb_flush(struct kvm_vcpu *vcpu,
1184                                             struct vmcs12 *vmcs12,
1185                                             bool is_vmenter)
1186 {
1187         struct vcpu_vmx *vmx = to_vmx(vcpu);
1188
1189         /*
1190          * If VPID is disabled, linear and combined mappings are flushed on
1191          * VM-Enter/VM-Exit, and guest-physical mappings are valid only for
1192          * their associated EPTP.
1193          */
1194         if (!enable_vpid)
1195                 return;
1196
1197         /*
1198          * If vmcs12 doesn't use VPID, L1 expects linear and combined mappings
1199          * for *all* contexts to be flushed on VM-Enter/VM-Exit.
1200          *
1201          * If VPID is enabled and used by vmc12, but L2 does not have a unique
1202          * TLB tag (ASID), i.e. EPT is disabled and KVM was unable to allocate
1203          * a VPID for L2, flush the current context as the effective ASID is
1204          * common to both L1 and L2.
1205          *
1206          * Defer the flush so that it runs after vmcs02.EPTP has been set by
1207          * KVM_REQ_LOAD_MMU_PGD (if nested EPT is enabled) and to avoid
1208          * redundant flushes further down the nested pipeline.
1209          *
1210          * If a TLB flush isn't required due to any of the above, and vpid12 is
1211          * changing then the new "virtual" VPID (vpid12) will reuse the same
1212          * "real" VPID (vpid02), and so needs to be sync'd.  There is no direct
1213          * mapping between vpid02 and vpid12, vpid02 is per-vCPU and reused for
1214          * all nested vCPUs.
1215          */
1216         if (!nested_cpu_has_vpid(vmcs12)) {
1217                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1218         } else if (!nested_has_guest_tlb_tag(vcpu)) {
1219                 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1220         } else if (is_vmenter &&
1221                    vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
1222                 vmx->nested.last_vpid = vmcs12->virtual_processor_id;
1223                 vpid_sync_context(nested_get_vpid02(vcpu));
1224         }
1225 }
1226
1227 static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
1228 {
1229         superset &= mask;
1230         subset &= mask;
1231
1232         return (superset | subset) == superset;
1233 }
1234
1235 static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
1236 {
1237         const u64 feature_and_reserved =
1238                 /* feature (except bit 48; see below) */
1239                 BIT_ULL(49) | BIT_ULL(54) | BIT_ULL(55) |
1240                 /* reserved */
1241                 BIT_ULL(31) | GENMASK_ULL(47, 45) | GENMASK_ULL(63, 56);
1242         u64 vmx_basic = vmx->nested.msrs.basic;
1243
1244         if (!is_bitwise_subset(vmx_basic, data, feature_and_reserved))
1245                 return -EINVAL;
1246
1247         /*
1248          * KVM does not emulate a version of VMX that constrains physical
1249          * addresses of VMX structures (e.g. VMCS) to 32-bits.
1250          */
1251         if (data & BIT_ULL(48))
1252                 return -EINVAL;
1253
1254         if (vmx_basic_vmcs_revision_id(vmx_basic) !=
1255             vmx_basic_vmcs_revision_id(data))
1256                 return -EINVAL;
1257
1258         if (vmx_basic_vmcs_size(vmx_basic) > vmx_basic_vmcs_size(data))
1259                 return -EINVAL;
1260
1261         vmx->nested.msrs.basic = data;
1262         return 0;
1263 }
1264
1265 static int
1266 vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
1267 {
1268         u64 supported;
1269         u32 *lowp, *highp;
1270
1271         switch (msr_index) {
1272         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
1273                 lowp = &vmx->nested.msrs.pinbased_ctls_low;
1274                 highp = &vmx->nested.msrs.pinbased_ctls_high;
1275                 break;
1276         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
1277                 lowp = &vmx->nested.msrs.procbased_ctls_low;
1278                 highp = &vmx->nested.msrs.procbased_ctls_high;
1279                 break;
1280         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
1281                 lowp = &vmx->nested.msrs.exit_ctls_low;
1282                 highp = &vmx->nested.msrs.exit_ctls_high;
1283                 break;
1284         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
1285                 lowp = &vmx->nested.msrs.entry_ctls_low;
1286                 highp = &vmx->nested.msrs.entry_ctls_high;
1287                 break;
1288         case MSR_IA32_VMX_PROCBASED_CTLS2:
1289                 lowp = &vmx->nested.msrs.secondary_ctls_low;
1290                 highp = &vmx->nested.msrs.secondary_ctls_high;
1291                 break;
1292         default:
1293                 BUG();
1294         }
1295
1296         supported = vmx_control_msr(*lowp, *highp);
1297
1298         /* Check must-be-1 bits are still 1. */
1299         if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0)))
1300                 return -EINVAL;
1301
1302         /* Check must-be-0 bits are still 0. */
1303         if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32)))
1304                 return -EINVAL;
1305
1306         *lowp = data;
1307         *highp = data >> 32;
1308         return 0;
1309 }
1310
1311 static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
1312 {
1313         const u64 feature_and_reserved_bits =
1314                 /* feature */
1315                 BIT_ULL(5) | GENMASK_ULL(8, 6) | BIT_ULL(14) | BIT_ULL(15) |
1316                 BIT_ULL(28) | BIT_ULL(29) | BIT_ULL(30) |
1317                 /* reserved */
1318                 GENMASK_ULL(13, 9) | BIT_ULL(31);
1319         u64 vmx_misc;
1320
1321         vmx_misc = vmx_control_msr(vmx->nested.msrs.misc_low,
1322                                    vmx->nested.msrs.misc_high);
1323
1324         if (!is_bitwise_subset(vmx_misc, data, feature_and_reserved_bits))
1325                 return -EINVAL;
1326
1327         if ((vmx->nested.msrs.pinbased_ctls_high &
1328              PIN_BASED_VMX_PREEMPTION_TIMER) &&
1329             vmx_misc_preemption_timer_rate(data) !=
1330             vmx_misc_preemption_timer_rate(vmx_misc))
1331                 return -EINVAL;
1332
1333         if (vmx_misc_cr3_count(data) > vmx_misc_cr3_count(vmx_misc))
1334                 return -EINVAL;
1335
1336         if (vmx_misc_max_msr(data) > vmx_misc_max_msr(vmx_misc))
1337                 return -EINVAL;
1338
1339         if (vmx_misc_mseg_revid(data) != vmx_misc_mseg_revid(vmx_misc))
1340                 return -EINVAL;
1341
1342         vmx->nested.msrs.misc_low = data;
1343         vmx->nested.msrs.misc_high = data >> 32;
1344
1345         return 0;
1346 }
1347
1348 static int vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx *vmx, u64 data)
1349 {
1350         u64 vmx_ept_vpid_cap;
1351
1352         vmx_ept_vpid_cap = vmx_control_msr(vmx->nested.msrs.ept_caps,
1353                                            vmx->nested.msrs.vpid_caps);
1354
1355         /* Every bit is either reserved or a feature bit. */
1356         if (!is_bitwise_subset(vmx_ept_vpid_cap, data, -1ULL))
1357                 return -EINVAL;
1358
1359         vmx->nested.msrs.ept_caps = data;
1360         vmx->nested.msrs.vpid_caps = data >> 32;
1361         return 0;
1362 }
1363
1364 static int vmx_restore_fixed0_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
1365 {
1366         u64 *msr;
1367
1368         switch (msr_index) {
1369         case MSR_IA32_VMX_CR0_FIXED0:
1370                 msr = &vmx->nested.msrs.cr0_fixed0;
1371                 break;
1372         case MSR_IA32_VMX_CR4_FIXED0:
1373                 msr = &vmx->nested.msrs.cr4_fixed0;
1374                 break;
1375         default:
1376                 BUG();
1377         }
1378
1379         /*
1380          * 1 bits (which indicates bits which "must-be-1" during VMX operation)
1381          * must be 1 in the restored value.
1382          */
1383         if (!is_bitwise_subset(data, *msr, -1ULL))
1384                 return -EINVAL;
1385
1386         *msr = data;
1387         return 0;
1388 }
1389
1390 /*
1391  * Called when userspace is restoring VMX MSRs.
1392  *
1393  * Returns 0 on success, non-0 otherwise.
1394  */
1395 int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
1396 {
1397         struct vcpu_vmx *vmx = to_vmx(vcpu);
1398
1399         /*
1400          * Don't allow changes to the VMX capability MSRs while the vCPU
1401          * is in VMX operation.
1402          */
1403         if (vmx->nested.vmxon)
1404                 return -EBUSY;
1405
1406         switch (msr_index) {
1407         case MSR_IA32_VMX_BASIC:
1408                 return vmx_restore_vmx_basic(vmx, data);
1409         case MSR_IA32_VMX_PINBASED_CTLS:
1410         case MSR_IA32_VMX_PROCBASED_CTLS:
1411         case MSR_IA32_VMX_EXIT_CTLS:
1412         case MSR_IA32_VMX_ENTRY_CTLS:
1413                 /*
1414                  * The "non-true" VMX capability MSRs are generated from the
1415                  * "true" MSRs, so we do not support restoring them directly.
1416                  *
1417                  * If userspace wants to emulate VMX_BASIC[55]=0, userspace
1418                  * should restore the "true" MSRs with the must-be-1 bits
1419                  * set according to the SDM Vol 3. A.2 "RESERVED CONTROLS AND
1420                  * DEFAULT SETTINGS".
1421                  */
1422                 return -EINVAL;
1423         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
1424         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
1425         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
1426         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
1427         case MSR_IA32_VMX_PROCBASED_CTLS2:
1428                 return vmx_restore_control_msr(vmx, msr_index, data);
1429         case MSR_IA32_VMX_MISC:
1430                 return vmx_restore_vmx_misc(vmx, data);
1431         case MSR_IA32_VMX_CR0_FIXED0:
1432         case MSR_IA32_VMX_CR4_FIXED0:
1433                 return vmx_restore_fixed0_msr(vmx, msr_index, data);
1434         case MSR_IA32_VMX_CR0_FIXED1:
1435         case MSR_IA32_VMX_CR4_FIXED1:
1436                 /*
1437                  * These MSRs are generated based on the vCPU's CPUID, so we
1438                  * do not support restoring them directly.
1439                  */
1440                 return -EINVAL;
1441         case MSR_IA32_VMX_EPT_VPID_CAP:
1442                 return vmx_restore_vmx_ept_vpid_cap(vmx, data);
1443         case MSR_IA32_VMX_VMCS_ENUM:
1444                 vmx->nested.msrs.vmcs_enum = data;
1445                 return 0;
1446         case MSR_IA32_VMX_VMFUNC:
1447                 if (data & ~vmx->nested.msrs.vmfunc_controls)
1448                         return -EINVAL;
1449                 vmx->nested.msrs.vmfunc_controls = data;
1450                 return 0;
1451         default:
1452                 /*
1453                  * The rest of the VMX capability MSRs do not support restore.
1454                  */
1455                 return -EINVAL;
1456         }
1457 }
1458
1459 /* Returns 0 on success, non-0 otherwise. */
1460 int vmx_get_vmx_msr(struct nested_vmx_msrs *msrs, u32 msr_index, u64 *pdata)
1461 {
1462         switch (msr_index) {
1463         case MSR_IA32_VMX_BASIC:
1464                 *pdata = msrs->basic;
1465                 break;
1466         case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
1467         case MSR_IA32_VMX_PINBASED_CTLS:
1468                 *pdata = vmx_control_msr(
1469                         msrs->pinbased_ctls_low,
1470                         msrs->pinbased_ctls_high);
1471                 if (msr_index == MSR_IA32_VMX_PINBASED_CTLS)
1472                         *pdata |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
1473                 break;
1474         case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
1475         case MSR_IA32_VMX_PROCBASED_CTLS:
1476                 *pdata = vmx_control_msr(
1477                         msrs->procbased_ctls_low,
1478                         msrs->procbased_ctls_high);
1479                 if (msr_index == MSR_IA32_VMX_PROCBASED_CTLS)
1480                         *pdata |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
1481                 break;
1482         case MSR_IA32_VMX_TRUE_EXIT_CTLS:
1483         case MSR_IA32_VMX_EXIT_CTLS:
1484                 *pdata = vmx_control_msr(
1485                         msrs->exit_ctls_low,
1486                         msrs->exit_ctls_high);
1487                 if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
1488                         *pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
1489                 break;
1490         case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
1491         case MSR_IA32_VMX_ENTRY_CTLS:
1492                 *pdata = vmx_control_msr(
1493                         msrs->entry_ctls_low,
1494                         msrs->entry_ctls_high);
1495                 if (msr_index == MSR_IA32_VMX_ENTRY_CTLS)
1496                         *pdata |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
1497                 break;
1498         case MSR_IA32_VMX_MISC:
1499                 *pdata = vmx_control_msr(
1500                         msrs->misc_low,
1501                         msrs->misc_high);
1502                 break;
1503         case MSR_IA32_VMX_CR0_FIXED0:
1504                 *pdata = msrs->cr0_fixed0;
1505                 break;
1506         case MSR_IA32_VMX_CR0_FIXED1:
1507                 *pdata = msrs->cr0_fixed1;
1508                 break;
1509         case MSR_IA32_VMX_CR4_FIXED0:
1510                 *pdata = msrs->cr4_fixed0;
1511                 break;
1512         case MSR_IA32_VMX_CR4_FIXED1:
1513                 *pdata = msrs->cr4_fixed1;
1514                 break;
1515         case MSR_IA32_VMX_VMCS_ENUM:
1516                 *pdata = msrs->vmcs_enum;
1517                 break;
1518         case MSR_IA32_VMX_PROCBASED_CTLS2:
1519                 *pdata = vmx_control_msr(
1520                         msrs->secondary_ctls_low,
1521                         msrs->secondary_ctls_high);
1522                 break;
1523         case MSR_IA32_VMX_EPT_VPID_CAP:
1524                 *pdata = msrs->ept_caps |
1525                         ((u64)msrs->vpid_caps << 32);
1526                 break;
1527         case MSR_IA32_VMX_VMFUNC:
1528                 *pdata = msrs->vmfunc_controls;
1529                 break;
1530         default:
1531                 return 1;
1532         }
1533
1534         return 0;
1535 }
1536
1537 /*
1538  * Copy the writable VMCS shadow fields back to the VMCS12, in case they have
1539  * been modified by the L1 guest.  Note, "writable" in this context means
1540  * "writable by the guest", i.e. tagged SHADOW_FIELD_RW; the set of
1541  * fields tagged SHADOW_FIELD_RO may or may not align with the "read-only"
1542  * VM-exit information fields (which are actually writable if the vCPU is
1543  * configured to support "VMWRITE to any supported field in the VMCS").
1544  */
1545 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
1546 {
1547         struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
1548         struct vmcs12 *vmcs12 = get_vmcs12(&vmx->vcpu);
1549         struct shadow_vmcs_field field;
1550         unsigned long val;
1551         int i;
1552
1553         if (WARN_ON(!shadow_vmcs))
1554                 return;
1555
1556         preempt_disable();
1557
1558         vmcs_load(shadow_vmcs);
1559
1560         for (i = 0; i < max_shadow_read_write_fields; i++) {
1561                 field = shadow_read_write_fields[i];
1562                 val = __vmcs_readl(field.encoding);
1563                 vmcs12_write_any(vmcs12, field.encoding, field.offset, val);
1564         }
1565
1566         vmcs_clear(shadow_vmcs);
1567         vmcs_load(vmx->loaded_vmcs->vmcs);
1568
1569         preempt_enable();
1570 }
1571
1572 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
1573 {
1574         const struct shadow_vmcs_field *fields[] = {
1575                 shadow_read_write_fields,
1576                 shadow_read_only_fields
1577         };
1578         const int max_fields[] = {
1579                 max_shadow_read_write_fields,
1580                 max_shadow_read_only_fields
1581         };
1582         struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
1583         struct vmcs12 *vmcs12 = get_vmcs12(&vmx->vcpu);
1584         struct shadow_vmcs_field field;
1585         unsigned long val;
1586         int i, q;
1587
1588         if (WARN_ON(!shadow_vmcs))
1589                 return;
1590
1591         vmcs_load(shadow_vmcs);
1592
1593         for (q = 0; q < ARRAY_SIZE(fields); q++) {
1594                 for (i = 0; i < max_fields[q]; i++) {
1595                         field = fields[q][i];
1596                         val = vmcs12_read_any(vmcs12, field.encoding,
1597                                               field.offset);
1598                         __vmcs_writel(field.encoding, val);
1599                 }
1600         }
1601
1602         vmcs_clear(shadow_vmcs);
1603         vmcs_load(vmx->loaded_vmcs->vmcs);
1604 }
1605
1606 static int copy_enlightened_to_vmcs12(struct vcpu_vmx *vmx)
1607 {
1608         struct vmcs12 *vmcs12 = vmx->nested.cached_vmcs12;
1609         struct hv_enlightened_vmcs *evmcs = vmx->nested.hv_evmcs;
1610
1611         /* HV_VMX_ENLIGHTENED_CLEAN_FIELD_NONE */
1612         vmcs12->tpr_threshold = evmcs->tpr_threshold;
1613         vmcs12->guest_rip = evmcs->guest_rip;
1614
1615         if (unlikely(!(evmcs->hv_clean_fields &
1616                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_BASIC))) {
1617                 vmcs12->guest_rsp = evmcs->guest_rsp;
1618                 vmcs12->guest_rflags = evmcs->guest_rflags;
1619                 vmcs12->guest_interruptibility_info =
1620                         evmcs->guest_interruptibility_info;
1621         }
1622
1623         if (unlikely(!(evmcs->hv_clean_fields &
1624                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_PROC))) {
1625                 vmcs12->cpu_based_vm_exec_control =
1626                         evmcs->cpu_based_vm_exec_control;
1627         }
1628
1629         if (unlikely(!(evmcs->hv_clean_fields &
1630                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_EXCPN))) {
1631                 vmcs12->exception_bitmap = evmcs->exception_bitmap;
1632         }
1633
1634         if (unlikely(!(evmcs->hv_clean_fields &
1635                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_ENTRY))) {
1636                 vmcs12->vm_entry_controls = evmcs->vm_entry_controls;
1637         }
1638
1639         if (unlikely(!(evmcs->hv_clean_fields &
1640                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_EVENT))) {
1641                 vmcs12->vm_entry_intr_info_field =
1642                         evmcs->vm_entry_intr_info_field;
1643                 vmcs12->vm_entry_exception_error_code =
1644                         evmcs->vm_entry_exception_error_code;
1645                 vmcs12->vm_entry_instruction_len =
1646                         evmcs->vm_entry_instruction_len;
1647         }
1648
1649         if (unlikely(!(evmcs->hv_clean_fields &
1650                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_HOST_GRP1))) {
1651                 vmcs12->host_ia32_pat = evmcs->host_ia32_pat;
1652                 vmcs12->host_ia32_efer = evmcs->host_ia32_efer;
1653                 vmcs12->host_cr0 = evmcs->host_cr0;
1654                 vmcs12->host_cr3 = evmcs->host_cr3;
1655                 vmcs12->host_cr4 = evmcs->host_cr4;
1656                 vmcs12->host_ia32_sysenter_esp = evmcs->host_ia32_sysenter_esp;
1657                 vmcs12->host_ia32_sysenter_eip = evmcs->host_ia32_sysenter_eip;
1658                 vmcs12->host_rip = evmcs->host_rip;
1659                 vmcs12->host_ia32_sysenter_cs = evmcs->host_ia32_sysenter_cs;
1660                 vmcs12->host_es_selector = evmcs->host_es_selector;
1661                 vmcs12->host_cs_selector = evmcs->host_cs_selector;
1662                 vmcs12->host_ss_selector = evmcs->host_ss_selector;
1663                 vmcs12->host_ds_selector = evmcs->host_ds_selector;
1664                 vmcs12->host_fs_selector = evmcs->host_fs_selector;
1665                 vmcs12->host_gs_selector = evmcs->host_gs_selector;
1666                 vmcs12->host_tr_selector = evmcs->host_tr_selector;
1667         }
1668
1669         if (unlikely(!(evmcs->hv_clean_fields &
1670                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_GRP1))) {
1671                 vmcs12->pin_based_vm_exec_control =
1672                         evmcs->pin_based_vm_exec_control;
1673                 vmcs12->vm_exit_controls = evmcs->vm_exit_controls;
1674                 vmcs12->secondary_vm_exec_control =
1675                         evmcs->secondary_vm_exec_control;
1676         }
1677
1678         if (unlikely(!(evmcs->hv_clean_fields &
1679                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_IO_BITMAP))) {
1680                 vmcs12->io_bitmap_a = evmcs->io_bitmap_a;
1681                 vmcs12->io_bitmap_b = evmcs->io_bitmap_b;
1682         }
1683
1684         if (unlikely(!(evmcs->hv_clean_fields &
1685                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP))) {
1686                 vmcs12->msr_bitmap = evmcs->msr_bitmap;
1687         }
1688
1689         if (unlikely(!(evmcs->hv_clean_fields &
1690                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2))) {
1691                 vmcs12->guest_es_base = evmcs->guest_es_base;
1692                 vmcs12->guest_cs_base = evmcs->guest_cs_base;
1693                 vmcs12->guest_ss_base = evmcs->guest_ss_base;
1694                 vmcs12->guest_ds_base = evmcs->guest_ds_base;
1695                 vmcs12->guest_fs_base = evmcs->guest_fs_base;
1696                 vmcs12->guest_gs_base = evmcs->guest_gs_base;
1697                 vmcs12->guest_ldtr_base = evmcs->guest_ldtr_base;
1698                 vmcs12->guest_tr_base = evmcs->guest_tr_base;
1699                 vmcs12->guest_gdtr_base = evmcs->guest_gdtr_base;
1700                 vmcs12->guest_idtr_base = evmcs->guest_idtr_base;
1701                 vmcs12->guest_es_limit = evmcs->guest_es_limit;
1702                 vmcs12->guest_cs_limit = evmcs->guest_cs_limit;
1703                 vmcs12->guest_ss_limit = evmcs->guest_ss_limit;
1704                 vmcs12->guest_ds_limit = evmcs->guest_ds_limit;
1705                 vmcs12->guest_fs_limit = evmcs->guest_fs_limit;
1706                 vmcs12->guest_gs_limit = evmcs->guest_gs_limit;
1707                 vmcs12->guest_ldtr_limit = evmcs->guest_ldtr_limit;
1708                 vmcs12->guest_tr_limit = evmcs->guest_tr_limit;
1709                 vmcs12->guest_gdtr_limit = evmcs->guest_gdtr_limit;
1710                 vmcs12->guest_idtr_limit = evmcs->guest_idtr_limit;
1711                 vmcs12->guest_es_ar_bytes = evmcs->guest_es_ar_bytes;
1712                 vmcs12->guest_cs_ar_bytes = evmcs->guest_cs_ar_bytes;
1713                 vmcs12->guest_ss_ar_bytes = evmcs->guest_ss_ar_bytes;
1714                 vmcs12->guest_ds_ar_bytes = evmcs->guest_ds_ar_bytes;
1715                 vmcs12->guest_fs_ar_bytes = evmcs->guest_fs_ar_bytes;
1716                 vmcs12->guest_gs_ar_bytes = evmcs->guest_gs_ar_bytes;
1717                 vmcs12->guest_ldtr_ar_bytes = evmcs->guest_ldtr_ar_bytes;
1718                 vmcs12->guest_tr_ar_bytes = evmcs->guest_tr_ar_bytes;
1719                 vmcs12->guest_es_selector = evmcs->guest_es_selector;
1720                 vmcs12->guest_cs_selector = evmcs->guest_cs_selector;
1721                 vmcs12->guest_ss_selector = evmcs->guest_ss_selector;
1722                 vmcs12->guest_ds_selector = evmcs->guest_ds_selector;
1723                 vmcs12->guest_fs_selector = evmcs->guest_fs_selector;
1724                 vmcs12->guest_gs_selector = evmcs->guest_gs_selector;
1725                 vmcs12->guest_ldtr_selector = evmcs->guest_ldtr_selector;
1726                 vmcs12->guest_tr_selector = evmcs->guest_tr_selector;
1727         }
1728
1729         if (unlikely(!(evmcs->hv_clean_fields &
1730                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_GRP2))) {
1731                 vmcs12->tsc_offset = evmcs->tsc_offset;
1732                 vmcs12->virtual_apic_page_addr = evmcs->virtual_apic_page_addr;
1733                 vmcs12->xss_exit_bitmap = evmcs->xss_exit_bitmap;
1734         }
1735
1736         if (unlikely(!(evmcs->hv_clean_fields &
1737                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CRDR))) {
1738                 vmcs12->cr0_guest_host_mask = evmcs->cr0_guest_host_mask;
1739                 vmcs12->cr4_guest_host_mask = evmcs->cr4_guest_host_mask;
1740                 vmcs12->cr0_read_shadow = evmcs->cr0_read_shadow;
1741                 vmcs12->cr4_read_shadow = evmcs->cr4_read_shadow;
1742                 vmcs12->guest_cr0 = evmcs->guest_cr0;
1743                 vmcs12->guest_cr3 = evmcs->guest_cr3;
1744                 vmcs12->guest_cr4 = evmcs->guest_cr4;
1745                 vmcs12->guest_dr7 = evmcs->guest_dr7;
1746         }
1747
1748         if (unlikely(!(evmcs->hv_clean_fields &
1749                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_HOST_POINTER))) {
1750                 vmcs12->host_fs_base = evmcs->host_fs_base;
1751                 vmcs12->host_gs_base = evmcs->host_gs_base;
1752                 vmcs12->host_tr_base = evmcs->host_tr_base;
1753                 vmcs12->host_gdtr_base = evmcs->host_gdtr_base;
1754                 vmcs12->host_idtr_base = evmcs->host_idtr_base;
1755                 vmcs12->host_rsp = evmcs->host_rsp;
1756         }
1757
1758         if (unlikely(!(evmcs->hv_clean_fields &
1759                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_CONTROL_XLAT))) {
1760                 vmcs12->ept_pointer = evmcs->ept_pointer;
1761                 vmcs12->virtual_processor_id = evmcs->virtual_processor_id;
1762         }
1763
1764         if (unlikely(!(evmcs->hv_clean_fields &
1765                        HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1))) {
1766                 vmcs12->vmcs_link_pointer = evmcs->vmcs_link_pointer;
1767                 vmcs12->guest_ia32_debugctl = evmcs->guest_ia32_debugctl;
1768                 vmcs12->guest_ia32_pat = evmcs->guest_ia32_pat;
1769                 vmcs12->guest_ia32_efer = evmcs->guest_ia32_efer;
1770                 vmcs12->guest_pdptr0 = evmcs->guest_pdptr0;
1771                 vmcs12->guest_pdptr1 = evmcs->guest_pdptr1;
1772                 vmcs12->guest_pdptr2 = evmcs->guest_pdptr2;
1773                 vmcs12->guest_pdptr3 = evmcs->guest_pdptr3;
1774                 vmcs12->guest_pending_dbg_exceptions =
1775                         evmcs->guest_pending_dbg_exceptions;
1776                 vmcs12->guest_sysenter_esp = evmcs->guest_sysenter_esp;
1777                 vmcs12->guest_sysenter_eip = evmcs->guest_sysenter_eip;
1778                 vmcs12->guest_bndcfgs = evmcs->guest_bndcfgs;
1779                 vmcs12->guest_activity_state = evmcs->guest_activity_state;
1780                 vmcs12->guest_sysenter_cs = evmcs->guest_sysenter_cs;
1781         }
1782
1783         /*
1784          * Not used?
1785          * vmcs12->vm_exit_msr_store_addr = evmcs->vm_exit_msr_store_addr;
1786          * vmcs12->vm_exit_msr_load_addr = evmcs->vm_exit_msr_load_addr;
1787          * vmcs12->vm_entry_msr_load_addr = evmcs->vm_entry_msr_load_addr;
1788          * vmcs12->cr3_target_value0 = evmcs->cr3_target_value0;
1789          * vmcs12->cr3_target_value1 = evmcs->cr3_target_value1;
1790          * vmcs12->cr3_target_value2 = evmcs->cr3_target_value2;
1791          * vmcs12->cr3_target_value3 = evmcs->cr3_target_value3;
1792          * vmcs12->page_fault_error_code_mask =
1793          *              evmcs->page_fault_error_code_mask;
1794          * vmcs12->page_fault_error_code_match =
1795          *              evmcs->page_fault_error_code_match;
1796          * vmcs12->cr3_target_count = evmcs->cr3_target_count;
1797          * vmcs12->vm_exit_msr_store_count = evmcs->vm_exit_msr_store_count;
1798          * vmcs12->vm_exit_msr_load_count = evmcs->vm_exit_msr_load_count;
1799          * vmcs12->vm_entry_msr_load_count = evmcs->vm_entry_msr_load_count;
1800          */
1801
1802         /*
1803          * Read only fields:
1804          * vmcs12->guest_physical_address = evmcs->guest_physical_address;
1805          * vmcs12->vm_instruction_error = evmcs->vm_instruction_error;
1806          * vmcs12->vm_exit_reason = evmcs->vm_exit_reason;
1807          * vmcs12->vm_exit_intr_info = evmcs->vm_exit_intr_info;
1808          * vmcs12->vm_exit_intr_error_code = evmcs->vm_exit_intr_error_code;
1809          * vmcs12->idt_vectoring_info_field = evmcs->idt_vectoring_info_field;
1810          * vmcs12->idt_vectoring_error_code = evmcs->idt_vectoring_error_code;
1811          * vmcs12->vm_exit_instruction_len = evmcs->vm_exit_instruction_len;
1812          * vmcs12->vmx_instruction_info = evmcs->vmx_instruction_info;
1813          * vmcs12->exit_qualification = evmcs->exit_qualification;
1814          * vmcs12->guest_linear_address = evmcs->guest_linear_address;
1815          *
1816          * Not present in struct vmcs12:
1817          * vmcs12->exit_io_instruction_ecx = evmcs->exit_io_instruction_ecx;
1818          * vmcs12->exit_io_instruction_esi = evmcs->exit_io_instruction_esi;
1819          * vmcs12->exit_io_instruction_edi = evmcs->exit_io_instruction_edi;
1820          * vmcs12->exit_io_instruction_eip = evmcs->exit_io_instruction_eip;
1821          */
1822
1823         return 0;
1824 }
1825
1826 static int copy_vmcs12_to_enlightened(struct vcpu_vmx *vmx)
1827 {
1828         struct vmcs12 *vmcs12 = vmx->nested.cached_vmcs12;
1829         struct hv_enlightened_vmcs *evmcs = vmx->nested.hv_evmcs;
1830
1831         /*
1832          * Should not be changed by KVM:
1833          *
1834          * evmcs->host_es_selector = vmcs12->host_es_selector;
1835          * evmcs->host_cs_selector = vmcs12->host_cs_selector;
1836          * evmcs->host_ss_selector = vmcs12->host_ss_selector;
1837          * evmcs->host_ds_selector = vmcs12->host_ds_selector;
1838          * evmcs->host_fs_selector = vmcs12->host_fs_selector;
1839          * evmcs->host_gs_selector = vmcs12->host_gs_selector;
1840          * evmcs->host_tr_selector = vmcs12->host_tr_selector;
1841          * evmcs->host_ia32_pat = vmcs12->host_ia32_pat;
1842          * evmcs->host_ia32_efer = vmcs12->host_ia32_efer;
1843          * evmcs->host_cr0 = vmcs12->host_cr0;
1844          * evmcs->host_cr3 = vmcs12->host_cr3;
1845          * evmcs->host_cr4 = vmcs12->host_cr4;
1846          * evmcs->host_ia32_sysenter_esp = vmcs12->host_ia32_sysenter_esp;
1847          * evmcs->host_ia32_sysenter_eip = vmcs12->host_ia32_sysenter_eip;
1848          * evmcs->host_rip = vmcs12->host_rip;
1849          * evmcs->host_ia32_sysenter_cs = vmcs12->host_ia32_sysenter_cs;
1850          * evmcs->host_fs_base = vmcs12->host_fs_base;
1851          * evmcs->host_gs_base = vmcs12->host_gs_base;
1852          * evmcs->host_tr_base = vmcs12->host_tr_base;
1853          * evmcs->host_gdtr_base = vmcs12->host_gdtr_base;
1854          * evmcs->host_idtr_base = vmcs12->host_idtr_base;
1855          * evmcs->host_rsp = vmcs12->host_rsp;
1856          * sync_vmcs02_to_vmcs12() doesn't read these:
1857          * evmcs->io_bitmap_a = vmcs12->io_bitmap_a;
1858          * evmcs->io_bitmap_b = vmcs12->io_bitmap_b;
1859          * evmcs->msr_bitmap = vmcs12->msr_bitmap;
1860          * evmcs->ept_pointer = vmcs12->ept_pointer;
1861          * evmcs->xss_exit_bitmap = vmcs12->xss_exit_bitmap;
1862          * evmcs->vm_exit_msr_store_addr = vmcs12->vm_exit_msr_store_addr;
1863          * evmcs->vm_exit_msr_load_addr = vmcs12->vm_exit_msr_load_addr;
1864          * evmcs->vm_entry_msr_load_addr = vmcs12->vm_entry_msr_load_addr;
1865          * evmcs->cr3_target_value0 = vmcs12->cr3_target_value0;
1866          * evmcs->cr3_target_value1 = vmcs12->cr3_target_value1;
1867          * evmcs->cr3_target_value2 = vmcs12->cr3_target_value2;
1868          * evmcs->cr3_target_value3 = vmcs12->cr3_target_value3;
1869          * evmcs->tpr_threshold = vmcs12->tpr_threshold;
1870          * evmcs->virtual_processor_id = vmcs12->virtual_processor_id;
1871          * evmcs->exception_bitmap = vmcs12->exception_bitmap;
1872          * evmcs->vmcs_link_pointer = vmcs12->vmcs_link_pointer;
1873          * evmcs->pin_based_vm_exec_control = vmcs12->pin_based_vm_exec_control;
1874          * evmcs->vm_exit_controls = vmcs12->vm_exit_controls;
1875          * evmcs->secondary_vm_exec_control = vmcs12->secondary_vm_exec_control;
1876          * evmcs->page_fault_error_code_mask =
1877          *              vmcs12->page_fault_error_code_mask;
1878          * evmcs->page_fault_error_code_match =
1879          *              vmcs12->page_fault_error_code_match;
1880          * evmcs->cr3_target_count = vmcs12->cr3_target_count;
1881          * evmcs->virtual_apic_page_addr = vmcs12->virtual_apic_page_addr;
1882          * evmcs->tsc_offset = vmcs12->tsc_offset;
1883          * evmcs->guest_ia32_debugctl = vmcs12->guest_ia32_debugctl;
1884          * evmcs->cr0_guest_host_mask = vmcs12->cr0_guest_host_mask;
1885          * evmcs->cr4_guest_host_mask = vmcs12->cr4_guest_host_mask;
1886          * evmcs->cr0_read_shadow = vmcs12->cr0_read_shadow;
1887          * evmcs->cr4_read_shadow = vmcs12->cr4_read_shadow;
1888          * evmcs->vm_exit_msr_store_count = vmcs12->vm_exit_msr_store_count;
1889          * evmcs->vm_exit_msr_load_count = vmcs12->vm_exit_msr_load_count;
1890          * evmcs->vm_entry_msr_load_count = vmcs12->vm_entry_msr_load_count;
1891          *
1892          * Not present in struct vmcs12:
1893          * evmcs->exit_io_instruction_ecx = vmcs12->exit_io_instruction_ecx;
1894          * evmcs->exit_io_instruction_esi = vmcs12->exit_io_instruction_esi;
1895          * evmcs->exit_io_instruction_edi = vmcs12->exit_io_instruction_edi;
1896          * evmcs->exit_io_instruction_eip = vmcs12->exit_io_instruction_eip;
1897          */
1898
1899         evmcs->guest_es_selector = vmcs12->guest_es_selector;
1900         evmcs->guest_cs_selector = vmcs12->guest_cs_selector;
1901         evmcs->guest_ss_selector = vmcs12->guest_ss_selector;
1902         evmcs->guest_ds_selector = vmcs12->guest_ds_selector;
1903         evmcs->guest_fs_selector = vmcs12->guest_fs_selector;
1904         evmcs->guest_gs_selector = vmcs12->guest_gs_selector;
1905         evmcs->guest_ldtr_selector = vmcs12->guest_ldtr_selector;
1906         evmcs->guest_tr_selector = vmcs12->guest_tr_selector;
1907
1908         evmcs->guest_es_limit = vmcs12->guest_es_limit;
1909         evmcs->guest_cs_limit = vmcs12->guest_cs_limit;
1910         evmcs->guest_ss_limit = vmcs12->guest_ss_limit;
1911         evmcs->guest_ds_limit = vmcs12->guest_ds_limit;
1912         evmcs->guest_fs_limit = vmcs12->guest_fs_limit;
1913         evmcs->guest_gs_limit = vmcs12->guest_gs_limit;
1914         evmcs->guest_ldtr_limit = vmcs12->guest_ldtr_limit;
1915         evmcs->guest_tr_limit = vmcs12->guest_tr_limit;
1916         evmcs->guest_gdtr_limit = vmcs12->guest_gdtr_limit;
1917         evmcs->guest_idtr_limit = vmcs12->guest_idtr_limit;
1918
1919         evmcs->guest_es_ar_bytes = vmcs12->guest_es_ar_bytes;
1920         evmcs->guest_cs_ar_bytes = vmcs12->guest_cs_ar_bytes;
1921         evmcs->guest_ss_ar_bytes = vmcs12->guest_ss_ar_bytes;
1922         evmcs->guest_ds_ar_bytes = vmcs12->guest_ds_ar_bytes;
1923         evmcs->guest_fs_ar_bytes = vmcs12->guest_fs_ar_bytes;
1924         evmcs->guest_gs_ar_bytes = vmcs12->guest_gs_ar_bytes;
1925         evmcs->guest_ldtr_ar_bytes = vmcs12->guest_ldtr_ar_bytes;
1926         evmcs->guest_tr_ar_bytes = vmcs12->guest_tr_ar_bytes;
1927
1928         evmcs->guest_es_base = vmcs12->guest_es_base;
1929         evmcs->guest_cs_base = vmcs12->guest_cs_base;
1930         evmcs->guest_ss_base = vmcs12->guest_ss_base;
1931         evmcs->guest_ds_base = vmcs12->guest_ds_base;
1932         evmcs->guest_fs_base = vmcs12->guest_fs_base;
1933         evmcs->guest_gs_base = vmcs12->guest_gs_base;
1934         evmcs->guest_ldtr_base = vmcs12->guest_ldtr_base;
1935         evmcs->guest_tr_base = vmcs12->guest_tr_base;
1936         evmcs->guest_gdtr_base = vmcs12->guest_gdtr_base;
1937         evmcs->guest_idtr_base = vmcs12->guest_idtr_base;
1938
1939         evmcs->guest_ia32_pat = vmcs12->guest_ia32_pat;
1940         evmcs->guest_ia32_efer = vmcs12->guest_ia32_efer;
1941
1942         evmcs->guest_pdptr0 = vmcs12->guest_pdptr0;
1943         evmcs->guest_pdptr1 = vmcs12->guest_pdptr1;
1944         evmcs->guest_pdptr2 = vmcs12->guest_pdptr2;
1945         evmcs->guest_pdptr3 = vmcs12->guest_pdptr3;
1946
1947         evmcs->guest_pending_dbg_exceptions =
1948                 vmcs12->guest_pending_dbg_exceptions;
1949         evmcs->guest_sysenter_esp = vmcs12->guest_sysenter_esp;
1950         evmcs->guest_sysenter_eip = vmcs12->guest_sysenter_eip;
1951
1952         evmcs->guest_activity_state = vmcs12->guest_activity_state;
1953         evmcs->guest_sysenter_cs = vmcs12->guest_sysenter_cs;
1954
1955         evmcs->guest_cr0 = vmcs12->guest_cr0;
1956         evmcs->guest_cr3 = vmcs12->guest_cr3;
1957         evmcs->guest_cr4 = vmcs12->guest_cr4;
1958         evmcs->guest_dr7 = vmcs12->guest_dr7;
1959
1960         evmcs->guest_physical_address = vmcs12->guest_physical_address;
1961
1962         evmcs->vm_instruction_error = vmcs12->vm_instruction_error;
1963         evmcs->vm_exit_reason = vmcs12->vm_exit_reason;
1964         evmcs->vm_exit_intr_info = vmcs12->vm_exit_intr_info;
1965         evmcs->vm_exit_intr_error_code = vmcs12->vm_exit_intr_error_code;
1966         evmcs->idt_vectoring_info_field = vmcs12->idt_vectoring_info_field;
1967         evmcs->idt_vectoring_error_code = vmcs12->idt_vectoring_error_code;
1968         evmcs->vm_exit_instruction_len = vmcs12->vm_exit_instruction_len;
1969         evmcs->vmx_instruction_info = vmcs12->vmx_instruction_info;
1970
1971         evmcs->exit_qualification = vmcs12->exit_qualification;
1972
1973         evmcs->guest_linear_address = vmcs12->guest_linear_address;
1974         evmcs->guest_rsp = vmcs12->guest_rsp;
1975         evmcs->guest_rflags = vmcs12->guest_rflags;
1976
1977         evmcs->guest_interruptibility_info =
1978                 vmcs12->guest_interruptibility_info;
1979         evmcs->cpu_based_vm_exec_control = vmcs12->cpu_based_vm_exec_control;
1980         evmcs->vm_entry_controls = vmcs12->vm_entry_controls;
1981         evmcs->vm_entry_intr_info_field = vmcs12->vm_entry_intr_info_field;
1982         evmcs->vm_entry_exception_error_code =
1983                 vmcs12->vm_entry_exception_error_code;
1984         evmcs->vm_entry_instruction_len = vmcs12->vm_entry_instruction_len;
1985
1986         evmcs->guest_rip = vmcs12->guest_rip;
1987
1988         evmcs->guest_bndcfgs = vmcs12->guest_bndcfgs;
1989
1990         return 0;
1991 }
1992
1993 /*
1994  * This is an equivalent of the nested hypervisor executing the vmptrld
1995  * instruction.
1996  */
1997 static enum nested_evmptrld_status nested_vmx_handle_enlightened_vmptrld(
1998         struct kvm_vcpu *vcpu, bool from_launch)
1999 {
2000         struct vcpu_vmx *vmx = to_vmx(vcpu);
2001         bool evmcs_gpa_changed = false;
2002         u64 evmcs_gpa;
2003
2004         if (likely(!vmx->nested.enlightened_vmcs_enabled))
2005                 return EVMPTRLD_DISABLED;
2006
2007         if (!nested_enlightened_vmentry(vcpu, &evmcs_gpa))
2008                 return EVMPTRLD_DISABLED;
2009
2010         if (unlikely(!vmx->nested.hv_evmcs ||
2011                      evmcs_gpa != vmx->nested.hv_evmcs_vmptr)) {
2012                 if (!vmx->nested.hv_evmcs)
2013                         vmx->nested.current_vmptr = -1ull;
2014
2015                 nested_release_evmcs(vcpu);
2016
2017                 if (kvm_vcpu_map(vcpu, gpa_to_gfn(evmcs_gpa),
2018                                  &vmx->nested.hv_evmcs_map))
2019                         return EVMPTRLD_ERROR;
2020
2021                 vmx->nested.hv_evmcs = vmx->nested.hv_evmcs_map.hva;
2022
2023                 /*
2024                  * Currently, KVM only supports eVMCS version 1
2025                  * (== KVM_EVMCS_VERSION) and thus we expect guest to set this
2026                  * value to first u32 field of eVMCS which should specify eVMCS
2027                  * VersionNumber.
2028                  *
2029                  * Guest should be aware of supported eVMCS versions by host by
2030                  * examining CPUID.0x4000000A.EAX[0:15]. Host userspace VMM is
2031                  * expected to set this CPUID leaf according to the value
2032                  * returned in vmcs_version from nested_enable_evmcs().
2033                  *
2034                  * However, it turns out that Microsoft Hyper-V fails to comply
2035                  * to their own invented interface: When Hyper-V use eVMCS, it
2036                  * just sets first u32 field of eVMCS to revision_id specified
2037                  * in MSR_IA32_VMX_BASIC. Instead of used eVMCS version number
2038                  * which is one of the supported versions specified in
2039                  * CPUID.0x4000000A.EAX[0:15].
2040                  *
2041                  * To overcome Hyper-V bug, we accept here either a supported
2042                  * eVMCS version or VMCS12 revision_id as valid values for first
2043                  * u32 field of eVMCS.
2044                  */
2045                 if ((vmx->nested.hv_evmcs->revision_id != KVM_EVMCS_VERSION) &&
2046                     (vmx->nested.hv_evmcs->revision_id != VMCS12_REVISION)) {
2047                         nested_release_evmcs(vcpu);
2048                         return EVMPTRLD_VMFAIL;
2049                 }
2050
2051                 vmx->nested.dirty_vmcs12 = true;
2052                 vmx->nested.hv_evmcs_vmptr = evmcs_gpa;
2053
2054                 evmcs_gpa_changed = true;
2055                 /*
2056                  * Unlike normal vmcs12, enlightened vmcs12 is not fully
2057                  * reloaded from guest's memory (read only fields, fields not
2058                  * present in struct hv_enlightened_vmcs, ...). Make sure there
2059                  * are no leftovers.
2060                  */
2061                 if (from_launch) {
2062                         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2063                         memset(vmcs12, 0, sizeof(*vmcs12));
2064                         vmcs12->hdr.revision_id = VMCS12_REVISION;
2065                 }
2066
2067         }
2068
2069         /*
2070          * Clean fields data can't be used on VMLAUNCH and when we switch
2071          * between different L2 guests as KVM keeps a single VMCS12 per L1.
2072          */
2073         if (from_launch || evmcs_gpa_changed)
2074                 vmx->nested.hv_evmcs->hv_clean_fields &=
2075                         ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
2076
2077         return EVMPTRLD_SUCCEEDED;
2078 }
2079
2080 void nested_sync_vmcs12_to_shadow(struct kvm_vcpu *vcpu)
2081 {
2082         struct vcpu_vmx *vmx = to_vmx(vcpu);
2083
2084         if (vmx->nested.hv_evmcs) {
2085                 copy_vmcs12_to_enlightened(vmx);
2086                 /* All fields are clean */
2087                 vmx->nested.hv_evmcs->hv_clean_fields |=
2088                         HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
2089         } else {
2090                 copy_vmcs12_to_shadow(vmx);
2091         }
2092
2093         vmx->nested.need_vmcs12_to_shadow_sync = false;
2094 }
2095
2096 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
2097 {
2098         struct vcpu_vmx *vmx =
2099                 container_of(timer, struct vcpu_vmx, nested.preemption_timer);
2100
2101         vmx->nested.preemption_timer_expired = true;
2102         kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
2103         kvm_vcpu_kick(&vmx->vcpu);
2104
2105         return HRTIMER_NORESTART;
2106 }
2107
2108 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
2109 {
2110         u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
2111         struct vcpu_vmx *vmx = to_vmx(vcpu);
2112
2113         /*
2114          * A timer value of zero is architecturally guaranteed to cause
2115          * a VMExit prior to executing any instructions in the guest.
2116          */
2117         if (preemption_timeout == 0) {
2118                 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
2119                 return;
2120         }
2121
2122         if (vcpu->arch.virtual_tsc_khz == 0)
2123                 return;
2124
2125         preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
2126         preemption_timeout *= 1000000;
2127         do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
2128         hrtimer_start(&vmx->nested.preemption_timer,
2129                       ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
2130 }
2131
2132 static u64 nested_vmx_calc_efer(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
2133 {
2134         if (vmx->nested.nested_run_pending &&
2135             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
2136                 return vmcs12->guest_ia32_efer;
2137         else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
2138                 return vmx->vcpu.arch.efer | (EFER_LMA | EFER_LME);
2139         else
2140                 return vmx->vcpu.arch.efer & ~(EFER_LMA | EFER_LME);
2141 }
2142
2143 static void prepare_vmcs02_constant_state(struct vcpu_vmx *vmx)
2144 {
2145         /*
2146          * If vmcs02 hasn't been initialized, set the constant vmcs02 state
2147          * according to L0's settings (vmcs12 is irrelevant here).  Host
2148          * fields that come from L0 and are not constant, e.g. HOST_CR3,
2149          * will be set as needed prior to VMLAUNCH/VMRESUME.
2150          */
2151         if (vmx->nested.vmcs02_initialized)
2152                 return;
2153         vmx->nested.vmcs02_initialized = true;
2154
2155         /*
2156          * We don't care what the EPTP value is we just need to guarantee
2157          * it's valid so we don't get a false positive when doing early
2158          * consistency checks.
2159          */
2160         if (enable_ept && nested_early_check)
2161                 vmcs_write64(EPT_POINTER, construct_eptp(&vmx->vcpu, 0));
2162
2163         /* All VMFUNCs are currently emulated through L0 vmexits.  */
2164         if (cpu_has_vmx_vmfunc())
2165                 vmcs_write64(VM_FUNCTION_CONTROL, 0);
2166
2167         if (cpu_has_vmx_posted_intr())
2168                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
2169
2170         if (cpu_has_vmx_msr_bitmap())
2171                 vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
2172
2173         /*
2174          * The PML address never changes, so it is constant in vmcs02.
2175          * Conceptually we want to copy the PML index from vmcs01 here,
2176          * and then back to vmcs01 on nested vmexit.  But since we flush
2177          * the log and reset GUEST_PML_INDEX on each vmexit, the PML
2178          * index is also effectively constant in vmcs02.
2179          */
2180         if (enable_pml) {
2181                 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
2182                 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
2183         }
2184
2185         if (cpu_has_vmx_encls_vmexit())
2186                 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
2187
2188         /*
2189          * Set the MSR load/store lists to match L0's settings.  Only the
2190          * addresses are constant (for vmcs02), the counts can change based
2191          * on L2's behavior, e.g. switching to/from long mode.
2192          */
2193         vmcs_write64(VM_EXIT_MSR_STORE_ADDR, __pa(vmx->msr_autostore.guest.val));
2194         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
2195         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
2196
2197         vmx_set_constant_host_state(vmx);
2198 }
2199
2200 static void prepare_vmcs02_early_rare(struct vcpu_vmx *vmx,
2201                                       struct vmcs12 *vmcs12)
2202 {
2203         prepare_vmcs02_constant_state(vmx);
2204
2205         vmcs_write64(VMCS_LINK_POINTER, -1ull);
2206
2207         if (enable_vpid) {
2208                 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02)
2209                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
2210                 else
2211                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
2212         }
2213 }
2214
2215 static void prepare_vmcs02_early(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
2216 {
2217         u32 exec_control, vmcs12_exec_ctrl;
2218         u64 guest_efer = nested_vmx_calc_efer(vmx, vmcs12);
2219
2220         if (vmx->nested.dirty_vmcs12 || vmx->nested.hv_evmcs)
2221                 prepare_vmcs02_early_rare(vmx, vmcs12);
2222
2223         /*
2224          * PIN CONTROLS
2225          */
2226         exec_control = vmx_pin_based_exec_ctrl(vmx);
2227         exec_control |= (vmcs12->pin_based_vm_exec_control &
2228                          ~PIN_BASED_VMX_PREEMPTION_TIMER);
2229
2230         /* Posted interrupts setting is only taken from vmcs12.  */
2231         if (nested_cpu_has_posted_intr(vmcs12)) {
2232                 vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
2233                 vmx->nested.pi_pending = false;
2234         } else {
2235                 exec_control &= ~PIN_BASED_POSTED_INTR;
2236         }
2237         pin_controls_set(vmx, exec_control);
2238
2239         /*
2240          * EXEC CONTROLS
2241          */
2242         exec_control = vmx_exec_control(vmx); /* L0's desires */
2243         exec_control &= ~CPU_BASED_INTR_WINDOW_EXITING;
2244         exec_control &= ~CPU_BASED_NMI_WINDOW_EXITING;
2245         exec_control &= ~CPU_BASED_TPR_SHADOW;
2246         exec_control |= vmcs12->cpu_based_vm_exec_control;
2247
2248         vmx->nested.l1_tpr_threshold = -1;
2249         if (exec_control & CPU_BASED_TPR_SHADOW)
2250                 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
2251 #ifdef CONFIG_X86_64
2252         else
2253                 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
2254                                 CPU_BASED_CR8_STORE_EXITING;
2255 #endif
2256
2257         /*
2258          * A vmexit (to either L1 hypervisor or L0 userspace) is always needed
2259          * for I/O port accesses.
2260          */
2261         exec_control |= CPU_BASED_UNCOND_IO_EXITING;
2262         exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
2263
2264         /*
2265          * This bit will be computed in nested_get_vmcs12_pages, because
2266          * we do not have access to L1's MSR bitmap yet.  For now, keep
2267          * the same bit as before, hoping to avoid multiple VMWRITEs that
2268          * only set/clear this bit.
2269          */
2270         exec_control &= ~CPU_BASED_USE_MSR_BITMAPS;
2271         exec_control |= exec_controls_get(vmx) & CPU_BASED_USE_MSR_BITMAPS;
2272
2273         exec_controls_set(vmx, exec_control);
2274
2275         /*
2276          * SECONDARY EXEC CONTROLS
2277          */
2278         if (cpu_has_secondary_exec_ctrls()) {
2279                 exec_control = vmx->secondary_exec_control;
2280
2281                 /* Take the following fields only from vmcs12 */
2282                 exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2283                                   SECONDARY_EXEC_ENABLE_INVPCID |
2284                                   SECONDARY_EXEC_RDTSCP |
2285                                   SECONDARY_EXEC_XSAVES |
2286                                   SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE |
2287                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2288                                   SECONDARY_EXEC_APIC_REGISTER_VIRT |
2289                                   SECONDARY_EXEC_ENABLE_VMFUNC);
2290                 if (nested_cpu_has(vmcs12,
2291                                    CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
2292                         vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
2293                                 ~SECONDARY_EXEC_ENABLE_PML;
2294                         exec_control |= vmcs12_exec_ctrl;
2295                 }
2296
2297                 /* VMCS shadowing for L2 is emulated for now */
2298                 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
2299
2300                 /*
2301                  * Preset *DT exiting when emulating UMIP, so that vmx_set_cr4()
2302                  * will not have to rewrite the controls just for this bit.
2303                  */
2304                 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated() &&
2305                     (vmcs12->guest_cr4 & X86_CR4_UMIP))
2306                         exec_control |= SECONDARY_EXEC_DESC;
2307
2308                 if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
2309                         vmcs_write16(GUEST_INTR_STATUS,
2310                                 vmcs12->guest_intr_status);
2311
2312                 secondary_exec_controls_set(vmx, exec_control);
2313         }
2314
2315         /*
2316          * ENTRY CONTROLS
2317          *
2318          * vmcs12's VM_{ENTRY,EXIT}_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE
2319          * are emulated by vmx_set_efer() in prepare_vmcs02(), but speculate
2320          * on the related bits (if supported by the CPU) in the hope that
2321          * we can avoid VMWrites during vmx_set_efer().
2322          */
2323         exec_control = (vmcs12->vm_entry_controls | vmx_vmentry_ctrl()) &
2324                         ~VM_ENTRY_IA32E_MODE & ~VM_ENTRY_LOAD_IA32_EFER;
2325         if (cpu_has_load_ia32_efer()) {
2326                 if (guest_efer & EFER_LMA)
2327                         exec_control |= VM_ENTRY_IA32E_MODE;
2328                 if (guest_efer != host_efer)
2329                         exec_control |= VM_ENTRY_LOAD_IA32_EFER;
2330         }
2331         vm_entry_controls_set(vmx, exec_control);
2332
2333         /*
2334          * EXIT CONTROLS
2335          *
2336          * L2->L1 exit controls are emulated - the hardware exit is to L0 so
2337          * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
2338          * bits may be modified by vmx_set_efer() in prepare_vmcs02().
2339          */
2340         exec_control = vmx_vmexit_ctrl();
2341         if (cpu_has_load_ia32_efer() && guest_efer != host_efer)
2342                 exec_control |= VM_EXIT_LOAD_IA32_EFER;
2343         vm_exit_controls_set(vmx, exec_control);
2344
2345         /*
2346          * Interrupt/Exception Fields
2347          */
2348         if (vmx->nested.nested_run_pending) {
2349                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
2350                              vmcs12->vm_entry_intr_info_field);
2351                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
2352                              vmcs12->vm_entry_exception_error_code);
2353                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
2354                              vmcs12->vm_entry_instruction_len);
2355                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
2356                              vmcs12->guest_interruptibility_info);
2357                 vmx->loaded_vmcs->nmi_known_unmasked =
2358                         !(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
2359         } else {
2360                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
2361         }
2362 }
2363
2364 static void prepare_vmcs02_rare(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
2365 {
2366         struct hv_enlightened_vmcs *hv_evmcs = vmx->nested.hv_evmcs;
2367
2368         if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
2369                            HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2)) {
2370                 vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
2371                 vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
2372                 vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
2373                 vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
2374                 vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
2375                 vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
2376                 vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
2377                 vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
2378                 vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
2379                 vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
2380                 vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
2381                 vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
2382                 vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
2383                 vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
2384                 vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
2385                 vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
2386                 vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
2387                 vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
2388                 vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
2389                 vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
2390                 vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
2391                 vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
2392                 vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
2393                 vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
2394                 vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
2395                 vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
2396                 vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
2397                 vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
2398                 vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
2399                 vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
2400                 vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
2401                 vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
2402                 vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
2403                 vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
2404                 vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
2405                 vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
2406         }
2407
2408         if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
2409                            HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1)) {
2410                 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
2411                 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
2412                             vmcs12->guest_pending_dbg_exceptions);
2413                 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
2414                 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
2415
2416                 /*
2417                  * L1 may access the L2's PDPTR, so save them to construct
2418                  * vmcs12
2419                  */
2420                 if (enable_ept) {
2421                         vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
2422                         vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
2423                         vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
2424                         vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
2425                 }
2426
2427                 if (kvm_mpx_supported() && vmx->nested.nested_run_pending &&
2428                     (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
2429                         vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
2430         }
2431
2432         if (nested_cpu_has_xsaves(vmcs12))
2433                 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
2434
2435         /*
2436          * Whether page-faults are trapped is determined by a combination of
2437          * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
2438          * If enable_ept, L0 doesn't care about page faults and we should
2439          * set all of these to L1's desires. However, if !enable_ept, L0 does
2440          * care about (at least some) page faults, and because it is not easy
2441          * (if at all possible?) to merge L0 and L1's desires, we simply ask
2442          * to exit on each and every L2 page fault. This is done by setting
2443          * MASK=MATCH=0 and (see below) EB.PF=1.
2444          * Note that below we don't need special code to set EB.PF beyond the
2445          * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
2446          * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
2447          * !enable_ept, EB.PF is 1, so the "or" will always be 1.
2448          */
2449         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
2450                 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
2451         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
2452                 enable_ept ? vmcs12->page_fault_error_code_match : 0);
2453
2454         if (cpu_has_vmx_apicv()) {
2455                 vmcs_write64(EOI_EXIT_BITMAP0, vmcs12->eoi_exit_bitmap0);
2456                 vmcs_write64(EOI_EXIT_BITMAP1, vmcs12->eoi_exit_bitmap1);
2457                 vmcs_write64(EOI_EXIT_BITMAP2, vmcs12->eoi_exit_bitmap2);
2458                 vmcs_write64(EOI_EXIT_BITMAP3, vmcs12->eoi_exit_bitmap3);
2459         }
2460
2461         /*
2462          * Make sure the msr_autostore list is up to date before we set the
2463          * count in the vmcs02.
2464          */
2465         prepare_vmx_msr_autostore_list(&vmx->vcpu, MSR_IA32_TSC);
2466
2467         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, vmx->msr_autostore.guest.nr);
2468         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
2469         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
2470
2471         set_cr4_guest_host_mask(vmx);
2472 }
2473
2474 /*
2475  * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
2476  * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
2477  * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
2478  * guest in a way that will both be appropriate to L1's requests, and our
2479  * needs. In addition to modifying the active vmcs (which is vmcs02), this
2480  * function also has additional necessary side-effects, like setting various
2481  * vcpu->arch fields.
2482  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
2483  * is assigned to entry_failure_code on failure.
2484  */
2485 static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
2486                           u32 *entry_failure_code)
2487 {
2488         struct vcpu_vmx *vmx = to_vmx(vcpu);
2489         struct hv_enlightened_vmcs *hv_evmcs = vmx->nested.hv_evmcs;
2490         bool load_guest_pdptrs_vmcs12 = false;
2491
2492         if (vmx->nested.dirty_vmcs12 || hv_evmcs) {
2493                 prepare_vmcs02_rare(vmx, vmcs12);
2494                 vmx->nested.dirty_vmcs12 = false;
2495
2496                 load_guest_pdptrs_vmcs12 = !hv_evmcs ||
2497                         !(hv_evmcs->hv_clean_fields &
2498                           HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1);
2499         }
2500
2501         if (vmx->nested.nested_run_pending &&
2502             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
2503                 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
2504                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
2505         } else {
2506                 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
2507                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
2508         }
2509         if (kvm_mpx_supported() && (!vmx->nested.nested_run_pending ||
2510             !(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)))
2511                 vmcs_write64(GUEST_BNDCFGS, vmx->nested.vmcs01_guest_bndcfgs);
2512         vmx_set_rflags(vcpu, vmcs12->guest_rflags);
2513
2514         /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
2515          * bitwise-or of what L1 wants to trap for L2, and what we want to
2516          * trap. Note that CR0.TS also needs updating - we do this later.
2517          */
2518         update_exception_bitmap(vcpu);
2519         vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
2520         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
2521
2522         if (vmx->nested.nested_run_pending &&
2523             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
2524                 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
2525                 vcpu->arch.pat = vmcs12->guest_ia32_pat;
2526         } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2527                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
2528         }
2529
2530         vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
2531
2532         if (kvm_has_tsc_control)
2533                 decache_tsc_multiplier(vmx);
2534
2535         nested_vmx_transition_tlb_flush(vcpu, vmcs12, true);
2536
2537         if (nested_cpu_has_ept(vmcs12))
2538                 nested_ept_init_mmu_context(vcpu);
2539
2540         /*
2541          * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
2542          * bits which we consider mandatory enabled.
2543          * The CR0_READ_SHADOW is what L2 should have expected to read given
2544          * the specifications by L1; It's not enough to take
2545          * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
2546          * have more bits than L1 expected.
2547          */
2548         vmx_set_cr0(vcpu, vmcs12->guest_cr0);
2549         vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
2550
2551         vmx_set_cr4(vcpu, vmcs12->guest_cr4);
2552         vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
2553
2554         vcpu->arch.efer = nested_vmx_calc_efer(vmx, vmcs12);
2555         /* Note: may modify VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
2556         vmx_set_efer(vcpu, vcpu->arch.efer);
2557
2558         /*
2559          * Guest state is invalid and unrestricted guest is disabled,
2560          * which means L1 attempted VMEntry to L2 with invalid state.
2561          * Fail the VMEntry.
2562          */
2563         if (vmx->emulation_required) {
2564                 *entry_failure_code = ENTRY_FAIL_DEFAULT;
2565                 return -EINVAL;
2566         }
2567
2568         /* Shadow page tables on either EPT or shadow page tables. */
2569         if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
2570                                 entry_failure_code))
2571                 return -EINVAL;
2572
2573         /*
2574          * Immediately write vmcs02.GUEST_CR3.  It will be propagated to vmcs12
2575          * on nested VM-Exit, which can occur without actually running L2 and
2576          * thus without hitting vmx_load_mmu_pgd(), e.g. if L1 is entering L2 with
2577          * vmcs12.GUEST_ACTIVITYSTATE=HLT, in which case KVM will intercept the
2578          * transition to HLT instead of running L2.
2579          */
2580         if (enable_ept)
2581                 vmcs_writel(GUEST_CR3, vmcs12->guest_cr3);
2582
2583         /* Late preparation of GUEST_PDPTRs now that EFER and CRs are set. */
2584         if (load_guest_pdptrs_vmcs12 && nested_cpu_has_ept(vmcs12) &&
2585             is_pae_paging(vcpu)) {
2586                 vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
2587                 vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
2588                 vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
2589                 vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
2590         }
2591
2592         if (!enable_ept)
2593                 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
2594
2595         if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL) &&
2596             WARN_ON_ONCE(kvm_set_msr(vcpu, MSR_CORE_PERF_GLOBAL_CTRL,
2597                                      vmcs12->guest_ia32_perf_global_ctrl)))
2598                 return -EINVAL;
2599
2600         kvm_rsp_write(vcpu, vmcs12->guest_rsp);
2601         kvm_rip_write(vcpu, vmcs12->guest_rip);
2602         return 0;
2603 }
2604
2605 static int nested_vmx_check_nmi_controls(struct vmcs12 *vmcs12)
2606 {
2607         if (CC(!nested_cpu_has_nmi_exiting(vmcs12) &&
2608                nested_cpu_has_virtual_nmis(vmcs12)))
2609                 return -EINVAL;
2610
2611         if (CC(!nested_cpu_has_virtual_nmis(vmcs12) &&
2612                nested_cpu_has(vmcs12, CPU_BASED_NMI_WINDOW_EXITING)))
2613                 return -EINVAL;
2614
2615         return 0;
2616 }
2617
2618 static bool nested_vmx_check_eptp(struct kvm_vcpu *vcpu, u64 new_eptp)
2619 {
2620         struct vcpu_vmx *vmx = to_vmx(vcpu);
2621         int maxphyaddr = cpuid_maxphyaddr(vcpu);
2622
2623         /* Check for memory type validity */
2624         switch (new_eptp & VMX_EPTP_MT_MASK) {
2625         case VMX_EPTP_MT_UC:
2626                 if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPTP_UC_BIT)))
2627                         return false;
2628                 break;
2629         case VMX_EPTP_MT_WB:
2630                 if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPTP_WB_BIT)))
2631                         return false;
2632                 break;
2633         default:
2634                 return false;
2635         }
2636
2637         /* Page-walk levels validity. */
2638         switch (new_eptp & VMX_EPTP_PWL_MASK) {
2639         case VMX_EPTP_PWL_5:
2640                 if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPT_PAGE_WALK_5_BIT)))
2641                         return false;
2642                 break;
2643         case VMX_EPTP_PWL_4:
2644                 if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPT_PAGE_WALK_4_BIT)))
2645                         return false;
2646                 break;
2647         default:
2648                 return false;
2649         }
2650
2651         /* Reserved bits should not be set */
2652         if (CC(new_eptp >> maxphyaddr || ((new_eptp >> 7) & 0x1f)))
2653                 return false;
2654
2655         /* AD, if set, should be supported */
2656         if (new_eptp & VMX_EPTP_AD_ENABLE_BIT) {
2657                 if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPT_AD_BIT)))
2658                         return false;
2659         }
2660
2661         return true;
2662 }
2663
2664 /*
2665  * Checks related to VM-Execution Control Fields
2666  */
2667 static int nested_check_vm_execution_controls(struct kvm_vcpu *vcpu,
2668                                               struct vmcs12 *vmcs12)
2669 {
2670         struct vcpu_vmx *vmx = to_vmx(vcpu);
2671
2672         if (CC(!vmx_control_verify(vmcs12->pin_based_vm_exec_control,
2673                                    vmx->nested.msrs.pinbased_ctls_low,
2674                                    vmx->nested.msrs.pinbased_ctls_high)) ||
2675             CC(!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
2676                                    vmx->nested.msrs.procbased_ctls_low,
2677                                    vmx->nested.msrs.procbased_ctls_high)))
2678                 return -EINVAL;
2679
2680         if (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
2681             CC(!vmx_control_verify(vmcs12->secondary_vm_exec_control,
2682                                    vmx->nested.msrs.secondary_ctls_low,
2683                                    vmx->nested.msrs.secondary_ctls_high)))
2684                 return -EINVAL;
2685
2686         if (CC(vmcs12->cr3_target_count > nested_cpu_vmx_misc_cr3_count(vcpu)) ||
2687             nested_vmx_check_io_bitmap_controls(vcpu, vmcs12) ||
2688             nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12) ||
2689             nested_vmx_check_tpr_shadow_controls(vcpu, vmcs12) ||
2690             nested_vmx_check_apic_access_controls(vcpu, vmcs12) ||
2691             nested_vmx_check_apicv_controls(vcpu, vmcs12) ||
2692             nested_vmx_check_nmi_controls(vmcs12) ||
2693             nested_vmx_check_pml_controls(vcpu, vmcs12) ||
2694             nested_vmx_check_unrestricted_guest_controls(vcpu, vmcs12) ||
2695             nested_vmx_check_mode_based_ept_exec_controls(vcpu, vmcs12) ||
2696             nested_vmx_check_shadow_vmcs_controls(vcpu, vmcs12) ||
2697             CC(nested_cpu_has_vpid(vmcs12) && !vmcs12->virtual_processor_id))
2698                 return -EINVAL;
2699
2700         if (!nested_cpu_has_preemption_timer(vmcs12) &&
2701             nested_cpu_has_save_preemption_timer(vmcs12))
2702                 return -EINVAL;
2703
2704         if (nested_cpu_has_ept(vmcs12) &&
2705             CC(!nested_vmx_check_eptp(vcpu, vmcs12->ept_pointer)))
2706                 return -EINVAL;
2707
2708         if (nested_cpu_has_vmfunc(vmcs12)) {
2709                 if (CC(vmcs12->vm_function_control &
2710                        ~vmx->nested.msrs.vmfunc_controls))
2711                         return -EINVAL;
2712
2713                 if (nested_cpu_has_eptp_switching(vmcs12)) {
2714                         if (CC(!nested_cpu_has_ept(vmcs12)) ||
2715                             CC(!page_address_valid(vcpu, vmcs12->eptp_list_address)))
2716                                 return -EINVAL;
2717                 }
2718         }
2719
2720         return 0;
2721 }
2722
2723 /*
2724  * Checks related to VM-Exit Control Fields
2725  */
2726 static int nested_check_vm_exit_controls(struct kvm_vcpu *vcpu,
2727                                          struct vmcs12 *vmcs12)
2728 {
2729         struct vcpu_vmx *vmx = to_vmx(vcpu);
2730
2731         if (CC(!vmx_control_verify(vmcs12->vm_exit_controls,
2732                                     vmx->nested.msrs.exit_ctls_low,
2733                                     vmx->nested.msrs.exit_ctls_high)) ||
2734             CC(nested_vmx_check_exit_msr_switch_controls(vcpu, vmcs12)))
2735                 return -EINVAL;
2736
2737         return 0;
2738 }
2739
2740 /*
2741  * Checks related to VM-Entry Control Fields
2742  */
2743 static int nested_check_vm_entry_controls(struct kvm_vcpu *vcpu,
2744                                           struct vmcs12 *vmcs12)
2745 {
2746         struct vcpu_vmx *vmx = to_vmx(vcpu);
2747
2748         if (CC(!vmx_control_verify(vmcs12->vm_entry_controls,
2749                                     vmx->nested.msrs.entry_ctls_low,
2750                                     vmx->nested.msrs.entry_ctls_high)))
2751                 return -EINVAL;
2752
2753         /*
2754          * From the Intel SDM, volume 3:
2755          * Fields relevant to VM-entry event injection must be set properly.
2756          * These fields are the VM-entry interruption-information field, the
2757          * VM-entry exception error code, and the VM-entry instruction length.
2758          */
2759         if (vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) {
2760                 u32 intr_info = vmcs12->vm_entry_intr_info_field;
2761                 u8 vector = intr_info & INTR_INFO_VECTOR_MASK;
2762                 u32 intr_type = intr_info & INTR_INFO_INTR_TYPE_MASK;
2763                 bool has_error_code = intr_info & INTR_INFO_DELIVER_CODE_MASK;
2764                 bool should_have_error_code;
2765                 bool urg = nested_cpu_has2(vmcs12,
2766                                            SECONDARY_EXEC_UNRESTRICTED_GUEST);
2767                 bool prot_mode = !urg || vmcs12->guest_cr0 & X86_CR0_PE;
2768
2769                 /* VM-entry interruption-info field: interruption type */
2770                 if (CC(intr_type == INTR_TYPE_RESERVED) ||
2771                     CC(intr_type == INTR_TYPE_OTHER_EVENT &&
2772                        !nested_cpu_supports_monitor_trap_flag(vcpu)))
2773                         return -EINVAL;
2774
2775                 /* VM-entry interruption-info field: vector */
2776                 if (CC(intr_type == INTR_TYPE_NMI_INTR && vector != NMI_VECTOR) ||
2777                     CC(intr_type == INTR_TYPE_HARD_EXCEPTION && vector > 31) ||
2778                     CC(intr_type == INTR_TYPE_OTHER_EVENT && vector != 0))
2779                         return -EINVAL;
2780
2781                 /* VM-entry interruption-info field: deliver error code */
2782                 should_have_error_code =
2783                         intr_type == INTR_TYPE_HARD_EXCEPTION && prot_mode &&
2784                         x86_exception_has_error_code(vector);
2785                 if (CC(has_error_code != should_have_error_code))
2786                         return -EINVAL;
2787
2788                 /* VM-entry exception error code */
2789                 if (CC(has_error_code &&
2790                        vmcs12->vm_entry_exception_error_code & GENMASK(31, 16)))
2791                         return -EINVAL;
2792
2793                 /* VM-entry interruption-info field: reserved bits */
2794                 if (CC(intr_info & INTR_INFO_RESVD_BITS_MASK))
2795                         return -EINVAL;
2796
2797                 /* VM-entry instruction length */
2798                 switch (intr_type) {
2799                 case INTR_TYPE_SOFT_EXCEPTION:
2800                 case INTR_TYPE_SOFT_INTR:
2801                 case INTR_TYPE_PRIV_SW_EXCEPTION:
2802                         if (CC(vmcs12->vm_entry_instruction_len > 15) ||
2803                             CC(vmcs12->vm_entry_instruction_len == 0 &&
2804                             CC(!nested_cpu_has_zero_length_injection(vcpu))))
2805                                 return -EINVAL;
2806                 }
2807         }
2808
2809         if (nested_vmx_check_entry_msr_switch_controls(vcpu, vmcs12))
2810                 return -EINVAL;
2811
2812         return 0;
2813 }
2814
2815 static int nested_vmx_check_controls(struct kvm_vcpu *vcpu,
2816                                      struct vmcs12 *vmcs12)
2817 {
2818         if (nested_check_vm_execution_controls(vcpu, vmcs12) ||
2819             nested_check_vm_exit_controls(vcpu, vmcs12) ||
2820             nested_check_vm_entry_controls(vcpu, vmcs12))
2821                 return -EINVAL;
2822
2823         if (to_vmx(vcpu)->nested.enlightened_vmcs_enabled)
2824                 return nested_evmcs_check_controls(vmcs12);
2825
2826         return 0;
2827 }
2828
2829 static int nested_vmx_check_host_state(struct kvm_vcpu *vcpu,
2830                                        struct vmcs12 *vmcs12)
2831 {
2832         bool ia32e;
2833
2834         if (CC(!nested_host_cr0_valid(vcpu, vmcs12->host_cr0)) ||
2835             CC(!nested_host_cr4_valid(vcpu, vmcs12->host_cr4)) ||
2836             CC(!nested_cr3_valid(vcpu, vmcs12->host_cr3)))
2837                 return -EINVAL;
2838
2839         if (CC(is_noncanonical_address(vmcs12->host_ia32_sysenter_esp, vcpu)) ||
2840             CC(is_noncanonical_address(vmcs12->host_ia32_sysenter_eip, vcpu)))
2841                 return -EINVAL;
2842
2843         if ((vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) &&
2844             CC(!kvm_pat_valid(vmcs12->host_ia32_pat)))
2845                 return -EINVAL;
2846
2847         if ((vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL) &&
2848             CC(!kvm_valid_perf_global_ctrl(vcpu_to_pmu(vcpu),
2849                                            vmcs12->host_ia32_perf_global_ctrl)))
2850                 return -EINVAL;
2851
2852 #ifdef CONFIG_X86_64
2853         ia32e = !!(vcpu->arch.efer & EFER_LMA);
2854 #else
2855         ia32e = false;
2856 #endif
2857
2858         if (ia32e) {
2859                 if (CC(!(vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)) ||
2860                     CC(!(vmcs12->host_cr4 & X86_CR4_PAE)))
2861                         return -EINVAL;
2862         } else {
2863                 if (CC(vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE) ||
2864                     CC(vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) ||
2865                     CC(vmcs12->host_cr4 & X86_CR4_PCIDE) ||
2866                     CC((vmcs12->host_rip) >> 32))
2867                         return -EINVAL;
2868         }
2869
2870         if (CC(vmcs12->host_cs_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2871             CC(vmcs12->host_ss_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2872             CC(vmcs12->host_ds_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2873             CC(vmcs12->host_es_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2874             CC(vmcs12->host_fs_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2875             CC(vmcs12->host_gs_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2876             CC(vmcs12->host_tr_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2877             CC(vmcs12->host_cs_selector == 0) ||
2878             CC(vmcs12->host_tr_selector == 0) ||
2879             CC(vmcs12->host_ss_selector == 0 && !ia32e))
2880                 return -EINVAL;
2881
2882         if (CC(is_noncanonical_address(vmcs12->host_fs_base, vcpu)) ||
2883             CC(is_noncanonical_address(vmcs12->host_gs_base, vcpu)) ||
2884             CC(is_noncanonical_address(vmcs12->host_gdtr_base, vcpu)) ||
2885             CC(is_noncanonical_address(vmcs12->host_idtr_base, vcpu)) ||
2886             CC(is_noncanonical_address(vmcs12->host_tr_base, vcpu)) ||
2887             CC(is_noncanonical_address(vmcs12->host_rip, vcpu)))
2888                 return -EINVAL;
2889
2890         /*
2891          * If the load IA32_EFER VM-exit control is 1, bits reserved in the
2892          * IA32_EFER MSR must be 0 in the field for that register. In addition,
2893          * the values of the LMA and LME bits in the field must each be that of
2894          * the host address-space size VM-exit control.
2895          */
2896         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
2897                 if (CC(!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer)) ||
2898                     CC(ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA)) ||
2899                     CC(ia32e != !!(vmcs12->host_ia32_efer & EFER_LME)))
2900                         return -EINVAL;
2901         }
2902
2903         return 0;
2904 }
2905
2906 static int nested_vmx_check_vmcs_link_ptr(struct kvm_vcpu *vcpu,
2907                                           struct vmcs12 *vmcs12)
2908 {
2909         int r = 0;
2910         struct vmcs12 *shadow;
2911         struct kvm_host_map map;
2912
2913         if (vmcs12->vmcs_link_pointer == -1ull)
2914                 return 0;
2915
2916         if (CC(!page_address_valid(vcpu, vmcs12->vmcs_link_pointer)))
2917                 return -EINVAL;
2918
2919         if (CC(kvm_vcpu_map(vcpu, gpa_to_gfn(vmcs12->vmcs_link_pointer), &map)))
2920                 return -EINVAL;
2921
2922         shadow = map.hva;
2923
2924         if (CC(shadow->hdr.revision_id != VMCS12_REVISION) ||
2925             CC(shadow->hdr.shadow_vmcs != nested_cpu_has_shadow_vmcs(vmcs12)))
2926                 r = -EINVAL;
2927
2928         kvm_vcpu_unmap(vcpu, &map, false);
2929         return r;
2930 }
2931
2932 /*
2933  * Checks related to Guest Non-register State
2934  */
2935 static int nested_check_guest_non_reg_state(struct vmcs12 *vmcs12)
2936 {
2937         if (CC(vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
2938                vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT))
2939                 return -EINVAL;
2940
2941         return 0;
2942 }
2943
2944 static int nested_vmx_check_guest_state(struct kvm_vcpu *vcpu,
2945                                         struct vmcs12 *vmcs12,
2946                                         u32 *exit_qual)
2947 {
2948         bool ia32e;
2949
2950         *exit_qual = ENTRY_FAIL_DEFAULT;
2951
2952         if (CC(!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0)) ||
2953             CC(!nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4)))
2954                 return -EINVAL;
2955
2956         if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) &&
2957             CC(!kvm_dr7_valid(vmcs12->guest_dr7)))
2958                 return -EINVAL;
2959
2960         if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT) &&
2961             CC(!kvm_pat_valid(vmcs12->guest_ia32_pat)))
2962                 return -EINVAL;
2963
2964         if (nested_vmx_check_vmcs_link_ptr(vcpu, vmcs12)) {
2965                 *exit_qual = ENTRY_FAIL_VMCS_LINK_PTR;
2966                 return -EINVAL;
2967         }
2968
2969         if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL) &&
2970             CC(!kvm_valid_perf_global_ctrl(vcpu_to_pmu(vcpu),
2971                                            vmcs12->guest_ia32_perf_global_ctrl)))
2972                 return -EINVAL;
2973
2974         /*
2975          * If the load IA32_EFER VM-entry control is 1, the following checks
2976          * are performed on the field for the IA32_EFER MSR:
2977          * - Bits reserved in the IA32_EFER MSR must be 0.
2978          * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
2979          *   the IA-32e mode guest VM-exit control. It must also be identical
2980          *   to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
2981          *   CR0.PG) is 1.
2982          */
2983         if (to_vmx(vcpu)->nested.nested_run_pending &&
2984             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {
2985                 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
2986                 if (CC(!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer)) ||
2987                     CC(ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA)) ||
2988                     CC(((vmcs12->guest_cr0 & X86_CR0_PG) &&
2989                      ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME))))
2990                         return -EINVAL;
2991         }
2992
2993         if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS) &&
2994             (CC(is_noncanonical_address(vmcs12->guest_bndcfgs & PAGE_MASK, vcpu)) ||
2995              CC((vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD))))
2996                 return -EINVAL;
2997
2998         if (nested_check_guest_non_reg_state(vmcs12))
2999                 return -EINVAL;
3000
3001         return 0;
3002 }
3003
3004 static int nested_vmx_check_vmentry_hw(struct kvm_vcpu *vcpu)
3005 {
3006         struct vcpu_vmx *vmx = to_vmx(vcpu);
3007         unsigned long cr3, cr4;
3008         bool vm_fail;
3009
3010         if (!nested_early_check)
3011                 return 0;
3012
3013         if (vmx->msr_autoload.host.nr)
3014                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
3015         if (vmx->msr_autoload.guest.nr)
3016                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
3017
3018         preempt_disable();
3019
3020         vmx_prepare_switch_to_guest(vcpu);
3021
3022         /*
3023          * Induce a consistency check VMExit by clearing bit 1 in GUEST_RFLAGS,
3024          * which is reserved to '1' by hardware.  GUEST_RFLAGS is guaranteed to
3025          * be written (by prepare_vmcs02()) before the "real" VMEnter, i.e.
3026          * there is no need to preserve other bits or save/restore the field.
3027          */
3028         vmcs_writel(GUEST_RFLAGS, 0);
3029
3030         cr3 = __get_current_cr3_fast();
3031         if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
3032                 vmcs_writel(HOST_CR3, cr3);
3033                 vmx->loaded_vmcs->host_state.cr3 = cr3;
3034         }
3035
3036         cr4 = cr4_read_shadow();
3037         if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
3038                 vmcs_writel(HOST_CR4, cr4);
3039                 vmx->loaded_vmcs->host_state.cr4 = cr4;
3040         }
3041
3042         asm(
3043                 "sub $%c[wordsize], %%" _ASM_SP "\n\t" /* temporarily adjust RSP for CALL */
3044                 "cmp %%" _ASM_SP ", %c[host_state_rsp](%[loaded_vmcs]) \n\t"
3045                 "je 1f \n\t"
3046                 __ex("vmwrite %%" _ASM_SP ", %[HOST_RSP]") "\n\t"
3047                 "mov %%" _ASM_SP ", %c[host_state_rsp](%[loaded_vmcs]) \n\t"
3048                 "1: \n\t"
3049                 "add $%c[wordsize], %%" _ASM_SP "\n\t" /* un-adjust RSP */
3050
3051                 /* Check if vmlaunch or vmresume is needed */
3052                 "cmpb $0, %c[launched](%[loaded_vmcs])\n\t"
3053
3054                 /*
3055                  * VMLAUNCH and VMRESUME clear RFLAGS.{CF,ZF} on VM-Exit, set
3056                  * RFLAGS.CF on VM-Fail Invalid and set RFLAGS.ZF on VM-Fail
3057                  * Valid.  vmx_vmenter() directly "returns" RFLAGS, and so the
3058                  * results of VM-Enter is captured via CC_{SET,OUT} to vm_fail.
3059                  */
3060                 "call vmx_vmenter\n\t"
3061
3062                 CC_SET(be)
3063               : ASM_CALL_CONSTRAINT, CC_OUT(be) (vm_fail)
3064               : [HOST_RSP]"r"((unsigned long)HOST_RSP),
3065                 [loaded_vmcs]"r"(vmx->loaded_vmcs),
3066                 [launched]"i"(offsetof(struct loaded_vmcs, launched)),
3067                 [host_state_rsp]"i"(offsetof(struct loaded_vmcs, host_state.rsp)),
3068                 [wordsize]"i"(sizeof(ulong))
3069               : "memory"
3070         );
3071
3072         if (vmx->msr_autoload.host.nr)
3073                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
3074         if (vmx->msr_autoload.guest.nr)
3075                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
3076
3077         if (vm_fail) {
3078                 u32 error = vmcs_read32(VM_INSTRUCTION_ERROR);
3079
3080                 preempt_enable();
3081
3082                 trace_kvm_nested_vmenter_failed(
3083                         "early hardware check VM-instruction error: ", error);
3084                 WARN_ON_ONCE(error != VMXERR_ENTRY_INVALID_CONTROL_FIELD);
3085                 return 1;
3086         }
3087
3088         /*
3089          * VMExit clears RFLAGS.IF and DR7, even on a consistency check.
3090          */
3091         local_irq_enable();
3092         if (hw_breakpoint_active())
3093                 set_debugreg(__this_cpu_read(cpu_dr7), 7);
3094         preempt_enable();
3095
3096         /*
3097          * A non-failing VMEntry means we somehow entered guest mode with
3098          * an illegal RIP, and that's just the tip of the iceberg.  There
3099          * is no telling what memory has been modified or what state has
3100          * been exposed to unknown code.  Hitting this all but guarantees
3101          * a (very critical) hardware issue.
3102          */
3103         WARN_ON(!(vmcs_read32(VM_EXIT_REASON) &
3104                 VMX_EXIT_REASONS_FAILED_VMENTRY));
3105
3106         return 0;
3107 }
3108
3109 static bool nested_get_vmcs12_pages(struct kvm_vcpu *vcpu)
3110 {
3111         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3112         struct vcpu_vmx *vmx = to_vmx(vcpu);
3113         struct kvm_host_map *map;
3114         struct page *page;
3115         u64 hpa;
3116
3117         /*
3118          * hv_evmcs may end up being not mapped after migration (when
3119          * L2 was running), map it here to make sure vmcs12 changes are
3120          * properly reflected.
3121          */
3122         if (vmx->nested.enlightened_vmcs_enabled && !vmx->nested.hv_evmcs) {
3123                 enum nested_evmptrld_status evmptrld_status =
3124                         nested_vmx_handle_enlightened_vmptrld(vcpu, false);
3125
3126                 if (evmptrld_status == EVMPTRLD_VMFAIL ||
3127                     evmptrld_status == EVMPTRLD_ERROR) {
3128                         pr_debug_ratelimited("%s: enlightened vmptrld failed\n",
3129                                              __func__);
3130                         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3131                         vcpu->run->internal.suberror =
3132                                 KVM_INTERNAL_ERROR_EMULATION;
3133                         vcpu->run->internal.ndata = 0;
3134                         return false;
3135                 }
3136         }
3137
3138         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
3139                 /*
3140                  * Translate L1 physical address to host physical
3141                  * address for vmcs02. Keep the page pinned, so this
3142                  * physical address remains valid. We keep a reference
3143                  * to it so we can release it later.
3144                  */
3145                 if (vmx->nested.apic_access_page) { /* shouldn't happen */
3146                         kvm_release_page_clean(vmx->nested.apic_access_page);
3147                         vmx->nested.apic_access_page = NULL;
3148                 }
3149                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->apic_access_addr);
3150                 if (!is_error_page(page)) {
3151                         vmx->nested.apic_access_page = page;
3152                         hpa = page_to_phys(vmx->nested.apic_access_page);
3153                         vmcs_write64(APIC_ACCESS_ADDR, hpa);
3154                 } else {
3155                         pr_debug_ratelimited("%s: no backing 'struct page' for APIC-access address in vmcs12\n",
3156                                              __func__);
3157                         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3158                         vcpu->run->internal.suberror =
3159                                 KVM_INTERNAL_ERROR_EMULATION;
3160                         vcpu->run->internal.ndata = 0;
3161                         return false;
3162                 }
3163         }
3164
3165         if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
3166                 map = &vmx->nested.virtual_apic_map;
3167
3168                 if (!kvm_vcpu_map(vcpu, gpa_to_gfn(vmcs12->virtual_apic_page_addr), map)) {
3169                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, pfn_to_hpa(map->pfn));
3170                 } else if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING) &&
3171                            nested_cpu_has(vmcs12, CPU_BASED_CR8_STORE_EXITING) &&
3172                            !nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
3173                         /*
3174                          * The processor will never use the TPR shadow, simply
3175                          * clear the bit from the execution control.  Such a
3176                          * configuration is useless, but it happens in tests.
3177                          * For any other configuration, failing the vm entry is
3178                          * _not_ what the processor does but it's basically the
3179                          * only possibility we have.
3180                          */
3181                         exec_controls_clearbit(vmx, CPU_BASED_TPR_SHADOW);
3182                 } else {
3183                         /*
3184                          * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR to
3185                          * force VM-Entry to fail.
3186                          */
3187                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
3188                 }
3189         }
3190
3191         if (nested_cpu_has_posted_intr(vmcs12)) {
3192                 map = &vmx->nested.pi_desc_map;
3193
3194                 if (!kvm_vcpu_map(vcpu, gpa_to_gfn(vmcs12->posted_intr_desc_addr), map)) {
3195                         vmx->nested.pi_desc =
3196                                 (struct pi_desc *)(((void *)map->hva) +
3197                                 offset_in_page(vmcs12->posted_intr_desc_addr));
3198                         vmcs_write64(POSTED_INTR_DESC_ADDR,
3199                                      pfn_to_hpa(map->pfn) + offset_in_page(vmcs12->posted_intr_desc_addr));
3200                 }
3201         }
3202         if (nested_vmx_prepare_msr_bitmap(vcpu, vmcs12))
3203                 exec_controls_setbit(vmx, CPU_BASED_USE_MSR_BITMAPS);
3204         else
3205                 exec_controls_clearbit(vmx, CPU_BASED_USE_MSR_BITMAPS);
3206         return true;
3207 }
3208
3209 /*
3210  * Intel's VMX Instruction Reference specifies a common set of prerequisites
3211  * for running VMX instructions (except VMXON, whose prerequisites are
3212  * slightly different). It also specifies what exception to inject otherwise.
3213  * Note that many of these exceptions have priority over VM exits, so they
3214  * don't have to be checked again here.
3215  */
3216 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
3217 {
3218         if (!to_vmx(vcpu)->nested.vmxon) {
3219                 kvm_queue_exception(vcpu, UD_VECTOR);
3220                 return 0;
3221         }
3222
3223         if (vmx_get_cpl(vcpu)) {
3224                 kvm_inject_gp(vcpu, 0);
3225                 return 0;
3226         }
3227
3228         return 1;
3229 }
3230
3231 static u8 vmx_has_apicv_interrupt(struct kvm_vcpu *vcpu)
3232 {
3233         u8 rvi = vmx_get_rvi();
3234         u8 vppr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_PROCPRI);
3235
3236         return ((rvi & 0xf0) > (vppr & 0xf0));
3237 }
3238
3239 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
3240                                    struct vmcs12 *vmcs12);
3241
3242 /*
3243  * If from_vmentry is false, this is being called from state restore (either RSM
3244  * or KVM_SET_NESTED_STATE).  Otherwise it's called from vmlaunch/vmresume.
3245  *
3246  * Returns:
3247  *      NVMX_VMENTRY_SUCCESS: Entered VMX non-root mode
3248  *      NVMX_VMENTRY_VMFAIL:  Consistency check VMFail
3249  *      NVMX_VMENTRY_VMEXIT:  Consistency check VMExit
3250  *      NVMX_VMENTRY_KVM_INTERNAL_ERROR: KVM internal error
3251  */
3252 enum nvmx_vmentry_status nested_vmx_enter_non_root_mode(struct kvm_vcpu *vcpu,
3253                                                         bool from_vmentry)
3254 {
3255         struct vcpu_vmx *vmx = to_vmx(vcpu);
3256         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3257         bool evaluate_pending_interrupts;
3258         u32 exit_reason = EXIT_REASON_INVALID_STATE;
3259         u32 exit_qual;
3260
3261         if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
3262                 kvm_vcpu_flush_tlb_current(vcpu);
3263
3264         evaluate_pending_interrupts = exec_controls_get(vmx) &
3265                 (CPU_BASED_INTR_WINDOW_EXITING | CPU_BASED_NMI_WINDOW_EXITING);
3266         if (likely(!evaluate_pending_interrupts) && kvm_vcpu_apicv_active(vcpu))
3267                 evaluate_pending_interrupts |= vmx_has_apicv_interrupt(vcpu);
3268
3269         if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
3270                 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
3271         if (kvm_mpx_supported() &&
3272                 !(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
3273                 vmx->nested.vmcs01_guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
3274
3275         /*
3276          * Overwrite vmcs01.GUEST_CR3 with L1's CR3 if EPT is disabled *and*
3277          * nested early checks are disabled.  In the event of a "late" VM-Fail,
3278          * i.e. a VM-Fail detected by hardware but not KVM, KVM must unwind its
3279          * software model to the pre-VMEntry host state.  When EPT is disabled,
3280          * GUEST_CR3 holds KVM's shadow CR3, not L1's "real" CR3, which causes
3281          * nested_vmx_restore_host_state() to corrupt vcpu->arch.cr3.  Stuffing
3282          * vmcs01.GUEST_CR3 results in the unwind naturally setting arch.cr3 to
3283          * the correct value.  Smashing vmcs01.GUEST_CR3 is safe because nested
3284          * VM-Exits, and the unwind, reset KVM's MMU, i.e. vmcs01.GUEST_CR3 is
3285          * guaranteed to be overwritten with a shadow CR3 prior to re-entering
3286          * L1.  Don't stuff vmcs01.GUEST_CR3 when using nested early checks as
3287          * KVM modifies vcpu->arch.cr3 if and only if the early hardware checks
3288          * pass, and early VM-Fails do not reset KVM's MMU, i.e. the VM-Fail
3289          * path would need to manually save/restore vmcs01.GUEST_CR3.
3290          */
3291         if (!enable_ept && !nested_early_check)
3292                 vmcs_writel(GUEST_CR3, vcpu->arch.cr3);
3293
3294         vmx_switch_vmcs(vcpu, &vmx->nested.vmcs02);
3295
3296         prepare_vmcs02_early(vmx, vmcs12);
3297
3298         if (from_vmentry) {
3299                 if (unlikely(!nested_get_vmcs12_pages(vcpu)))
3300                         return NVMX_VMENTRY_KVM_INTERNAL_ERROR;
3301
3302                 if (nested_vmx_check_vmentry_hw(vcpu)) {
3303                         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
3304                         return NVMX_VMENTRY_VMFAIL;
3305                 }
3306
3307                 if (nested_vmx_check_guest_state(vcpu, vmcs12, &exit_qual))
3308                         goto vmentry_fail_vmexit;
3309         }
3310
3311         enter_guest_mode(vcpu);
3312         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING)
3313                 vcpu->arch.tsc_offset += vmcs12->tsc_offset;
3314
3315         if (prepare_vmcs02(vcpu, vmcs12, &exit_qual))
3316                 goto vmentry_fail_vmexit_guest_mode;
3317
3318         if (from_vmentry) {
3319                 exit_reason = EXIT_REASON_MSR_LOAD_FAIL;
3320                 exit_qual = nested_vmx_load_msr(vcpu,
3321                                                 vmcs12->vm_entry_msr_load_addr,
3322                                                 vmcs12->vm_entry_msr_load_count);
3323                 if (exit_qual)
3324                         goto vmentry_fail_vmexit_guest_mode;
3325         } else {
3326                 /*
3327                  * The MMU is not initialized to point at the right entities yet and
3328                  * "get pages" would need to read data from the guest (i.e. we will
3329                  * need to perform gpa to hpa translation). Request a call
3330                  * to nested_get_vmcs12_pages before the next VM-entry.  The MSRs
3331                  * have already been set at vmentry time and should not be reset.
3332                  */
3333                 kvm_make_request(KVM_REQ_GET_VMCS12_PAGES, vcpu);
3334         }
3335
3336         /*
3337          * If L1 had a pending IRQ/NMI until it executed
3338          * VMLAUNCH/VMRESUME which wasn't delivered because it was
3339          * disallowed (e.g. interrupts disabled), L0 needs to
3340          * evaluate if this pending event should cause an exit from L2
3341          * to L1 or delivered directly to L2 (e.g. In case L1 don't
3342          * intercept EXTERNAL_INTERRUPT).
3343          *
3344          * Usually this would be handled by the processor noticing an
3345          * IRQ/NMI window request, or checking RVI during evaluation of
3346          * pending virtual interrupts.  However, this setting was done
3347          * on VMCS01 and now VMCS02 is active instead. Thus, we force L0
3348          * to perform pending event evaluation by requesting a KVM_REQ_EVENT.
3349          */
3350         if (unlikely(evaluate_pending_interrupts))
3351                 kvm_make_request(KVM_REQ_EVENT, vcpu);
3352
3353         /*
3354          * Do not start the preemption timer hrtimer until after we know
3355          * we are successful, so that only nested_vmx_vmexit needs to cancel
3356          * the timer.
3357          */
3358         vmx->nested.preemption_timer_expired = false;
3359         if (nested_cpu_has_preemption_timer(vmcs12))
3360                 vmx_start_preemption_timer(vcpu);
3361
3362         /*
3363          * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
3364          * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
3365          * returned as far as L1 is concerned. It will only return (and set
3366          * the success flag) when L2 exits (see nested_vmx_vmexit()).
3367          */
3368         return NVMX_VMENTRY_SUCCESS;
3369
3370         /*
3371          * A failed consistency check that leads to a VMExit during L1's
3372          * VMEnter to L2 is a variation of a normal VMexit, as explained in
3373          * 26.7 "VM-entry failures during or after loading guest state".
3374          */
3375 vmentry_fail_vmexit_guest_mode:
3376         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING)
3377                 vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
3378         leave_guest_mode(vcpu);
3379
3380 vmentry_fail_vmexit:
3381         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
3382
3383         if (!from_vmentry)
3384                 return NVMX_VMENTRY_VMEXIT;
3385
3386         load_vmcs12_host_state(vcpu, vmcs12);
3387         vmcs12->vm_exit_reason = exit_reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
3388         vmcs12->exit_qualification = exit_qual;
3389         if (enable_shadow_vmcs || vmx->nested.hv_evmcs)
3390                 vmx->nested.need_vmcs12_to_shadow_sync = true;
3391         return NVMX_VMENTRY_VMEXIT;
3392 }
3393
3394 /*
3395  * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
3396  * for running an L2 nested guest.
3397  */
3398 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
3399 {
3400         struct vmcs12 *vmcs12;
3401         enum nvmx_vmentry_status status;
3402         struct vcpu_vmx *vmx = to_vmx(vcpu);
3403         u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
3404         enum nested_evmptrld_status evmptrld_status;
3405
3406         if (!nested_vmx_check_permission(vcpu))
3407                 return 1;
3408
3409         evmptrld_status = nested_vmx_handle_enlightened_vmptrld(vcpu, launch);
3410         if (evmptrld_status == EVMPTRLD_ERROR) {
3411                 kvm_queue_exception(vcpu, UD_VECTOR);
3412                 return 1;
3413         } else if (evmptrld_status == EVMPTRLD_VMFAIL) {
3414                 return nested_vmx_failInvalid(vcpu);
3415         }
3416
3417         if (!vmx->nested.hv_evmcs && vmx->nested.current_vmptr == -1ull)
3418                 return nested_vmx_failInvalid(vcpu);
3419
3420         vmcs12 = get_vmcs12(vcpu);
3421
3422         /*
3423          * Can't VMLAUNCH or VMRESUME a shadow VMCS. Despite the fact
3424          * that there *is* a valid VMCS pointer, RFLAGS.CF is set
3425          * rather than RFLAGS.ZF, and no error number is stored to the
3426          * VM-instruction error field.
3427          */
3428         if (vmcs12->hdr.shadow_vmcs)
3429                 return nested_vmx_failInvalid(vcpu);
3430
3431         if (vmx->nested.hv_evmcs) {
3432                 copy_enlightened_to_vmcs12(vmx);
3433                 /* Enlightened VMCS doesn't have launch state */
3434                 vmcs12->launch_state = !launch;
3435         } else if (enable_shadow_vmcs) {
3436                 copy_shadow_to_vmcs12(vmx);
3437         }
3438
3439         /*
3440          * The nested entry process starts with enforcing various prerequisites
3441          * on vmcs12 as required by the Intel SDM, and act appropriately when
3442          * they fail: As the SDM explains, some conditions should cause the
3443          * instruction to fail, while others will cause the instruction to seem
3444          * to succeed, but return an EXIT_REASON_INVALID_STATE.
3445          * To speed up the normal (success) code path, we should avoid checking
3446          * for misconfigurations which will anyway be caught by the processor
3447          * when using the merged vmcs02.
3448          */
3449         if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS)
3450                 return nested_vmx_failValid(vcpu,
3451                         VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
3452
3453         if (vmcs12->launch_state == launch)
3454                 return nested_vmx_failValid(vcpu,
3455                         launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
3456                                : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
3457
3458         if (nested_vmx_check_controls(vcpu, vmcs12))
3459                 return nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
3460
3461         if (nested_vmx_check_host_state(vcpu, vmcs12))
3462                 return nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
3463
3464         /*
3465          * We're finally done with prerequisite checking, and can start with
3466          * the nested entry.
3467          */
3468         vmx->nested.nested_run_pending = 1;
3469         status = nested_vmx_enter_non_root_mode(vcpu, true);
3470         if (unlikely(status != NVMX_VMENTRY_SUCCESS))
3471                 goto vmentry_failed;
3472
3473         /* Hide L1D cache contents from the nested guest.  */
3474         vmx->vcpu.arch.l1tf_flush_l1d = true;
3475
3476         /*
3477          * Must happen outside of nested_vmx_enter_non_root_mode() as it will
3478          * also be used as part of restoring nVMX state for
3479          * snapshot restore (migration).
3480          *
3481          * In this flow, it is assumed that vmcs12 cache was
3482          * trasferred as part of captured nVMX state and should
3483          * therefore not be read from guest memory (which may not
3484          * exist on destination host yet).
3485          */
3486         nested_cache_shadow_vmcs12(vcpu, vmcs12);
3487
3488         /*
3489          * If we're entering a halted L2 vcpu and the L2 vcpu won't be
3490          * awakened by event injection or by an NMI-window VM-exit or
3491          * by an interrupt-window VM-exit, halt the vcpu.
3492          */
3493         if ((vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT) &&
3494             !(vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) &&
3495             !(vmcs12->cpu_based_vm_exec_control & CPU_BASED_NMI_WINDOW_EXITING) &&
3496             !((vmcs12->cpu_based_vm_exec_control & CPU_BASED_INTR_WINDOW_EXITING) &&
3497               (vmcs12->guest_rflags & X86_EFLAGS_IF))) {
3498                 vmx->nested.nested_run_pending = 0;
3499                 return kvm_vcpu_halt(vcpu);
3500         }
3501         return 1;
3502
3503 vmentry_failed:
3504         vmx->nested.nested_run_pending = 0;
3505         if (status == NVMX_VMENTRY_KVM_INTERNAL_ERROR)
3506                 return 0;
3507         if (status == NVMX_VMENTRY_VMEXIT)
3508                 return 1;
3509         WARN_ON_ONCE(status != NVMX_VMENTRY_VMFAIL);
3510         return nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
3511 }
3512
3513 /*
3514  * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
3515  * because L2 may have changed some cr0 bits directly (CR0_GUEST_HOST_MASK).
3516  * This function returns the new value we should put in vmcs12.guest_cr0.
3517  * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
3518  *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
3519  *     available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
3520  *     didn't trap the bit, because if L1 did, so would L0).
3521  *  2. Bits that L1 asked to trap (and therefore L0 also did) could not have
3522  *     been modified by L2, and L1 knows it. So just leave the old value of
3523  *     the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
3524  *     isn't relevant, because if L0 traps this bit it can set it to anything.
3525  *  3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
3526  *     changed these bits, and therefore they need to be updated, but L0
3527  *     didn't necessarily allow them to be changed in GUEST_CR0 - and rather
3528  *     put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
3529  */
3530 static inline unsigned long
3531 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
3532 {
3533         return
3534         /*1*/   (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
3535         /*2*/   (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
3536         /*3*/   (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
3537                         vcpu->arch.cr0_guest_owned_bits));
3538 }
3539
3540 static inline unsigned long
3541 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
3542 {
3543         return
3544         /*1*/   (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
3545         /*2*/   (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
3546         /*3*/   (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
3547                         vcpu->arch.cr4_guest_owned_bits));
3548 }
3549
3550 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
3551                                       struct vmcs12 *vmcs12)
3552 {
3553         u32 idt_vectoring;
3554         unsigned int nr;
3555
3556         if (vcpu->arch.exception.injected) {
3557                 nr = vcpu->arch.exception.nr;
3558                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
3559
3560                 if (kvm_exception_is_soft(nr)) {
3561                         vmcs12->vm_exit_instruction_len =
3562                                 vcpu->arch.event_exit_inst_len;
3563                         idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
3564                 } else
3565                         idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
3566
3567                 if (vcpu->arch.exception.has_error_code) {
3568                         idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
3569                         vmcs12->idt_vectoring_error_code =
3570                                 vcpu->arch.exception.error_code;
3571                 }
3572
3573                 vmcs12->idt_vectoring_info_field = idt_vectoring;
3574         } else if (vcpu->arch.nmi_injected) {
3575                 vmcs12->idt_vectoring_info_field =
3576                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
3577         } else if (vcpu->arch.interrupt.injected) {
3578                 nr = vcpu->arch.interrupt.nr;
3579                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
3580
3581                 if (vcpu->arch.interrupt.soft) {
3582                         idt_vectoring |= INTR_TYPE_SOFT_INTR;
3583                         vmcs12->vm_entry_instruction_len =
3584                                 vcpu->arch.event_exit_inst_len;
3585                 } else
3586                         idt_vectoring |= INTR_TYPE_EXT_INTR;
3587
3588                 vmcs12->idt_vectoring_info_field = idt_vectoring;
3589         }
3590 }
3591
3592
3593 void nested_mark_vmcs12_pages_dirty(struct kvm_vcpu *vcpu)
3594 {
3595         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3596         gfn_t gfn;
3597
3598         /*
3599          * Don't need to mark the APIC access page dirty; it is never
3600          * written to by the CPU during APIC virtualization.
3601          */
3602
3603         if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
3604                 gfn = vmcs12->virtual_apic_page_addr >> PAGE_SHIFT;
3605                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3606         }
3607
3608         if (nested_cpu_has_posted_intr(vmcs12)) {
3609                 gfn = vmcs12->posted_intr_desc_addr >> PAGE_SHIFT;
3610                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3611         }
3612 }
3613
3614 static void vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
3615 {
3616         struct vcpu_vmx *vmx = to_vmx(vcpu);
3617         int max_irr;
3618         void *vapic_page;
3619         u16 status;
3620
3621         if (!vmx->nested.pi_desc || !vmx->nested.pi_pending)
3622                 return;
3623
3624         vmx->nested.pi_pending = false;
3625         if (!pi_test_and_clear_on(vmx->nested.pi_desc))
3626                 return;
3627
3628         max_irr = find_last_bit((unsigned long *)vmx->nested.pi_desc->pir, 256);
3629         if (max_irr != 256) {
3630                 vapic_page = vmx->nested.virtual_apic_map.hva;
3631                 if (!vapic_page)
3632                         return;
3633
3634                 __kvm_apic_update_irr(vmx->nested.pi_desc->pir,
3635                         vapic_page, &max_irr);
3636                 status = vmcs_read16(GUEST_INTR_STATUS);
3637                 if ((u8)max_irr > ((u8)status & 0xff)) {
3638                         status &= ~0xff;
3639                         status |= (u8)max_irr;
3640                         vmcs_write16(GUEST_INTR_STATUS, status);
3641                 }
3642         }
3643
3644         nested_mark_vmcs12_pages_dirty(vcpu);
3645 }
3646
3647 static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
3648                                                unsigned long exit_qual)
3649 {
3650         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3651         unsigned int nr = vcpu->arch.exception.nr;
3652         u32 intr_info = nr | INTR_INFO_VALID_MASK;
3653
3654         if (vcpu->arch.exception.has_error_code) {
3655                 vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code;
3656                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
3657         }
3658
3659         if (kvm_exception_is_soft(nr))
3660                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
3661         else
3662                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
3663
3664         if (!(vmcs12->idt_vectoring_info_field & VECTORING_INFO_VALID_MASK) &&
3665             vmx_get_nmi_mask(vcpu))
3666                 intr_info |= INTR_INFO_UNBLOCK_NMI;
3667
3668         nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI, intr_info, exit_qual);
3669 }
3670
3671 /*
3672  * Returns true if a debug trap is pending delivery.
3673  *
3674  * In KVM, debug traps bear an exception payload. As such, the class of a #DB
3675  * exception may be inferred from the presence of an exception payload.
3676  */
3677 static inline bool vmx_pending_dbg_trap(struct kvm_vcpu *vcpu)
3678 {
3679         return vcpu->arch.exception.pending &&
3680                         vcpu->arch.exception.nr == DB_VECTOR &&
3681                         vcpu->arch.exception.payload;
3682 }
3683
3684 /*
3685  * Certain VM-exits set the 'pending debug exceptions' field to indicate a
3686  * recognized #DB (data or single-step) that has yet to be delivered. Since KVM
3687  * represents these debug traps with a payload that is said to be compatible
3688  * with the 'pending debug exceptions' field, write the payload to the VMCS
3689  * field if a VM-exit is delivered before the debug trap.
3690  */
3691 static void nested_vmx_update_pending_dbg(struct kvm_vcpu *vcpu)
3692 {
3693         if (vmx_pending_dbg_trap(vcpu))
3694                 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
3695                             vcpu->arch.exception.payload);
3696 }
3697
3698 static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
3699 {
3700         struct vcpu_vmx *vmx = to_vmx(vcpu);
3701         unsigned long exit_qual;
3702         bool block_nested_events =
3703             vmx->nested.nested_run_pending || kvm_event_needs_reinjection(vcpu);
3704         bool mtf_pending = vmx->nested.mtf_pending;
3705         struct kvm_lapic *apic = vcpu->arch.apic;
3706
3707         /*
3708          * Clear the MTF state. If a higher priority VM-exit is delivered first,
3709          * this state is discarded.
3710          */
3711         if (!block_nested_events)
3712                 vmx->nested.mtf_pending = false;
3713
3714         if (lapic_in_kernel(vcpu) &&
3715                 test_bit(KVM_APIC_INIT, &apic->pending_events)) {
3716                 if (block_nested_events)
3717                         return -EBUSY;
3718                 nested_vmx_update_pending_dbg(vcpu);
3719                 clear_bit(KVM_APIC_INIT, &apic->pending_events);
3720                 nested_vmx_vmexit(vcpu, EXIT_REASON_INIT_SIGNAL, 0, 0);
3721                 return 0;
3722         }
3723
3724         /*
3725          * Process any exceptions that are not debug traps before MTF.
3726          */
3727         if (vcpu->arch.exception.pending &&
3728             !vmx_pending_dbg_trap(vcpu) &&
3729             nested_vmx_check_exception(vcpu, &exit_qual)) {
3730                 if (block_nested_events)
3731                         return -EBUSY;
3732                 nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
3733                 return 0;
3734         }
3735
3736         if (mtf_pending) {
3737                 if (block_nested_events)
3738                         return -EBUSY;
3739                 nested_vmx_update_pending_dbg(vcpu);
3740                 nested_vmx_vmexit(vcpu, EXIT_REASON_MONITOR_TRAP_FLAG, 0, 0);
3741                 return 0;
3742         }
3743
3744         if (vcpu->arch.exception.pending &&
3745             nested_vmx_check_exception(vcpu, &exit_qual)) {
3746                 if (block_nested_events)
3747                         return -EBUSY;
3748                 nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
3749                 return 0;
3750         }
3751
3752         if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
3753             vmx->nested.preemption_timer_expired) {
3754                 if (block_nested_events)
3755                         return -EBUSY;
3756                 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
3757                 return 0;
3758         }
3759
3760         if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
3761                 if (block_nested_events)
3762                         return -EBUSY;
3763                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
3764                                   NMI_VECTOR | INTR_TYPE_NMI_INTR |
3765                                   INTR_INFO_VALID_MASK, 0);
3766                 /*
3767                  * The NMI-triggered VM exit counts as injection:
3768                  * clear this one and block further NMIs.
3769                  */
3770                 vcpu->arch.nmi_pending = 0;
3771                 vmx_set_nmi_mask(vcpu, true);
3772                 return 0;
3773         }
3774
3775         if (kvm_cpu_has_interrupt(vcpu) && nested_exit_on_intr(vcpu)) {
3776                 if (block_nested_events)
3777                         return -EBUSY;
3778                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
3779                 return 0;
3780         }
3781
3782         vmx_complete_nested_posted_interrupt(vcpu);
3783         return 0;
3784 }
3785
3786 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
3787 {
3788         ktime_t remaining =
3789                 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
3790         u64 value;
3791
3792         if (ktime_to_ns(remaining) <= 0)
3793                 return 0;
3794
3795         value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
3796         do_div(value, 1000000);
3797         return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
3798 }
3799
3800 static bool is_vmcs12_ext_field(unsigned long field)
3801 {
3802         switch (field) {
3803         case GUEST_ES_SELECTOR:
3804         case GUEST_CS_SELECTOR:
3805         case GUEST_SS_SELECTOR:
3806         case GUEST_DS_SELECTOR:
3807         case GUEST_FS_SELECTOR:
3808         case GUEST_GS_SELECTOR:
3809         case GUEST_LDTR_SELECTOR:
3810         case GUEST_TR_SELECTOR:
3811         case GUEST_ES_LIMIT:
3812         case GUEST_CS_LIMIT:
3813         case GUEST_SS_LIMIT:
3814         case GUEST_DS_LIMIT:
3815         case GUEST_FS_LIMIT:
3816         case GUEST_GS_LIMIT:
3817         case GUEST_LDTR_LIMIT:
3818         case GUEST_TR_LIMIT:
3819         case GUEST_GDTR_LIMIT:
3820         case GUEST_IDTR_LIMIT:
3821         case GUEST_ES_AR_BYTES:
3822         case GUEST_DS_AR_BYTES:
3823         case GUEST_FS_AR_BYTES:
3824         case GUEST_GS_AR_BYTES:
3825         case GUEST_LDTR_AR_BYTES:
3826         case GUEST_TR_AR_BYTES:
3827         case GUEST_ES_BASE:
3828         case GUEST_CS_BASE:
3829         case GUEST_SS_BASE:
3830         case GUEST_DS_BASE:
3831         case GUEST_FS_BASE:
3832         case GUEST_GS_BASE:
3833         case GUEST_LDTR_BASE:
3834         case GUEST_TR_BASE:
3835         case GUEST_GDTR_BASE:
3836         case GUEST_IDTR_BASE:
3837         case GUEST_PENDING_DBG_EXCEPTIONS:
3838         case GUEST_BNDCFGS:
3839                 return true;
3840         default:
3841                 break;
3842         }
3843
3844         return false;
3845 }
3846
3847 static void sync_vmcs02_to_vmcs12_rare(struct kvm_vcpu *vcpu,
3848                                        struct vmcs12 *vmcs12)
3849 {
3850         struct vcpu_vmx *vmx = to_vmx(vcpu);
3851
3852         vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
3853         vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
3854         vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
3855         vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
3856         vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
3857         vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
3858         vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
3859         vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
3860         vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
3861         vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
3862         vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
3863         vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
3864         vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
3865         vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
3866         vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
3867         vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
3868         vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
3869         vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
3870         vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
3871         vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
3872         vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
3873         vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
3874         vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
3875         vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
3876         vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
3877         vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
3878         vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
3879         vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
3880         vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
3881         vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
3882         vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
3883         vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
3884         vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
3885         vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
3886         vmcs12->guest_pending_dbg_exceptions =
3887                 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
3888         if (kvm_mpx_supported())
3889                 vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
3890
3891         vmx->nested.need_sync_vmcs02_to_vmcs12_rare = false;
3892 }
3893
3894 static void copy_vmcs02_to_vmcs12_rare(struct kvm_vcpu *vcpu,
3895                                        struct vmcs12 *vmcs12)
3896 {
3897         struct vcpu_vmx *vmx = to_vmx(vcpu);
3898         int cpu;
3899
3900         if (!vmx->nested.need_sync_vmcs02_to_vmcs12_rare)
3901                 return;
3902
3903
3904         WARN_ON_ONCE(vmx->loaded_vmcs != &vmx->vmcs01);
3905
3906         cpu = get_cpu();
3907         vmx->loaded_vmcs = &vmx->nested.vmcs02;
3908         vmx_vcpu_load(&vmx->vcpu, cpu);
3909
3910         sync_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
3911
3912         vmx->loaded_vmcs = &vmx->vmcs01;
3913         vmx_vcpu_load(&vmx->vcpu, cpu);
3914         put_cpu();
3915 }
3916
3917 /*
3918  * Update the guest state fields of vmcs12 to reflect changes that
3919  * occurred while L2 was running. (The "IA-32e mode guest" bit of the
3920  * VM-entry controls is also updated, since this is really a guest
3921  * state bit.)
3922  */
3923 static void sync_vmcs02_to_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
3924 {
3925         struct vcpu_vmx *vmx = to_vmx(vcpu);
3926
3927         if (vmx->nested.hv_evmcs)
3928                 sync_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
3929
3930         vmx->nested.need_sync_vmcs02_to_vmcs12_rare = !vmx->nested.hv_evmcs;
3931
3932         vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
3933         vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
3934
3935         vmcs12->guest_rsp = kvm_rsp_read(vcpu);
3936         vmcs12->guest_rip = kvm_rip_read(vcpu);
3937         vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
3938
3939         vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
3940         vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
3941
3942         vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
3943         vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
3944         vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
3945
3946         vmcs12->guest_interruptibility_info =
3947                 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
3948
3949         if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
3950                 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
3951         else
3952                 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
3953
3954         if (nested_cpu_has_preemption_timer(vmcs12) &&
3955             vmcs12->vm_exit_controls & VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
3956                         vmcs12->vmx_preemption_timer_value =
3957                                 vmx_get_preemption_timer_value(vcpu);
3958
3959         /*
3960          * In some cases (usually, nested EPT), L2 is allowed to change its
3961          * own CR3 without exiting. If it has changed it, we must keep it.
3962          * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
3963          * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
3964          *
3965          * Additionally, restore L2's PDPTR to vmcs12.
3966          */
3967         if (enable_ept) {
3968                 vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
3969                 if (nested_cpu_has_ept(vmcs12) && is_pae_paging(vcpu)) {
3970                         vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
3971                         vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
3972                         vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
3973                         vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
3974                 }
3975         }
3976
3977         vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
3978
3979         if (nested_cpu_has_vid(vmcs12))
3980                 vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
3981
3982         vmcs12->vm_entry_controls =
3983                 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
3984                 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
3985
3986         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS)
3987                 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
3988
3989         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
3990                 vmcs12->guest_ia32_efer = vcpu->arch.efer;
3991 }
3992
3993 /*
3994  * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
3995  * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
3996  * and this function updates it to reflect the changes to the guest state while
3997  * L2 was running (and perhaps made some exits which were handled directly by L0
3998  * without going back to L1), and to reflect the exit reason.
3999  * Note that we do not have to copy here all VMCS fields, just those that
4000  * could have changed by the L2 guest or the exit - i.e., the guest-state and
4001  * exit-information fields only. Other fields are modified by L1 with VMWRITE,
4002  * which already writes to vmcs12 directly.
4003  */
4004 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
4005                            u32 vm_exit_reason, u32 exit_intr_info,
4006                            unsigned long exit_qualification)
4007 {
4008         /* update exit information fields: */
4009         vmcs12->vm_exit_reason = vm_exit_reason;
4010         vmcs12->exit_qualification = exit_qualification;
4011         vmcs12->vm_exit_intr_info = exit_intr_info;
4012
4013         vmcs12->idt_vectoring_info_field = 0;
4014         vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4015         vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
4016
4017         if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
4018                 vmcs12->launch_state = 1;
4019
4020                 /* vm_entry_intr_info_field is cleared on exit. Emulate this
4021                  * instead of reading the real value. */
4022                 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
4023
4024                 /*
4025                  * Transfer the event that L0 or L1 may wanted to inject into
4026                  * L2 to IDT_VECTORING_INFO_FIELD.
4027                  */
4028                 vmcs12_save_pending_event(vcpu, vmcs12);
4029
4030                 /*
4031                  * According to spec, there's no need to store the guest's
4032                  * MSRs if the exit is due to a VM-entry failure that occurs
4033                  * during or after loading the guest state. Since this exit
4034                  * does not fall in that category, we need to save the MSRs.
4035                  */
4036                 if (nested_vmx_store_msr(vcpu,
4037                                          vmcs12->vm_exit_msr_store_addr,
4038                                          vmcs12->vm_exit_msr_store_count))
4039                         nested_vmx_abort(vcpu,
4040                                          VMX_ABORT_SAVE_GUEST_MSR_FAIL);
4041         }
4042
4043         /*
4044          * Drop what we picked up for L2 via vmx_complete_interrupts. It is
4045          * preserved above and would only end up incorrectly in L1.
4046          */
4047         vcpu->arch.nmi_injected = false;
4048         kvm_clear_exception_queue(vcpu);
4049         kvm_clear_interrupt_queue(vcpu);
4050 }
4051
4052 /*
4053  * A part of what we need to when the nested L2 guest exits and we want to
4054  * run its L1 parent, is to reset L1's guest state to the host state specified
4055  * in vmcs12.
4056  * This function is to be called not only on normal nested exit, but also on
4057  * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
4058  * Failures During or After Loading Guest State").
4059  * This function should be called when the active VMCS is L1's (vmcs01).
4060  */
4061 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
4062                                    struct vmcs12 *vmcs12)
4063 {
4064         struct kvm_segment seg;
4065         u32 entry_failure_code;
4066
4067         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
4068                 vcpu->arch.efer = vmcs12->host_ia32_efer;
4069         else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
4070                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
4071         else
4072                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
4073         vmx_set_efer(vcpu, vcpu->arch.efer);
4074
4075         kvm_rsp_write(vcpu, vmcs12->host_rsp);
4076         kvm_rip_write(vcpu, vmcs12->host_rip);
4077         vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
4078         vmx_set_interrupt_shadow(vcpu, 0);
4079
4080         /*
4081          * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
4082          * actually changed, because vmx_set_cr0 refers to efer set above.
4083          *
4084          * CR0_GUEST_HOST_MASK is already set in the original vmcs01
4085          * (KVM doesn't change it);
4086          */
4087         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
4088         vmx_set_cr0(vcpu, vmcs12->host_cr0);
4089
4090         /* Same as above - no reason to call set_cr4_guest_host_mask().  */
4091         vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
4092         vmx_set_cr4(vcpu, vmcs12->host_cr4);
4093
4094         nested_ept_uninit_mmu_context(vcpu);
4095
4096         /*
4097          * Only PDPTE load can fail as the value of cr3 was checked on entry and
4098          * couldn't have changed.
4099          */
4100         if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
4101                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
4102
4103         if (!enable_ept)
4104                 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
4105
4106         nested_vmx_transition_tlb_flush(vcpu, vmcs12, false);
4107
4108         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
4109         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
4110         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
4111         vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
4112         vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
4113         vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
4114         vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
4115
4116         /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1.  */
4117         if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
4118                 vmcs_write64(GUEST_BNDCFGS, 0);
4119
4120         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
4121                 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
4122                 vcpu->arch.pat = vmcs12->host_ia32_pat;
4123         }
4124         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
4125                 WARN_ON_ONCE(kvm_set_msr(vcpu, MSR_CORE_PERF_GLOBAL_CTRL,
4126                                          vmcs12->host_ia32_perf_global_ctrl));
4127
4128         /* Set L1 segment info according to Intel SDM
4129             27.5.2 Loading Host Segment and Descriptor-Table Registers */
4130         seg = (struct kvm_segment) {
4131                 .base = 0,
4132                 .limit = 0xFFFFFFFF,
4133                 .selector = vmcs12->host_cs_selector,
4134                 .type = 11,
4135                 .present = 1,
4136                 .s = 1,
4137                 .g = 1
4138         };
4139         if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
4140                 seg.l = 1;
4141         else
4142                 seg.db = 1;
4143         vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
4144         seg = (struct kvm_segment) {
4145                 .base = 0,
4146                 .limit = 0xFFFFFFFF,
4147                 .type = 3,
4148                 .present = 1,
4149                 .s = 1,
4150                 .db = 1,
4151                 .g = 1
4152         };
4153         seg.selector = vmcs12->host_ds_selector;
4154         vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
4155         seg.selector = vmcs12->host_es_selector;
4156         vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
4157         seg.selector = vmcs12->host_ss_selector;
4158         vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
4159         seg.selector = vmcs12->host_fs_selector;
4160         seg.base = vmcs12->host_fs_base;
4161         vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
4162         seg.selector = vmcs12->host_gs_selector;
4163         seg.base = vmcs12->host_gs_base;
4164         vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
4165         seg = (struct kvm_segment) {
4166                 .base = vmcs12->host_tr_base,
4167                 .limit = 0x67,
4168                 .selector = vmcs12->host_tr_selector,
4169                 .type = 11,
4170                 .present = 1
4171         };
4172         vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
4173
4174         kvm_set_dr(vcpu, 7, 0x400);
4175         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4176
4177         if (cpu_has_vmx_msr_bitmap())
4178                 vmx_update_msr_bitmap(vcpu);
4179
4180         if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
4181                                 vmcs12->vm_exit_msr_load_count))
4182                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
4183 }
4184
4185 static inline u64 nested_vmx_get_vmcs01_guest_efer(struct vcpu_vmx *vmx)
4186 {
4187         struct shared_msr_entry *efer_msr;
4188         unsigned int i;
4189
4190         if (vm_entry_controls_get(vmx) & VM_ENTRY_LOAD_IA32_EFER)
4191                 return vmcs_read64(GUEST_IA32_EFER);
4192
4193         if (cpu_has_load_ia32_efer())
4194                 return host_efer;
4195
4196         for (i = 0; i < vmx->msr_autoload.guest.nr; ++i) {
4197                 if (vmx->msr_autoload.guest.val[i].index == MSR_EFER)
4198                         return vmx->msr_autoload.guest.val[i].value;
4199         }
4200
4201         efer_msr = find_msr_entry(vmx, MSR_EFER);
4202         if (efer_msr)
4203                 return efer_msr->data;
4204
4205         return host_efer;
4206 }
4207
4208 static void nested_vmx_restore_host_state(struct kvm_vcpu *vcpu)
4209 {
4210         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4211         struct vcpu_vmx *vmx = to_vmx(vcpu);
4212         struct vmx_msr_entry g, h;
4213         gpa_t gpa;
4214         u32 i, j;
4215
4216         vcpu->arch.pat = vmcs_read64(GUEST_IA32_PAT);
4217
4218         if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
4219                 /*
4220                  * L1's host DR7 is lost if KVM_GUESTDBG_USE_HW_BP is set
4221                  * as vmcs01.GUEST_DR7 contains a userspace defined value
4222                  * and vcpu->arch.dr7 is not squirreled away before the
4223                  * nested VMENTER (not worth adding a variable in nested_vmx).
4224                  */
4225                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
4226                         kvm_set_dr(vcpu, 7, DR7_FIXED_1);
4227                 else
4228                         WARN_ON(kvm_set_dr(vcpu, 7, vmcs_readl(GUEST_DR7)));
4229         }
4230
4231         /*
4232          * Note that calling vmx_set_{efer,cr0,cr4} is important as they
4233          * handle a variety of side effects to KVM's software model.
4234          */
4235         vmx_set_efer(vcpu, nested_vmx_get_vmcs01_guest_efer(vmx));
4236
4237         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
4238         vmx_set_cr0(vcpu, vmcs_readl(CR0_READ_SHADOW));
4239
4240         vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
4241         vmx_set_cr4(vcpu, vmcs_readl(CR4_READ_SHADOW));
4242
4243         nested_ept_uninit_mmu_context(vcpu);
4244         vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
4245         kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
4246
4247         /*
4248          * Use ept_save_pdptrs(vcpu) to load the MMU's cached PDPTRs
4249          * from vmcs01 (if necessary).  The PDPTRs are not loaded on
4250          * VMFail, like everything else we just need to ensure our
4251          * software model is up-to-date.
4252          */
4253         if (enable_ept)
4254                 ept_save_pdptrs(vcpu);
4255
4256         kvm_mmu_reset_context(vcpu);
4257
4258         if (cpu_has_vmx_msr_bitmap())
4259                 vmx_update_msr_bitmap(vcpu);
4260
4261         /*
4262          * This nasty bit of open coding is a compromise between blindly
4263          * loading L1's MSRs using the exit load lists (incorrect emulation
4264          * of VMFail), leaving the nested VM's MSRs in the software model
4265          * (incorrect behavior) and snapshotting the modified MSRs (too
4266          * expensive since the lists are unbound by hardware).  For each
4267          * MSR that was (prematurely) loaded from the nested VMEntry load
4268          * list, reload it from the exit load list if it exists and differs
4269          * from the guest value.  The intent is to stuff host state as
4270          * silently as possible, not to fully process the exit load list.
4271          */
4272         for (i = 0; i < vmcs12->vm_entry_msr_load_count; i++) {
4273                 gpa = vmcs12->vm_entry_msr_load_addr + (i * sizeof(g));
4274                 if (kvm_vcpu_read_guest(vcpu, gpa, &g, sizeof(g))) {
4275                         pr_debug_ratelimited(
4276                                 "%s read MSR index failed (%u, 0x%08llx)\n",
4277                                 __func__, i, gpa);
4278                         goto vmabort;
4279                 }
4280
4281                 for (j = 0; j < vmcs12->vm_exit_msr_load_count; j++) {
4282                         gpa = vmcs12->vm_exit_msr_load_addr + (j * sizeof(h));
4283                         if (kvm_vcpu_read_guest(vcpu, gpa, &h, sizeof(h))) {
4284                                 pr_debug_ratelimited(
4285                                         "%s read MSR failed (%u, 0x%08llx)\n",
4286                                         __func__, j, gpa);
4287                                 goto vmabort;
4288                         }
4289                         if (h.index != g.index)
4290                                 continue;
4291                         if (h.value == g.value)
4292                                 break;
4293
4294                         if (nested_vmx_load_msr_check(vcpu, &h)) {
4295                                 pr_debug_ratelimited(
4296                                         "%s check failed (%u, 0x%x, 0x%x)\n",
4297                                         __func__, j, h.index, h.reserved);
4298                                 goto vmabort;
4299                         }
4300
4301                         if (kvm_set_msr(vcpu, h.index, h.value)) {
4302                                 pr_debug_ratelimited(
4303                                         "%s WRMSR failed (%u, 0x%x, 0x%llx)\n",
4304                                         __func__, j, h.index, h.value);
4305                                 goto vmabort;
4306                         }
4307                 }
4308         }
4309
4310         return;
4311
4312 vmabort:
4313         nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
4314 }
4315
4316 /*
4317  * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
4318  * and modify vmcs12 to make it see what it would expect to see there if
4319  * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
4320  */
4321 void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 vm_exit_reason,
4322                        u32 exit_intr_info, unsigned long exit_qualification)
4323 {
4324         struct vcpu_vmx *vmx = to_vmx(vcpu);
4325         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4326
4327         /* trying to cancel vmlaunch/vmresume is a bug */
4328         WARN_ON_ONCE(vmx->nested.nested_run_pending);
4329
4330         /* Service the TLB flush request for L2 before switching to L1. */
4331         if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
4332                 kvm_vcpu_flush_tlb_current(vcpu);
4333
4334         leave_guest_mode(vcpu);
4335
4336         if (nested_cpu_has_preemption_timer(vmcs12))
4337                 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
4338
4339         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING)
4340                 vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
4341
4342         if (likely(!vmx->fail)) {
4343                 sync_vmcs02_to_vmcs12(vcpu, vmcs12);
4344
4345                 if (vm_exit_reason != -1)
4346                         prepare_vmcs12(vcpu, vmcs12, vm_exit_reason,
4347                                        exit_intr_info, exit_qualification);
4348
4349                 /*
4350                  * Must happen outside of sync_vmcs02_to_vmcs12() as it will
4351                  * also be used to capture vmcs12 cache as part of
4352                  * capturing nVMX state for snapshot (migration).
4353                  *
4354                  * Otherwise, this flush will dirty guest memory at a
4355                  * point it is already assumed by user-space to be
4356                  * immutable.
4357                  */
4358                 nested_flush_cached_shadow_vmcs12(vcpu, vmcs12);
4359         } else {
4360                 /*
4361                  * The only expected VM-instruction error is "VM entry with
4362                  * invalid control field(s)." Anything else indicates a
4363                  * problem with L0.  And we should never get here with a
4364                  * VMFail of any type if early consistency checks are enabled.
4365                  */
4366                 WARN_ON_ONCE(vmcs_read32(VM_INSTRUCTION_ERROR) !=
4367                              VMXERR_ENTRY_INVALID_CONTROL_FIELD);
4368                 WARN_ON_ONCE(nested_early_check);
4369         }
4370
4371         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
4372
4373         /* Update any VMCS fields that might have changed while L2 ran */
4374         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
4375         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
4376         vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
4377         if (vmx->nested.l1_tpr_threshold != -1)
4378                 vmcs_write32(TPR_THRESHOLD, vmx->nested.l1_tpr_threshold);
4379
4380         if (kvm_has_tsc_control)
4381                 decache_tsc_multiplier(vmx);
4382
4383         if (vmx->nested.change_vmcs01_virtual_apic_mode) {
4384                 vmx->nested.change_vmcs01_virtual_apic_mode = false;
4385                 vmx_set_virtual_apic_mode(vcpu);
4386         }
4387
4388         /* Unpin physical memory we referred to in vmcs02 */
4389         if (vmx->nested.apic_access_page) {
4390                 kvm_release_page_clean(vmx->nested.apic_access_page);
4391                 vmx->nested.apic_access_page = NULL;
4392         }
4393         kvm_vcpu_unmap(vcpu, &vmx->nested.virtual_apic_map, true);
4394         kvm_vcpu_unmap(vcpu, &vmx->nested.pi_desc_map, true);
4395         vmx->nested.pi_desc = NULL;
4396
4397         if (vmx->nested.reload_vmcs01_apic_access_page) {
4398                 vmx->nested.reload_vmcs01_apic_access_page = false;
4399                 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4400         }
4401
4402         if ((vm_exit_reason != -1) &&
4403             (enable_shadow_vmcs || vmx->nested.hv_evmcs))
4404                 vmx->nested.need_vmcs12_to_shadow_sync = true;
4405
4406         /* in case we halted in L2 */
4407         vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
4408
4409         if (likely(!vmx->fail)) {
4410                 if ((u16)vm_exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT &&
4411                     nested_exit_intr_ack_set(vcpu)) {
4412                         int irq = kvm_cpu_get_interrupt(vcpu);
4413                         WARN_ON(irq < 0);
4414                         vmcs12->vm_exit_intr_info = irq |
4415                                 INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
4416                 }
4417
4418                 if (vm_exit_reason != -1)
4419                         trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
4420                                                        vmcs12->exit_qualification,
4421                                                        vmcs12->idt_vectoring_info_field,
4422                                                        vmcs12->vm_exit_intr_info,
4423                                                        vmcs12->vm_exit_intr_error_code,
4424                                                        KVM_ISA_VMX);
4425
4426                 load_vmcs12_host_state(vcpu, vmcs12);
4427
4428                 return;
4429         }
4430
4431         /*
4432          * After an early L2 VM-entry failure, we're now back
4433          * in L1 which thinks it just finished a VMLAUNCH or
4434          * VMRESUME instruction, so we need to set the failure
4435          * flag and the VM-instruction error field of the VMCS
4436          * accordingly, and skip the emulated instruction.
4437          */
4438         (void)nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
4439
4440         /*
4441          * Restore L1's host state to KVM's software model.  We're here
4442          * because a consistency check was caught by hardware, which
4443          * means some amount of guest state has been propagated to KVM's
4444          * model and needs to be unwound to the host's state.
4445          */
4446         nested_vmx_restore_host_state(vcpu);
4447
4448         vmx->fail = 0;
4449 }
4450
4451 /*
4452  * Decode the memory-address operand of a vmx instruction, as recorded on an
4453  * exit caused by such an instruction (run by a guest hypervisor).
4454  * On success, returns 0. When the operand is invalid, returns 1 and throws
4455  * #UD, #GP, or #SS.
4456  */
4457 int get_vmx_mem_address(struct kvm_vcpu *vcpu, unsigned long exit_qualification,
4458                         u32 vmx_instruction_info, bool wr, int len, gva_t *ret)
4459 {
4460         gva_t off;
4461         bool exn;
4462         struct kvm_segment s;
4463
4464         /*
4465          * According to Vol. 3B, "Information for VM Exits Due to Instruction
4466          * Execution", on an exit, vmx_instruction_info holds most of the
4467          * addressing components of the operand. Only the displacement part
4468          * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
4469          * For how an actual address is calculated from all these components,
4470          * refer to Vol. 1, "Operand Addressing".
4471          */
4472         int  scaling = vmx_instruction_info & 3;
4473         int  addr_size = (vmx_instruction_info >> 7) & 7;
4474         bool is_reg = vmx_instruction_info & (1u << 10);
4475         int  seg_reg = (vmx_instruction_info >> 15) & 7;
4476         int  index_reg = (vmx_instruction_info >> 18) & 0xf;
4477         bool index_is_valid = !(vmx_instruction_info & (1u << 22));
4478         int  base_reg       = (vmx_instruction_info >> 23) & 0xf;
4479         bool base_is_valid  = !(vmx_instruction_info & (1u << 27));
4480
4481         if (is_reg) {
4482                 kvm_queue_exception(vcpu, UD_VECTOR);
4483                 return 1;
4484         }
4485
4486         /* Addr = segment_base + offset */
4487         /* offset = base + [index * scale] + displacement */
4488         off = exit_qualification; /* holds the displacement */
4489         if (addr_size == 1)
4490                 off = (gva_t)sign_extend64(off, 31);
4491         else if (addr_size == 0)
4492                 off = (gva_t)sign_extend64(off, 15);
4493         if (base_is_valid)
4494                 off += kvm_register_read(vcpu, base_reg);
4495         if (index_is_valid)
4496                 off += kvm_register_read(vcpu, index_reg) << scaling;
4497         vmx_get_segment(vcpu, &s, seg_reg);
4498
4499         /*
4500          * The effective address, i.e. @off, of a memory operand is truncated
4501          * based on the address size of the instruction.  Note that this is
4502          * the *effective address*, i.e. the address prior to accounting for
4503          * the segment's base.
4504          */
4505         if (addr_size == 1) /* 32 bit */
4506                 off &= 0xffffffff;
4507         else if (addr_size == 0) /* 16 bit */
4508                 off &= 0xffff;
4509
4510         /* Checks for #GP/#SS exceptions. */
4511         exn = false;
4512         if (is_long_mode(vcpu)) {
4513                 /*
4514                  * The virtual/linear address is never truncated in 64-bit
4515                  * mode, e.g. a 32-bit address size can yield a 64-bit virtual
4516                  * address when using FS/GS with a non-zero base.
4517                  */
4518                 if (seg_reg == VCPU_SREG_FS || seg_reg == VCPU_SREG_GS)
4519                         *ret = s.base + off;
4520                 else
4521                         *ret = off;
4522
4523                 /* Long mode: #GP(0)/#SS(0) if the memory address is in a
4524                  * non-canonical form. This is the only check on the memory
4525                  * destination for long mode!
4526                  */
4527                 exn = is_noncanonical_address(*ret, vcpu);
4528         } else {
4529                 /*
4530                  * When not in long mode, the virtual/linear address is
4531                  * unconditionally truncated to 32 bits regardless of the
4532                  * address size.
4533                  */
4534                 *ret = (s.base + off) & 0xffffffff;
4535
4536                 /* Protected mode: apply checks for segment validity in the
4537                  * following order:
4538                  * - segment type check (#GP(0) may be thrown)
4539                  * - usability check (#GP(0)/#SS(0))
4540                  * - limit check (#GP(0)/#SS(0))
4541                  */
4542                 if (wr)
4543                         /* #GP(0) if the destination operand is located in a
4544                          * read-only data segment or any code segment.
4545                          */
4546                         exn = ((s.type & 0xa) == 0 || (s.type & 8));
4547                 else
4548                         /* #GP(0) if the source operand is located in an
4549                          * execute-only code segment
4550                          */
4551                         exn = ((s.type & 0xa) == 8);
4552                 if (exn) {
4553                         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
4554                         return 1;
4555                 }
4556                 /* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
4557                  */
4558                 exn = (s.unusable != 0);
4559
4560                 /*
4561                  * Protected mode: #GP(0)/#SS(0) if the memory operand is
4562                  * outside the segment limit.  All CPUs that support VMX ignore
4563                  * limit checks for flat segments, i.e. segments with base==0,
4564                  * limit==0xffffffff and of type expand-up data or code.
4565                  */
4566                 if (!(s.base == 0 && s.limit == 0xffffffff &&
4567                      ((s.type & 8) || !(s.type & 4))))
4568                         exn = exn || ((u64)off + len - 1 > s.limit);
4569         }
4570         if (exn) {
4571                 kvm_queue_exception_e(vcpu,
4572                                       seg_reg == VCPU_SREG_SS ?
4573                                                 SS_VECTOR : GP_VECTOR,
4574                                       0);
4575                 return 1;
4576         }
4577
4578         return 0;
4579 }
4580
4581 void nested_vmx_pmu_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
4582 {
4583         struct vcpu_vmx *vmx;
4584
4585         if (!nested_vmx_allowed(vcpu))
4586                 return;
4587
4588         vmx = to_vmx(vcpu);
4589         if (kvm_x86_ops.pmu_ops->is_valid_msr(vcpu, MSR_CORE_PERF_GLOBAL_CTRL)) {
4590                 vmx->nested.msrs.entry_ctls_high |=
4591                                 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
4592                 vmx->nested.msrs.exit_ctls_high |=
4593                                 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
4594         } else {
4595                 vmx->nested.msrs.entry_ctls_high &=
4596                                 ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
4597                 vmx->nested.msrs.exit_ctls_high &=
4598                                 ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
4599         }
4600 }
4601
4602 static int nested_vmx_get_vmptr(struct kvm_vcpu *vcpu, gpa_t *vmpointer)
4603 {
4604         gva_t gva;
4605         struct x86_exception e;
4606
4607         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
4608                                 vmcs_read32(VMX_INSTRUCTION_INFO), false,
4609                                 sizeof(*vmpointer), &gva))
4610                 return 1;
4611
4612         if (kvm_read_guest_virt(vcpu, gva, vmpointer, sizeof(*vmpointer), &e)) {
4613                 kvm_inject_emulated_page_fault(vcpu, &e);
4614                 return 1;
4615         }
4616
4617         return 0;
4618 }
4619
4620 /*
4621  * Allocate a shadow VMCS and associate it with the currently loaded
4622  * VMCS, unless such a shadow VMCS already exists. The newly allocated
4623  * VMCS is also VMCLEARed, so that it is ready for use.
4624  */
4625 static struct vmcs *alloc_shadow_vmcs(struct kvm_vcpu *vcpu)
4626 {
4627         struct vcpu_vmx *vmx = to_vmx(vcpu);
4628         struct loaded_vmcs *loaded_vmcs = vmx->loaded_vmcs;
4629
4630         /*
4631          * We should allocate a shadow vmcs for vmcs01 only when L1
4632          * executes VMXON and free it when L1 executes VMXOFF.
4633          * As it is invalid to execute VMXON twice, we shouldn't reach
4634          * here when vmcs01 already have an allocated shadow vmcs.
4635          */
4636         WARN_ON(loaded_vmcs == &vmx->vmcs01 && loaded_vmcs->shadow_vmcs);
4637
4638         if (!loaded_vmcs->shadow_vmcs) {
4639                 loaded_vmcs->shadow_vmcs = alloc_vmcs(true);
4640                 if (loaded_vmcs->shadow_vmcs)
4641                         vmcs_clear(loaded_vmcs->shadow_vmcs);
4642         }
4643         return loaded_vmcs->shadow_vmcs;
4644 }
4645
4646 static int enter_vmx_operation(struct kvm_vcpu *vcpu)
4647 {
4648         struct vcpu_vmx *vmx = to_vmx(vcpu);
4649         int r;
4650
4651         r = alloc_loaded_vmcs(&vmx->nested.vmcs02);
4652         if (r < 0)
4653                 goto out_vmcs02;
4654
4655         vmx->nested.cached_vmcs12 = kzalloc(VMCS12_SIZE, GFP_KERNEL_ACCOUNT);
4656         if (!vmx->nested.cached_vmcs12)
4657                 goto out_cached_vmcs12;
4658
4659         vmx->nested.cached_shadow_vmcs12 = kzalloc(VMCS12_SIZE, GFP_KERNEL_ACCOUNT);
4660         if (!vmx->nested.cached_shadow_vmcs12)
4661                 goto out_cached_shadow_vmcs12;
4662
4663         if (enable_shadow_vmcs && !alloc_shadow_vmcs(vcpu))
4664                 goto out_shadow_vmcs;
4665
4666         hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
4667                      HRTIMER_MODE_REL_PINNED);
4668         vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
4669
4670         vmx->nested.vpid02 = allocate_vpid();
4671
4672         vmx->nested.vmcs02_initialized = false;
4673         vmx->nested.vmxon = true;
4674
4675         if (vmx_pt_mode_is_host_guest()) {
4676                 vmx->pt_desc.guest.ctl = 0;
4677                 pt_update_intercept_for_msr(vmx);
4678         }
4679
4680         return 0;
4681
4682 out_shadow_vmcs:
4683         kfree(vmx->nested.cached_shadow_vmcs12);
4684
4685 out_cached_shadow_vmcs12:
4686         kfree(vmx->nested.cached_vmcs12);
4687
4688 out_cached_vmcs12:
4689         free_loaded_vmcs(&vmx->nested.vmcs02);
4690
4691 out_vmcs02:
4692         return -ENOMEM;
4693 }
4694
4695 /*
4696  * Emulate the VMXON instruction.
4697  * Currently, we just remember that VMX is active, and do not save or even
4698  * inspect the argument to VMXON (the so-called "VMXON pointer") because we
4699  * do not currently need to store anything in that guest-allocated memory
4700  * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
4701  * argument is different from the VMXON pointer (which the spec says they do).
4702  */
4703 static int handle_vmon(struct kvm_vcpu *vcpu)
4704 {
4705         int ret;
4706         gpa_t vmptr;
4707         uint32_t revision;
4708         struct vcpu_vmx *vmx = to_vmx(vcpu);
4709         const u64 VMXON_NEEDED_FEATURES = FEAT_CTL_LOCKED
4710                 | FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
4711
4712         /*
4713          * The Intel VMX Instruction Reference lists a bunch of bits that are
4714          * prerequisite to running VMXON, most notably cr4.VMXE must be set to
4715          * 1 (see vmx_set_cr4() for when we allow the guest to set this).
4716          * Otherwise, we should fail with #UD.  But most faulting conditions
4717          * have already been checked by hardware, prior to the VM-exit for
4718          * VMXON.  We do test guest cr4.VMXE because processor CR4 always has
4719          * that bit set to 1 in non-root mode.
4720          */
4721         if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) {
4722                 kvm_queue_exception(vcpu, UD_VECTOR);
4723                 return 1;
4724         }
4725
4726         /* CPL=0 must be checked manually. */
4727         if (vmx_get_cpl(vcpu)) {
4728                 kvm_inject_gp(vcpu, 0);
4729                 return 1;
4730         }
4731
4732         if (vmx->nested.vmxon)
4733                 return nested_vmx_failValid(vcpu,
4734                         VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
4735
4736         if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
4737                         != VMXON_NEEDED_FEATURES) {
4738                 kvm_inject_gp(vcpu, 0);
4739                 return 1;
4740         }
4741
4742         if (nested_vmx_get_vmptr(vcpu, &vmptr))
4743                 return 1;
4744
4745         /*
4746          * SDM 3: 24.11.5
4747          * The first 4 bytes of VMXON region contain the supported
4748          * VMCS revision identifier
4749          *
4750          * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
4751          * which replaces physical address width with 32
4752          */
4753         if (!page_address_valid(vcpu, vmptr))
4754                 return nested_vmx_failInvalid(vcpu);
4755
4756         if (kvm_read_guest(vcpu->kvm, vmptr, &revision, sizeof(revision)) ||
4757             revision != VMCS12_REVISION)
4758                 return nested_vmx_failInvalid(vcpu);
4759
4760         vmx->nested.vmxon_ptr = vmptr;
4761         ret = enter_vmx_operation(vcpu);
4762         if (ret)
4763                 return ret;
4764
4765         return nested_vmx_succeed(vcpu);
4766 }
4767
4768 static inline void nested_release_vmcs12(struct kvm_vcpu *vcpu)
4769 {
4770         struct vcpu_vmx *vmx = to_vmx(vcpu);
4771
4772         if (vmx->nested.current_vmptr == -1ull)
4773                 return;
4774
4775         copy_vmcs02_to_vmcs12_rare(vcpu, get_vmcs12(vcpu));
4776
4777         if (enable_shadow_vmcs) {
4778                 /* copy to memory all shadowed fields in case
4779                    they were modified */
4780                 copy_shadow_to_vmcs12(vmx);
4781                 vmx_disable_shadow_vmcs(vmx);
4782         }
4783         vmx->nested.posted_intr_nv = -1;
4784
4785         /* Flush VMCS12 to guest memory */
4786         kvm_vcpu_write_guest_page(vcpu,
4787                                   vmx->nested.current_vmptr >> PAGE_SHIFT,
4788                                   vmx->nested.cached_vmcs12, 0, VMCS12_SIZE);
4789
4790         kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
4791
4792         vmx->nested.current_vmptr = -1ull;
4793 }
4794
4795 /* Emulate the VMXOFF instruction */
4796 static int handle_vmoff(struct kvm_vcpu *vcpu)
4797 {
4798         if (!nested_vmx_check_permission(vcpu))
4799                 return 1;
4800
4801         free_nested(vcpu);
4802
4803         /* Process a latched INIT during time CPU was in VMX operation */
4804         kvm_make_request(KVM_REQ_EVENT, vcpu);
4805
4806         return nested_vmx_succeed(vcpu);
4807 }
4808
4809 /* Emulate the VMCLEAR instruction */
4810 static int handle_vmclear(struct kvm_vcpu *vcpu)
4811 {
4812         struct vcpu_vmx *vmx = to_vmx(vcpu);
4813         u32 zero = 0;
4814         gpa_t vmptr;
4815         u64 evmcs_gpa;
4816
4817         if (!nested_vmx_check_permission(vcpu))
4818                 return 1;
4819
4820         if (nested_vmx_get_vmptr(vcpu, &vmptr))
4821                 return 1;
4822
4823         if (!page_address_valid(vcpu, vmptr))
4824                 return nested_vmx_failValid(vcpu,
4825                         VMXERR_VMCLEAR_INVALID_ADDRESS);
4826
4827         if (vmptr == vmx->nested.vmxon_ptr)
4828                 return nested_vmx_failValid(vcpu,
4829                         VMXERR_VMCLEAR_VMXON_POINTER);
4830
4831         /*
4832          * When Enlightened VMEntry is enabled on the calling CPU we treat
4833          * memory area pointer by vmptr as Enlightened VMCS (as there's no good
4834          * way to distinguish it from VMCS12) and we must not corrupt it by
4835          * writing to the non-existent 'launch_state' field. The area doesn't
4836          * have to be the currently active EVMCS on the calling CPU and there's
4837          * nothing KVM has to do to transition it from 'active' to 'non-active'
4838          * state. It is possible that the area will stay mapped as
4839          * vmx->nested.hv_evmcs but this shouldn't be a problem.
4840          */
4841         if (likely(!vmx->nested.enlightened_vmcs_enabled ||
4842                    !nested_enlightened_vmentry(vcpu, &evmcs_gpa))) {
4843                 if (vmptr == vmx->nested.current_vmptr)
4844                         nested_release_vmcs12(vcpu);
4845
4846                 kvm_vcpu_write_guest(vcpu,
4847                                      vmptr + offsetof(struct vmcs12,
4848                                                       launch_state),
4849                                      &zero, sizeof(zero));
4850         }
4851
4852         return nested_vmx_succeed(vcpu);
4853 }
4854
4855 /* Emulate the VMLAUNCH instruction */
4856 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
4857 {
4858         return nested_vmx_run(vcpu, true);
4859 }
4860
4861 /* Emulate the VMRESUME instruction */
4862 static int handle_vmresume(struct kvm_vcpu *vcpu)
4863 {
4864
4865         return nested_vmx_run(vcpu, false);
4866 }
4867
4868 static int handle_vmread(struct kvm_vcpu *vcpu)
4869 {
4870         struct vmcs12 *vmcs12 = is_guest_mode(vcpu) ? get_shadow_vmcs12(vcpu)
4871                                                     : get_vmcs12(vcpu);
4872         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4873         u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
4874         struct vcpu_vmx *vmx = to_vmx(vcpu);
4875         struct x86_exception e;
4876         unsigned long field;
4877         u64 value;
4878         gva_t gva = 0;
4879         short offset;
4880         int len;
4881
4882         if (!nested_vmx_check_permission(vcpu))
4883                 return 1;
4884
4885         /*
4886          * In VMX non-root operation, when the VMCS-link pointer is -1ull,
4887          * any VMREAD sets the ALU flags for VMfailInvalid.
4888          */
4889         if (vmx->nested.current_vmptr == -1ull ||
4890             (is_guest_mode(vcpu) &&
4891              get_vmcs12(vcpu)->vmcs_link_pointer == -1ull))
4892                 return nested_vmx_failInvalid(vcpu);
4893
4894         /* Decode instruction info and find the field to read */
4895         field = kvm_register_readl(vcpu, (((instr_info) >> 28) & 0xf));
4896
4897         offset = vmcs_field_to_offset(field);
4898         if (offset < 0)
4899                 return nested_vmx_failValid(vcpu,
4900                         VMXERR_UNSUPPORTED_VMCS_COMPONENT);
4901
4902         if (!is_guest_mode(vcpu) && is_vmcs12_ext_field(field))
4903                 copy_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
4904
4905         /* Read the field, zero-extended to a u64 value */
4906         value = vmcs12_read_any(vmcs12, field, offset);
4907
4908         /*
4909          * Now copy part of this value to register or memory, as requested.
4910          * Note that the number of bits actually copied is 32 or 64 depending
4911          * on the guest's mode (32 or 64 bit), not on the given field's length.
4912          */
4913         if (instr_info & BIT(10)) {
4914                 kvm_register_writel(vcpu, (((instr_info) >> 3) & 0xf), value);
4915         } else {
4916                 len = is_64_bit_mode(vcpu) ? 8 : 4;
4917                 if (get_vmx_mem_address(vcpu, exit_qualification,
4918                                         instr_info, true, len, &gva))
4919                         return 1;
4920                 /* _system ok, nested_vmx_check_permission has verified cpl=0 */
4921                 if (kvm_write_guest_virt_system(vcpu, gva, &value, len, &e)) {
4922                         kvm_inject_emulated_page_fault(vcpu, &e);
4923                         return 1;
4924                 }
4925         }
4926
4927         return nested_vmx_succeed(vcpu);
4928 }
4929
4930 static bool is_shadow_field_rw(unsigned long field)
4931 {
4932         switch (field) {
4933 #define SHADOW_FIELD_RW(x, y) case x:
4934 #include "vmcs_shadow_fields.h"
4935                 return true;
4936         default:
4937                 break;
4938         }
4939         return false;
4940 }
4941
4942 static bool is_shadow_field_ro(unsigned long field)
4943 {
4944         switch (field) {
4945 #define SHADOW_FIELD_RO(x, y) case x:
4946 #include "vmcs_shadow_fields.h"
4947                 return true;
4948         default:
4949                 break;
4950         }
4951         return false;
4952 }
4953
4954 static int handle_vmwrite(struct kvm_vcpu *vcpu)
4955 {
4956         struct vmcs12 *vmcs12 = is_guest_mode(vcpu) ? get_shadow_vmcs12(vcpu)
4957                                                     : get_vmcs12(vcpu);
4958         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4959         u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
4960         struct vcpu_vmx *vmx = to_vmx(vcpu);
4961         struct x86_exception e;
4962         unsigned long field;
4963         short offset;
4964         gva_t gva;
4965         int len;
4966
4967         /*
4968          * The value to write might be 32 or 64 bits, depending on L1's long
4969          * mode, and eventually we need to write that into a field of several
4970          * possible lengths. The code below first zero-extends the value to 64
4971          * bit (value), and then copies only the appropriate number of
4972          * bits into the vmcs12 field.
4973          */
4974         u64 value = 0;
4975
4976         if (!nested_vmx_check_permission(vcpu))
4977                 return 1;
4978
4979         /*
4980          * In VMX non-root operation, when the VMCS-link pointer is -1ull,
4981          * any VMWRITE sets the ALU flags for VMfailInvalid.
4982          */
4983         if (vmx->nested.current_vmptr == -1ull ||
4984             (is_guest_mode(vcpu) &&
4985              get_vmcs12(vcpu)->vmcs_link_pointer == -1ull))
4986                 return nested_vmx_failInvalid(vcpu);
4987
4988         if (instr_info & BIT(10))
4989                 value = kvm_register_readl(vcpu, (((instr_info) >> 3) & 0xf));
4990         else {
4991                 len = is_64_bit_mode(vcpu) ? 8 : 4;
4992                 if (get_vmx_mem_address(vcpu, exit_qualification,
4993                                         instr_info, false, len, &gva))
4994                         return 1;
4995                 if (kvm_read_guest_virt(vcpu, gva, &value, len, &e)) {
4996                         kvm_inject_emulated_page_fault(vcpu, &e);
4997                         return 1;
4998                 }
4999         }
5000
5001         field = kvm_register_readl(vcpu, (((instr_info) >> 28) & 0xf));
5002
5003         offset = vmcs_field_to_offset(field);
5004         if (offset < 0)
5005                 return nested_vmx_failValid(vcpu,
5006                         VMXERR_UNSUPPORTED_VMCS_COMPONENT);
5007
5008         /*
5009          * If the vCPU supports "VMWRITE to any supported field in the
5010          * VMCS," then the "read-only" fields are actually read/write.
5011          */
5012         if (vmcs_field_readonly(field) &&
5013             !nested_cpu_has_vmwrite_any_field(vcpu))
5014                 return nested_vmx_failValid(vcpu,
5015                         VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
5016
5017         /*
5018          * Ensure vmcs12 is up-to-date before any VMWRITE that dirties
5019          * vmcs12, else we may crush a field or consume a stale value.
5020          */
5021         if (!is_guest_mode(vcpu) && !is_shadow_field_rw(field))
5022                 copy_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
5023
5024         /*
5025          * Some Intel CPUs intentionally drop the reserved bits of the AR byte
5026          * fields on VMWRITE.  Emulate this behavior to ensure consistent KVM
5027          * behavior regardless of the underlying hardware, e.g. if an AR_BYTE
5028          * field is intercepted for VMWRITE but not VMREAD (in L1), then VMREAD
5029          * from L1 will return a different value than VMREAD from L2 (L1 sees
5030          * the stripped down value, L2 sees the full value as stored by KVM).
5031          */
5032         if (field >= GUEST_ES_AR_BYTES && field <= GUEST_TR_AR_BYTES)
5033                 value &= 0x1f0ff;
5034
5035         vmcs12_write_any(vmcs12, field, offset, value);
5036
5037         /*
5038          * Do not track vmcs12 dirty-state if in guest-mode as we actually
5039          * dirty shadow vmcs12 instead of vmcs12.  Fields that can be updated
5040          * by L1 without a vmexit are always updated in the vmcs02, i.e. don't
5041          * "dirty" vmcs12, all others go down the prepare_vmcs02() slow path.
5042          */
5043         if (!is_guest_mode(vcpu) && !is_shadow_field_rw(field)) {
5044                 /*
5045                  * L1 can read these fields without exiting, ensure the
5046                  * shadow VMCS is up-to-date.
5047                  */
5048                 if (enable_shadow_vmcs && is_shadow_field_ro(field)) {
5049                         preempt_disable();
5050                         vmcs_load(vmx->vmcs01.shadow_vmcs);
5051
5052                         __vmcs_writel(field, value);
5053
5054                         vmcs_clear(vmx->vmcs01.shadow_vmcs);
5055                         vmcs_load(vmx->loaded_vmcs->vmcs);
5056                         preempt_enable();
5057                 }
5058                 vmx->nested.dirty_vmcs12 = true;
5059         }
5060
5061         return nested_vmx_succeed(vcpu);
5062 }
5063
5064 static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
5065 {
5066         vmx->nested.current_vmptr = vmptr;
5067         if (enable_shadow_vmcs) {
5068                 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_SHADOW_VMCS);
5069                 vmcs_write64(VMCS_LINK_POINTER,
5070                              __pa(vmx->vmcs01.shadow_vmcs));
5071                 vmx->nested.need_vmcs12_to_shadow_sync = true;
5072         }
5073         vmx->nested.dirty_vmcs12 = true;
5074 }
5075
5076 /* Emulate the VMPTRLD instruction */
5077 static int handle_vmptrld(struct kvm_vcpu *vcpu)
5078 {
5079         struct vcpu_vmx *vmx = to_vmx(vcpu);
5080         gpa_t vmptr;
5081
5082         if (!nested_vmx_check_permission(vcpu))
5083                 return 1;
5084
5085         if (nested_vmx_get_vmptr(vcpu, &vmptr))
5086                 return 1;
5087
5088         if (!page_address_valid(vcpu, vmptr))
5089                 return nested_vmx_failValid(vcpu,
5090                         VMXERR_VMPTRLD_INVALID_ADDRESS);
5091
5092         if (vmptr == vmx->nested.vmxon_ptr)
5093                 return nested_vmx_failValid(vcpu,
5094                         VMXERR_VMPTRLD_VMXON_POINTER);
5095
5096         /* Forbid normal VMPTRLD if Enlightened version was used */
5097         if (vmx->nested.hv_evmcs)
5098                 return 1;
5099
5100         if (vmx->nested.current_vmptr != vmptr) {
5101                 struct kvm_host_map map;
5102                 struct vmcs12 *new_vmcs12;
5103
5104                 if (kvm_vcpu_map(vcpu, gpa_to_gfn(vmptr), &map)) {
5105                         /*
5106                          * Reads from an unbacked page return all 1s,
5107                          * which means that the 32 bits located at the
5108                          * given physical address won't match the required
5109                          * VMCS12_REVISION identifier.
5110                          */
5111                         return nested_vmx_failValid(vcpu,
5112                                 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
5113                 }
5114
5115                 new_vmcs12 = map.hva;
5116
5117                 if (new_vmcs12->hdr.revision_id != VMCS12_REVISION ||
5118                     (new_vmcs12->hdr.shadow_vmcs &&
5119                      !nested_cpu_has_vmx_shadow_vmcs(vcpu))) {
5120                         kvm_vcpu_unmap(vcpu, &map, false);
5121                         return nested_vmx_failValid(vcpu,
5122                                 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
5123                 }
5124
5125                 nested_release_vmcs12(vcpu);
5126
5127                 /*
5128                  * Load VMCS12 from guest memory since it is not already
5129                  * cached.
5130                  */
5131                 memcpy(vmx->nested.cached_vmcs12, new_vmcs12, VMCS12_SIZE);
5132                 kvm_vcpu_unmap(vcpu, &map, false);
5133
5134                 set_current_vmptr(vmx, vmptr);
5135         }
5136
5137         return nested_vmx_succeed(vcpu);
5138 }
5139
5140 /* Emulate the VMPTRST instruction */
5141 static int handle_vmptrst(struct kvm_vcpu *vcpu)
5142 {
5143         unsigned long exit_qual = vmcs_readl(EXIT_QUALIFICATION);
5144         u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5145         gpa_t current_vmptr = to_vmx(vcpu)->nested.current_vmptr;
5146         struct x86_exception e;
5147         gva_t gva;
5148
5149         if (!nested_vmx_check_permission(vcpu))
5150                 return 1;
5151
5152         if (unlikely(to_vmx(vcpu)->nested.hv_evmcs))
5153                 return 1;
5154
5155         if (get_vmx_mem_address(vcpu, exit_qual, instr_info,
5156                                 true, sizeof(gpa_t), &gva))
5157                 return 1;
5158         /* *_system ok, nested_vmx_check_permission has verified cpl=0 */
5159         if (kvm_write_guest_virt_system(vcpu, gva, (void *)&current_vmptr,
5160                                         sizeof(gpa_t), &e)) {
5161                 kvm_inject_emulated_page_fault(vcpu, &e);
5162                 return 1;
5163         }
5164         return nested_vmx_succeed(vcpu);
5165 }
5166
5167 #define EPTP_PA_MASK   GENMASK_ULL(51, 12)
5168
5169 static bool nested_ept_root_matches(hpa_t root_hpa, u64 root_eptp, u64 eptp)
5170 {
5171         return VALID_PAGE(root_hpa) &&
5172                 ((root_eptp & EPTP_PA_MASK) == (eptp & EPTP_PA_MASK));
5173 }
5174
5175 /* Emulate the INVEPT instruction */
5176 static int handle_invept(struct kvm_vcpu *vcpu)
5177 {
5178         struct vcpu_vmx *vmx = to_vmx(vcpu);
5179         u32 vmx_instruction_info, types;
5180         unsigned long type, roots_to_free;
5181         struct kvm_mmu *mmu;
5182         gva_t gva;
5183         struct x86_exception e;
5184         struct {
5185                 u64 eptp, gpa;
5186         } operand;
5187         int i;
5188
5189         if (!(vmx->nested.msrs.secondary_ctls_high &
5190               SECONDARY_EXEC_ENABLE_EPT) ||
5191             !(vmx->nested.msrs.ept_caps & VMX_EPT_INVEPT_BIT)) {
5192                 kvm_queue_exception(vcpu, UD_VECTOR);
5193                 return 1;
5194         }
5195
5196         if (!nested_vmx_check_permission(vcpu))
5197                 return 1;
5198
5199         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5200         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5201
5202         types = (vmx->nested.msrs.ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
5203
5204         if (type >= 32 || !(types & (1 << type)))
5205                 return nested_vmx_failValid(vcpu,
5206                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
5207
5208         /* According to the Intel VMX instruction reference, the memory
5209          * operand is read even if it isn't needed (e.g., for type==global)
5210          */
5211         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
5212                         vmx_instruction_info, false, sizeof(operand), &gva))
5213                 return 1;
5214         if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
5215                 kvm_inject_emulated_page_fault(vcpu, &e);
5216                 return 1;
5217         }
5218
5219         /*
5220          * Nested EPT roots are always held through guest_mmu,
5221          * not root_mmu.
5222          */
5223         mmu = &vcpu->arch.guest_mmu;
5224
5225         switch (type) {
5226         case VMX_EPT_EXTENT_CONTEXT:
5227                 if (!nested_vmx_check_eptp(vcpu, operand.eptp))
5228                         return nested_vmx_failValid(vcpu,
5229                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
5230
5231                 roots_to_free = 0;
5232                 if (nested_ept_root_matches(mmu->root_hpa, mmu->root_pgd,
5233                                             operand.eptp))
5234                         roots_to_free |= KVM_MMU_ROOT_CURRENT;
5235
5236                 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5237                         if (nested_ept_root_matches(mmu->prev_roots[i].hpa,
5238                                                     mmu->prev_roots[i].pgd,
5239                                                     operand.eptp))
5240                                 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5241                 }
5242                 break;
5243         case VMX_EPT_EXTENT_GLOBAL:
5244                 roots_to_free = KVM_MMU_ROOTS_ALL;
5245                 break;
5246         default:
5247                 BUG_ON(1);
5248                 break;
5249         }
5250
5251         if (roots_to_free)
5252                 kvm_mmu_free_roots(vcpu, mmu, roots_to_free);
5253
5254         return nested_vmx_succeed(vcpu);
5255 }
5256
5257 static int handle_invvpid(struct kvm_vcpu *vcpu)
5258 {
5259         struct vcpu_vmx *vmx = to_vmx(vcpu);
5260         u32 vmx_instruction_info;
5261         unsigned long type, types;
5262         gva_t gva;
5263         struct x86_exception e;
5264         struct {
5265                 u64 vpid;
5266                 u64 gla;
5267         } operand;
5268         u16 vpid02;
5269
5270         if (!(vmx->nested.msrs.secondary_ctls_high &
5271               SECONDARY_EXEC_ENABLE_VPID) ||
5272                         !(vmx->nested.msrs.vpid_caps & VMX_VPID_INVVPID_BIT)) {
5273                 kvm_queue_exception(vcpu, UD_VECTOR);
5274                 return 1;
5275         }
5276
5277         if (!nested_vmx_check_permission(vcpu))
5278                 return 1;
5279
5280         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5281         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5282
5283         types = (vmx->nested.msrs.vpid_caps &
5284                         VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
5285
5286         if (type >= 32 || !(types & (1 << type)))
5287                 return nested_vmx_failValid(vcpu,
5288                         VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
5289
5290         /* according to the intel vmx instruction reference, the memory
5291          * operand is read even if it isn't needed (e.g., for type==global)
5292          */
5293         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
5294                         vmx_instruction_info, false, sizeof(operand), &gva))
5295                 return 1;
5296         if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
5297                 kvm_inject_emulated_page_fault(vcpu, &e);
5298                 return 1;
5299         }
5300         if (operand.vpid >> 16)
5301                 return nested_vmx_failValid(vcpu,
5302                         VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
5303
5304         vpid02 = nested_get_vpid02(vcpu);
5305         switch (type) {
5306         case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
5307                 if (!operand.vpid ||
5308                     is_noncanonical_address(operand.gla, vcpu))
5309                         return nested_vmx_failValid(vcpu,
5310                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
5311                 vpid_sync_vcpu_addr(vpid02, operand.gla);
5312                 break;
5313         case VMX_VPID_EXTENT_SINGLE_CONTEXT:
5314         case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
5315                 if (!operand.vpid)
5316                         return nested_vmx_failValid(vcpu,
5317                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
5318                 vpid_sync_context(vpid02);
5319                 break;
5320         case VMX_VPID_EXTENT_ALL_CONTEXT:
5321                 vpid_sync_context(vpid02);
5322                 break;
5323         default:
5324                 WARN_ON_ONCE(1);
5325                 return kvm_skip_emulated_instruction(vcpu);
5326         }
5327
5328         /*
5329          * Sync the shadow page tables if EPT is disabled, L1 is invalidating
5330          * linear mappings for L2 (tagged with L2's VPID).  Free all roots as
5331          * VPIDs are not tracked in the MMU role.
5332          *
5333          * Note, this operates on root_mmu, not guest_mmu, as L1 and L2 share
5334          * an MMU when EPT is disabled.
5335          *
5336          * TODO: sync only the affected SPTEs for INVDIVIDUAL_ADDR.
5337          */
5338         if (!enable_ept)
5339                 kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu,
5340                                    KVM_MMU_ROOTS_ALL);
5341
5342         return nested_vmx_succeed(vcpu);
5343 }
5344
5345 static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
5346                                      struct vmcs12 *vmcs12)
5347 {
5348         u32 index = kvm_rcx_read(vcpu);
5349         u64 new_eptp;
5350         bool accessed_dirty;
5351         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
5352
5353         if (!nested_cpu_has_eptp_switching(vmcs12) ||
5354             !nested_cpu_has_ept(vmcs12))
5355                 return 1;
5356
5357         if (index >= VMFUNC_EPTP_ENTRIES)
5358                 return 1;
5359
5360
5361         if (kvm_vcpu_read_guest_page(vcpu, vmcs12->eptp_list_address >> PAGE_SHIFT,
5362                                      &new_eptp, index * 8, 8))
5363                 return 1;
5364
5365         accessed_dirty = !!(new_eptp & VMX_EPTP_AD_ENABLE_BIT);
5366
5367         /*
5368          * If the (L2) guest does a vmfunc to the currently
5369          * active ept pointer, we don't have to do anything else
5370          */
5371         if (vmcs12->ept_pointer != new_eptp) {
5372                 if (!nested_vmx_check_eptp(vcpu, new_eptp))
5373                         return 1;
5374
5375                 kvm_mmu_unload(vcpu);
5376                 mmu->ept_ad = accessed_dirty;
5377                 mmu->mmu_role.base.ad_disabled = !accessed_dirty;
5378                 vmcs12->ept_pointer = new_eptp;
5379                 /*
5380                  * TODO: Check what's the correct approach in case
5381                  * mmu reload fails. Currently, we just let the next
5382                  * reload potentially fail
5383                  */
5384                 kvm_mmu_reload(vcpu);
5385         }
5386
5387         return 0;
5388 }
5389
5390 static int handle_vmfunc(struct kvm_vcpu *vcpu)
5391 {
5392         struct vcpu_vmx *vmx = to_vmx(vcpu);
5393         struct vmcs12 *vmcs12;
5394         u32 function = kvm_rax_read(vcpu);
5395
5396         /*
5397          * VMFUNC is only supported for nested guests, but we always enable the
5398          * secondary control for simplicity; for non-nested mode, fake that we
5399          * didn't by injecting #UD.
5400          */
5401         if (!is_guest_mode(vcpu)) {
5402                 kvm_queue_exception(vcpu, UD_VECTOR);
5403                 return 1;
5404         }
5405
5406         vmcs12 = get_vmcs12(vcpu);
5407         if ((vmcs12->vm_function_control & (1 << function)) == 0)
5408                 goto fail;
5409
5410         switch (function) {
5411         case 0:
5412                 if (nested_vmx_eptp_switching(vcpu, vmcs12))
5413                         goto fail;
5414                 break;
5415         default:
5416                 goto fail;
5417         }
5418         return kvm_skip_emulated_instruction(vcpu);
5419
5420 fail:
5421         nested_vmx_vmexit(vcpu, vmx->exit_reason,
5422                           vmcs_read32(VM_EXIT_INTR_INFO),
5423                           vmcs_readl(EXIT_QUALIFICATION));
5424         return 1;
5425 }
5426
5427 /*
5428  * Return true if an IO instruction with the specified port and size should cause
5429  * a VM-exit into L1.
5430  */
5431 bool nested_vmx_check_io_bitmaps(struct kvm_vcpu *vcpu, unsigned int port,
5432                                  int size)
5433 {
5434         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5435         gpa_t bitmap, last_bitmap;
5436         u8 b;
5437
5438         last_bitmap = (gpa_t)-1;
5439         b = -1;
5440
5441         while (size > 0) {
5442                 if (port < 0x8000)
5443                         bitmap = vmcs12->io_bitmap_a;
5444                 else if (port < 0x10000)
5445                         bitmap = vmcs12->io_bitmap_b;
5446                 else
5447                         return true;
5448                 bitmap += (port & 0x7fff) / 8;
5449
5450                 if (last_bitmap != bitmap)
5451                         if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
5452                                 return true;
5453                 if (b & (1 << (port & 7)))
5454                         return true;
5455
5456                 port++;
5457                 size--;
5458                 last_bitmap = bitmap;
5459         }
5460
5461         return false;
5462 }
5463
5464 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
5465                                        struct vmcs12 *vmcs12)
5466 {
5467         unsigned long exit_qualification;
5468         unsigned short port;
5469         int size;
5470
5471         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
5472                 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
5473
5474         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5475
5476         port = exit_qualification >> 16;
5477         size = (exit_qualification & 7) + 1;
5478
5479         return nested_vmx_check_io_bitmaps(vcpu, port, size);
5480 }
5481
5482 /*
5483  * Return 1 if we should exit from L2 to L1 to handle an MSR access,
5484  * rather than handle it ourselves in L0. I.e., check whether L1 expressed
5485  * disinterest in the current event (read or write a specific MSR) by using an
5486  * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
5487  */
5488 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
5489         struct vmcs12 *vmcs12, u32 exit_reason)
5490 {
5491         u32 msr_index = kvm_rcx_read(vcpu);
5492         gpa_t bitmap;
5493
5494         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
5495                 return true;
5496
5497         /*
5498          * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
5499          * for the four combinations of read/write and low/high MSR numbers.
5500          * First we need to figure out which of the four to use:
5501          */
5502         bitmap = vmcs12->msr_bitmap;
5503         if (exit_reason == EXIT_REASON_MSR_WRITE)
5504                 bitmap += 2048;
5505         if (msr_index >= 0xc0000000) {
5506                 msr_index -= 0xc0000000;
5507                 bitmap += 1024;
5508         }
5509
5510         /* Then read the msr_index'th bit from this bitmap: */
5511         if (msr_index < 1024*8) {
5512                 unsigned char b;
5513                 if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
5514                         return true;
5515                 return 1 & (b >> (msr_index & 7));
5516         } else
5517                 return true; /* let L1 handle the wrong parameter */
5518 }
5519
5520 /*
5521  * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
5522  * rather than handle it ourselves in L0. I.e., check if L1 wanted to
5523  * intercept (via guest_host_mask etc.) the current event.
5524  */
5525 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
5526         struct vmcs12 *vmcs12)
5527 {
5528         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5529         int cr = exit_qualification & 15;
5530         int reg;
5531         unsigned long val;
5532
5533         switch ((exit_qualification >> 4) & 3) {
5534         case 0: /* mov to cr */
5535                 reg = (exit_qualification >> 8) & 15;
5536                 val = kvm_register_readl(vcpu, reg);
5537                 switch (cr) {
5538                 case 0:
5539                         if (vmcs12->cr0_guest_host_mask &
5540                             (val ^ vmcs12->cr0_read_shadow))
5541                                 return true;
5542                         break;
5543                 case 3:
5544                         if ((vmcs12->cr3_target_count >= 1 &&
5545                                         vmcs12->cr3_target_value0 == val) ||
5546                                 (vmcs12->cr3_target_count >= 2 &&
5547                                         vmcs12->cr3_target_value1 == val) ||
5548                                 (vmcs12->cr3_target_count >= 3 &&
5549                                         vmcs12->cr3_target_value2 == val) ||
5550                                 (vmcs12->cr3_target_count >= 4 &&
5551                                         vmcs12->cr3_target_value3 == val))
5552                                 return false;
5553                         if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
5554                                 return true;
5555                         break;
5556                 case 4:
5557                         if (vmcs12->cr4_guest_host_mask &
5558                             (vmcs12->cr4_read_shadow ^ val))
5559                                 return true;
5560                         break;
5561                 case 8:
5562                         if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
5563                                 return true;
5564                         break;
5565                 }
5566                 break;
5567         case 2: /* clts */
5568                 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
5569                     (vmcs12->cr0_read_shadow & X86_CR0_TS))
5570                         return true;
5571                 break;
5572         case 1: /* mov from cr */
5573                 switch (cr) {
5574                 case 3:
5575                         if (vmcs12->cpu_based_vm_exec_control &
5576                             CPU_BASED_CR3_STORE_EXITING)
5577                                 return true;
5578                         break;
5579                 case 8:
5580                         if (vmcs12->cpu_based_vm_exec_control &
5581                             CPU_BASED_CR8_STORE_EXITING)
5582                                 return true;
5583                         break;
5584                 }
5585                 break;
5586         case 3: /* lmsw */
5587                 /*
5588                  * lmsw can change bits 1..3 of cr0, and only set bit 0 of
5589                  * cr0. Other attempted changes are ignored, with no exit.
5590                  */
5591                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5592                 if (vmcs12->cr0_guest_host_mask & 0xe &
5593                     (val ^ vmcs12->cr0_read_shadow))
5594                         return true;
5595                 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
5596                     !(vmcs12->cr0_read_shadow & 0x1) &&
5597                     (val & 0x1))
5598                         return true;
5599                 break;
5600         }
5601         return false;
5602 }
5603
5604 static bool nested_vmx_exit_handled_vmcs_access(struct kvm_vcpu *vcpu,
5605         struct vmcs12 *vmcs12, gpa_t bitmap)
5606 {
5607         u32 vmx_instruction_info;
5608         unsigned long field;
5609         u8 b;
5610
5611         if (!nested_cpu_has_shadow_vmcs(vmcs12))
5612                 return true;
5613
5614         /* Decode instruction info and find the field to access */
5615         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5616         field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
5617
5618         /* Out-of-range fields always cause a VM exit from L2 to L1 */
5619         if (field >> 15)
5620                 return true;
5621
5622         if (kvm_vcpu_read_guest(vcpu, bitmap + field/8, &b, 1))
5623                 return true;
5624
5625         return 1 & (b >> (field & 7));
5626 }
5627
5628 static bool nested_vmx_exit_handled_mtf(struct vmcs12 *vmcs12)
5629 {
5630         u32 entry_intr_info = vmcs12->vm_entry_intr_info_field;
5631
5632         if (nested_cpu_has_mtf(vmcs12))
5633                 return true;
5634
5635         /*
5636          * An MTF VM-exit may be injected into the guest by setting the
5637          * interruption-type to 7 (other event) and the vector field to 0. Such
5638          * is the case regardless of the 'monitor trap flag' VM-execution
5639          * control.
5640          */
5641         return entry_intr_info == (INTR_INFO_VALID_MASK
5642                                    | INTR_TYPE_OTHER_EVENT);
5643 }
5644
5645 /*
5646  * Return true if L0 wants to handle an exit from L2 regardless of whether or not
5647  * L1 wants the exit.  Only call this when in is_guest_mode (L2).
5648  */
5649 static bool nested_vmx_l0_wants_exit(struct kvm_vcpu *vcpu, u32 exit_reason)
5650 {
5651         u32 intr_info;
5652
5653         switch (exit_reason) {
5654         case EXIT_REASON_EXCEPTION_NMI:
5655                 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
5656                 if (is_nmi(intr_info))
5657                         return true;
5658                 else if (is_page_fault(intr_info))
5659                         return vcpu->arch.apf.host_apf_reason || !enable_ept;
5660                 else if (is_debug(intr_info) &&
5661                          vcpu->guest_debug &
5662                          (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
5663                         return true;
5664                 else if (is_breakpoint(intr_info) &&
5665                          vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
5666                         return true;
5667                 return false;
5668         case EXIT_REASON_EXTERNAL_INTERRUPT:
5669                 return true;
5670         case EXIT_REASON_MCE_DURING_VMENTRY:
5671                 return true;
5672         case EXIT_REASON_EPT_VIOLATION:
5673                 /*
5674                  * L0 always deals with the EPT violation. If nested EPT is
5675                  * used, and the nested mmu code discovers that the address is
5676                  * missing in the guest EPT table (EPT12), the EPT violation
5677                  * will be injected with nested_ept_inject_page_fault()
5678                  */
5679                 return true;
5680         case EXIT_REASON_EPT_MISCONFIG:
5681                 /*
5682                  * L2 never uses directly L1's EPT, but rather L0's own EPT
5683                  * table (shadow on EPT) or a merged EPT table that L0 built
5684                  * (EPT on EPT). So any problems with the structure of the
5685                  * table is L0's fault.
5686                  */
5687                 return true;
5688         case EXIT_REASON_PREEMPTION_TIMER:
5689                 return true;
5690         case EXIT_REASON_PML_FULL:
5691                 /* We emulate PML support to L1. */
5692                 return true;
5693         case EXIT_REASON_VMFUNC:
5694                 /* VM functions are emulated through L2->L0 vmexits. */
5695                 return true;
5696         case EXIT_REASON_ENCLS:
5697                 /* SGX is never exposed to L1 */
5698                 return true;
5699         default:
5700                 break;
5701         }
5702         return false;
5703 }
5704
5705 /*
5706  * Return 1 if L1 wants to intercept an exit from L2.  Only call this when in
5707  * is_guest_mode (L2).
5708  */
5709 static bool nested_vmx_l1_wants_exit(struct kvm_vcpu *vcpu, u32 exit_reason)
5710 {
5711         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5712         u32 intr_info;
5713
5714         switch (exit_reason) {
5715         case EXIT_REASON_EXCEPTION_NMI:
5716                 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
5717                 if (is_nmi(intr_info))
5718                         return true;
5719                 else if (is_page_fault(intr_info))
5720                         return true;
5721                 return vmcs12->exception_bitmap &
5722                                 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
5723         case EXIT_REASON_EXTERNAL_INTERRUPT:
5724                 return nested_exit_on_intr(vcpu);
5725         case EXIT_REASON_TRIPLE_FAULT:
5726                 return true;
5727         case EXIT_REASON_INTERRUPT_WINDOW:
5728                 return nested_cpu_has(vmcs12, CPU_BASED_INTR_WINDOW_EXITING);
5729         case EXIT_REASON_NMI_WINDOW:
5730                 return nested_cpu_has(vmcs12, CPU_BASED_NMI_WINDOW_EXITING);
5731         case EXIT_REASON_TASK_SWITCH:
5732                 return true;
5733         case EXIT_REASON_CPUID:
5734                 return true;
5735         case EXIT_REASON_HLT:
5736                 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
5737         case EXIT_REASON_INVD:
5738                 return true;
5739         case EXIT_REASON_INVLPG:
5740                 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
5741         case EXIT_REASON_RDPMC:
5742                 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
5743         case EXIT_REASON_RDRAND:
5744                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDRAND_EXITING);
5745         case EXIT_REASON_RDSEED:
5746                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDSEED_EXITING);
5747         case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
5748                 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
5749         case EXIT_REASON_VMREAD:
5750                 return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
5751                         vmcs12->vmread_bitmap);
5752         case EXIT_REASON_VMWRITE:
5753                 return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
5754                         vmcs12->vmwrite_bitmap);
5755         case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
5756         case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
5757         case EXIT_REASON_VMPTRST: case EXIT_REASON_VMRESUME:
5758         case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
5759         case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
5760                 /*
5761                  * VMX instructions trap unconditionally. This allows L1 to
5762                  * emulate them for its L2 guest, i.e., allows 3-level nesting!
5763                  */
5764                 return true;
5765         case EXIT_REASON_CR_ACCESS:
5766                 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
5767         case EXIT_REASON_DR_ACCESS:
5768                 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
5769         case EXIT_REASON_IO_INSTRUCTION:
5770                 return nested_vmx_exit_handled_io(vcpu, vmcs12);
5771         case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
5772                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
5773         case EXIT_REASON_MSR_READ:
5774         case EXIT_REASON_MSR_WRITE:
5775                 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
5776         case EXIT_REASON_INVALID_STATE:
5777                 return true;
5778         case EXIT_REASON_MWAIT_INSTRUCTION:
5779                 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
5780         case EXIT_REASON_MONITOR_TRAP_FLAG:
5781                 return nested_vmx_exit_handled_mtf(vmcs12);
5782         case EXIT_REASON_MONITOR_INSTRUCTION:
5783                 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
5784         case EXIT_REASON_PAUSE_INSTRUCTION:
5785                 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
5786                         nested_cpu_has2(vmcs12,
5787                                 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
5788         case EXIT_REASON_MCE_DURING_VMENTRY:
5789                 return true;
5790         case EXIT_REASON_TPR_BELOW_THRESHOLD:
5791                 return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
5792         case EXIT_REASON_APIC_ACCESS:
5793         case EXIT_REASON_APIC_WRITE:
5794         case EXIT_REASON_EOI_INDUCED:
5795                 /*
5796                  * The controls for "virtualize APIC accesses," "APIC-
5797                  * register virtualization," and "virtual-interrupt
5798                  * delivery" only come from vmcs12.
5799                  */
5800                 return true;
5801         case EXIT_REASON_INVPCID:
5802                 return
5803                         nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_INVPCID) &&
5804                         nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
5805         case EXIT_REASON_WBINVD:
5806                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
5807         case EXIT_REASON_XSETBV:
5808                 return true;
5809         case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
5810                 /*
5811                  * This should never happen, since it is not possible to
5812                  * set XSS to a non-zero value---neither in L1 nor in L2.
5813                  * If if it were, XSS would have to be checked against
5814                  * the XSS exit bitmap in vmcs12.
5815                  */
5816                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
5817         case EXIT_REASON_UMWAIT:
5818         case EXIT_REASON_TPAUSE:
5819                 return nested_cpu_has2(vmcs12,
5820                         SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE);
5821         default:
5822                 return true;
5823         }
5824 }
5825
5826 /*
5827  * Conditionally reflect a VM-Exit into L1.  Returns %true if the VM-Exit was
5828  * reflected into L1.
5829  */
5830 bool nested_vmx_reflect_vmexit(struct kvm_vcpu *vcpu)
5831 {
5832         struct vcpu_vmx *vmx = to_vmx(vcpu);
5833         u32 exit_reason = vmx->exit_reason;
5834         u32 exit_intr_info, exit_qual;
5835
5836         WARN_ON_ONCE(vmx->nested.nested_run_pending);
5837
5838         /*
5839          * Late nested VM-Fail shares the same flow as nested VM-Exit since KVM
5840          * has already loaded L2's state.
5841          */
5842         if (unlikely(vmx->fail)) {
5843                 trace_kvm_nested_vmenter_failed(
5844                         "hardware VM-instruction error: ",
5845                         vmcs_read32(VM_INSTRUCTION_ERROR));
5846                 exit_intr_info = 0;
5847                 exit_qual = 0;
5848                 goto reflect_vmexit;
5849         }
5850
5851         exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
5852         exit_qual = vmcs_readl(EXIT_QUALIFICATION);
5853
5854         trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason, exit_qual,
5855                                 vmx->idt_vectoring_info, exit_intr_info,
5856                                 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5857                                 KVM_ISA_VMX);
5858
5859         /* If L0 (KVM) wants the exit, it trumps L1's desires. */
5860         if (nested_vmx_l0_wants_exit(vcpu, exit_reason))
5861                 return false;
5862
5863         /* If L1 doesn't want the exit, handle it in L0. */
5864         if (!nested_vmx_l1_wants_exit(vcpu, exit_reason))
5865                 return false;
5866
5867         /*
5868          * vmcs.VM_EXIT_INTR_INFO is only valid for EXCEPTION_NMI exits.  For
5869          * EXTERNAL_INTERRUPT, the value for vmcs12->vm_exit_intr_info would
5870          * need to be synthesized by querying the in-kernel LAPIC, but external
5871          * interrupts are never reflected to L1 so it's a non-issue.
5872          */
5873         if ((exit_intr_info &
5874              (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
5875             (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) {
5876                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5877
5878                 vmcs12->vm_exit_intr_error_code =
5879                         vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5880         }
5881
5882 reflect_vmexit:
5883         nested_vmx_vmexit(vcpu, exit_reason, exit_intr_info, exit_qual);
5884         return true;
5885 }
5886
5887 static int vmx_get_nested_state(struct kvm_vcpu *vcpu,
5888                                 struct kvm_nested_state __user *user_kvm_nested_state,
5889                                 u32 user_data_size)
5890 {
5891         struct vcpu_vmx *vmx;
5892         struct vmcs12 *vmcs12;
5893         struct kvm_nested_state kvm_state = {
5894                 .flags = 0,
5895                 .format = KVM_STATE_NESTED_FORMAT_VMX,
5896                 .size = sizeof(kvm_state),
5897                 .hdr.vmx.vmxon_pa = -1ull,
5898                 .hdr.vmx.vmcs12_pa = -1ull,
5899         };
5900         struct kvm_vmx_nested_state_data __user *user_vmx_nested_state =
5901                 &user_kvm_nested_state->data.vmx[0];
5902
5903         if (!vcpu)
5904                 return kvm_state.size + sizeof(*user_vmx_nested_state);
5905
5906         vmx = to_vmx(vcpu);
5907         vmcs12 = get_vmcs12(vcpu);
5908
5909         if (nested_vmx_allowed(vcpu) &&
5910             (vmx->nested.vmxon || vmx->nested.smm.vmxon)) {
5911                 kvm_state.hdr.vmx.vmxon_pa = vmx->nested.vmxon_ptr;
5912                 kvm_state.hdr.vmx.vmcs12_pa = vmx->nested.current_vmptr;
5913
5914                 if (vmx_has_valid_vmcs12(vcpu)) {
5915                         kvm_state.size += sizeof(user_vmx_nested_state->vmcs12);
5916
5917                         if (vmx->nested.hv_evmcs)
5918                                 kvm_state.flags |= KVM_STATE_NESTED_EVMCS;
5919
5920                         if (is_guest_mode(vcpu) &&
5921                             nested_cpu_has_shadow_vmcs(vmcs12) &&
5922                             vmcs12->vmcs_link_pointer != -1ull)
5923                                 kvm_state.size += sizeof(user_vmx_nested_state->shadow_vmcs12);
5924                 }
5925
5926                 if (vmx->nested.smm.vmxon)
5927                         kvm_state.hdr.vmx.smm.flags |= KVM_STATE_NESTED_SMM_VMXON;
5928
5929                 if (vmx->nested.smm.guest_mode)
5930                         kvm_state.hdr.vmx.smm.flags |= KVM_STATE_NESTED_SMM_GUEST_MODE;
5931
5932                 if (is_guest_mode(vcpu)) {
5933                         kvm_state.flags |= KVM_STATE_NESTED_GUEST_MODE;
5934
5935                         if (vmx->nested.nested_run_pending)
5936                                 kvm_state.flags |= KVM_STATE_NESTED_RUN_PENDING;
5937
5938                         if (vmx->nested.mtf_pending)
5939                                 kvm_state.flags |= KVM_STATE_NESTED_MTF_PENDING;
5940                 }
5941         }
5942
5943         if (user_data_size < kvm_state.size)
5944                 goto out;
5945
5946         if (copy_to_user(user_kvm_nested_state, &kvm_state, sizeof(kvm_state)))
5947                 return -EFAULT;
5948
5949         if (!vmx_has_valid_vmcs12(vcpu))
5950                 goto out;
5951
5952         /*
5953          * When running L2, the authoritative vmcs12 state is in the
5954          * vmcs02. When running L1, the authoritative vmcs12 state is
5955          * in the shadow or enlightened vmcs linked to vmcs01, unless
5956          * need_vmcs12_to_shadow_sync is set, in which case, the authoritative
5957          * vmcs12 state is in the vmcs12 already.
5958          */
5959         if (is_guest_mode(vcpu)) {
5960                 sync_vmcs02_to_vmcs12(vcpu, vmcs12);
5961                 sync_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
5962         } else if (!vmx->nested.need_vmcs12_to_shadow_sync) {
5963                 if (vmx->nested.hv_evmcs)
5964                         copy_enlightened_to_vmcs12(vmx);
5965                 else if (enable_shadow_vmcs)
5966                         copy_shadow_to_vmcs12(vmx);
5967         }
5968
5969         BUILD_BUG_ON(sizeof(user_vmx_nested_state->vmcs12) < VMCS12_SIZE);
5970         BUILD_BUG_ON(sizeof(user_vmx_nested_state->shadow_vmcs12) < VMCS12_SIZE);
5971
5972         /*
5973          * Copy over the full allocated size of vmcs12 rather than just the size
5974          * of the struct.
5975          */
5976         if (copy_to_user(user_vmx_nested_state->vmcs12, vmcs12, VMCS12_SIZE))
5977                 return -EFAULT;
5978
5979         if (nested_cpu_has_shadow_vmcs(vmcs12) &&
5980             vmcs12->vmcs_link_pointer != -1ull) {
5981                 if (copy_to_user(user_vmx_nested_state->shadow_vmcs12,
5982                                  get_shadow_vmcs12(vcpu), VMCS12_SIZE))
5983                         return -EFAULT;
5984         }
5985
5986 out:
5987         return kvm_state.size;
5988 }
5989
5990 /*
5991  * Forcibly leave nested mode in order to be able to reset the VCPU later on.
5992  */
5993 void vmx_leave_nested(struct kvm_vcpu *vcpu)
5994 {
5995         if (is_guest_mode(vcpu)) {
5996                 to_vmx(vcpu)->nested.nested_run_pending = 0;
5997                 nested_vmx_vmexit(vcpu, -1, 0, 0);
5998         }
5999         free_nested(vcpu);
6000 }
6001
6002 static int vmx_set_nested_state(struct kvm_vcpu *vcpu,
6003                                 struct kvm_nested_state __user *user_kvm_nested_state,
6004                                 struct kvm_nested_state *kvm_state)
6005 {
6006         struct vcpu_vmx *vmx = to_vmx(vcpu);
6007         struct vmcs12 *vmcs12;
6008         u32 exit_qual;
6009         struct kvm_vmx_nested_state_data __user *user_vmx_nested_state =
6010                 &user_kvm_nested_state->data.vmx[0];
6011         int ret;
6012
6013         if (kvm_state->format != KVM_STATE_NESTED_FORMAT_VMX)
6014                 return -EINVAL;
6015
6016         if (kvm_state->hdr.vmx.vmxon_pa == -1ull) {
6017                 if (kvm_state->hdr.vmx.smm.flags)
6018                         return -EINVAL;
6019
6020                 if (kvm_state->hdr.vmx.vmcs12_pa != -1ull)
6021                         return -EINVAL;
6022
6023                 /*
6024                  * KVM_STATE_NESTED_EVMCS used to signal that KVM should
6025                  * enable eVMCS capability on vCPU. However, since then
6026                  * code was changed such that flag signals vmcs12 should
6027                  * be copied into eVMCS in guest memory.
6028                  *
6029                  * To preserve backwards compatability, allow user
6030                  * to set this flag even when there is no VMXON region.
6031                  */
6032                 if (kvm_state->flags & ~KVM_STATE_NESTED_EVMCS)
6033                         return -EINVAL;
6034         } else {
6035                 if (!nested_vmx_allowed(vcpu))
6036                         return -EINVAL;
6037
6038                 if (!page_address_valid(vcpu, kvm_state->hdr.vmx.vmxon_pa))
6039                         return -EINVAL;
6040         }
6041
6042         if ((kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
6043             (kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
6044                 return -EINVAL;
6045
6046         if (kvm_state->hdr.vmx.smm.flags &
6047             ~(KVM_STATE_NESTED_SMM_GUEST_MODE | KVM_STATE_NESTED_SMM_VMXON))
6048                 return -EINVAL;
6049
6050         /*
6051          * SMM temporarily disables VMX, so we cannot be in guest mode,
6052          * nor can VMLAUNCH/VMRESUME be pending.  Outside SMM, SMM flags
6053          * must be zero.
6054          */
6055         if (is_smm(vcpu) ?
6056                 (kvm_state->flags &
6057                  (KVM_STATE_NESTED_GUEST_MODE | KVM_STATE_NESTED_RUN_PENDING))
6058                 : kvm_state->hdr.vmx.smm.flags)
6059                 return -EINVAL;
6060
6061         if ((kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
6062             !(kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON))
6063                 return -EINVAL;
6064
6065         if ((kvm_state->flags & KVM_STATE_NESTED_EVMCS) &&
6066                 (!nested_vmx_allowed(vcpu) || !vmx->nested.enlightened_vmcs_enabled))
6067                         return -EINVAL;
6068
6069         vmx_leave_nested(vcpu);
6070
6071         if (kvm_state->hdr.vmx.vmxon_pa == -1ull)
6072                 return 0;
6073
6074         vmx->nested.vmxon_ptr = kvm_state->hdr.vmx.vmxon_pa;
6075         ret = enter_vmx_operation(vcpu);
6076         if (ret)
6077                 return ret;
6078
6079         /* Empty 'VMXON' state is permitted */
6080         if (kvm_state->size < sizeof(*kvm_state) + sizeof(*vmcs12))
6081                 return 0;
6082
6083         if (kvm_state->hdr.vmx.vmcs12_pa != -1ull) {
6084                 if (kvm_state->hdr.vmx.vmcs12_pa == kvm_state->hdr.vmx.vmxon_pa ||
6085                     !page_address_valid(vcpu, kvm_state->hdr.vmx.vmcs12_pa))
6086                         return -EINVAL;
6087
6088                 set_current_vmptr(vmx, kvm_state->hdr.vmx.vmcs12_pa);
6089         } else if (kvm_state->flags & KVM_STATE_NESTED_EVMCS) {
6090                 /*
6091                  * nested_vmx_handle_enlightened_vmptrld() cannot be called
6092                  * directly from here as HV_X64_MSR_VP_ASSIST_PAGE may not be
6093                  * restored yet. EVMCS will be mapped from
6094                  * nested_get_vmcs12_pages().
6095                  */
6096                 kvm_make_request(KVM_REQ_GET_VMCS12_PAGES, vcpu);
6097         } else {
6098                 return -EINVAL;
6099         }
6100
6101         if (kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON) {
6102                 vmx->nested.smm.vmxon = true;
6103                 vmx->nested.vmxon = false;
6104
6105                 if (kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE)
6106                         vmx->nested.smm.guest_mode = true;
6107         }
6108
6109         vmcs12 = get_vmcs12(vcpu);
6110         if (copy_from_user(vmcs12, user_vmx_nested_state->vmcs12, sizeof(*vmcs12)))
6111                 return -EFAULT;
6112
6113         if (vmcs12->hdr.revision_id != VMCS12_REVISION)
6114                 return -EINVAL;
6115
6116         if (!(kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
6117                 return 0;
6118
6119         vmx->nested.nested_run_pending =
6120                 !!(kvm_state->flags & KVM_STATE_NESTED_RUN_PENDING);
6121
6122         vmx->nested.mtf_pending =
6123                 !!(kvm_state->flags & KVM_STATE_NESTED_MTF_PENDING);
6124
6125         ret = -EINVAL;
6126         if (nested_cpu_has_shadow_vmcs(vmcs12) &&
6127             vmcs12->vmcs_link_pointer != -1ull) {
6128                 struct vmcs12 *shadow_vmcs12 = get_shadow_vmcs12(vcpu);
6129
6130                 if (kvm_state->size <
6131                     sizeof(*kvm_state) +
6132                     sizeof(user_vmx_nested_state->vmcs12) + sizeof(*shadow_vmcs12))
6133                         goto error_guest_mode;
6134
6135                 if (copy_from_user(shadow_vmcs12,
6136                                    user_vmx_nested_state->shadow_vmcs12,
6137                                    sizeof(*shadow_vmcs12))) {
6138                         ret = -EFAULT;
6139                         goto error_guest_mode;
6140                 }
6141
6142                 if (shadow_vmcs12->hdr.revision_id != VMCS12_REVISION ||
6143                     !shadow_vmcs12->hdr.shadow_vmcs)
6144                         goto error_guest_mode;
6145         }
6146
6147         if (nested_vmx_check_controls(vcpu, vmcs12) ||
6148             nested_vmx_check_host_state(vcpu, vmcs12) ||
6149             nested_vmx_check_guest_state(vcpu, vmcs12, &exit_qual))
6150                 goto error_guest_mode;
6151
6152         vmx->nested.dirty_vmcs12 = true;
6153         ret = nested_vmx_enter_non_root_mode(vcpu, false);
6154         if (ret)
6155                 goto error_guest_mode;
6156
6157         return 0;
6158
6159 error_guest_mode:
6160         vmx->nested.nested_run_pending = 0;
6161         return ret;
6162 }
6163
6164 void nested_vmx_set_vmcs_shadowing_bitmap(void)
6165 {
6166         if (enable_shadow_vmcs) {
6167                 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
6168                 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
6169         }
6170 }
6171
6172 /*
6173  * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
6174  * returned for the various VMX controls MSRs when nested VMX is enabled.
6175  * The same values should also be used to verify that vmcs12 control fields are
6176  * valid during nested entry from L1 to L2.
6177  * Each of these control msrs has a low and high 32-bit half: A low bit is on
6178  * if the corresponding bit in the (32-bit) control field *must* be on, and a
6179  * bit in the high half is on if the corresponding bit in the control field
6180  * may be on. See also vmx_control_verify().
6181  */
6182 void nested_vmx_setup_ctls_msrs(struct nested_vmx_msrs *msrs, u32 ept_caps)
6183 {
6184         /*
6185          * Note that as a general rule, the high half of the MSRs (bits in
6186          * the control fields which may be 1) should be initialized by the
6187          * intersection of the underlying hardware's MSR (i.e., features which
6188          * can be supported) and the list of features we want to expose -
6189          * because they are known to be properly supported in our code.
6190          * Also, usually, the low half of the MSRs (bits which must be 1) can
6191          * be set to 0, meaning that L1 may turn off any of these bits. The
6192          * reason is that if one of these bits is necessary, it will appear
6193          * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
6194          * fields of vmcs01 and vmcs02, will turn these bits off - and
6195          * nested_vmx_l1_wants_exit() will not pass related exits to L1.
6196          * These rules have exceptions below.
6197          */
6198
6199         /* pin-based controls */
6200         rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
6201                 msrs->pinbased_ctls_low,
6202                 msrs->pinbased_ctls_high);
6203         msrs->pinbased_ctls_low |=
6204                 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
6205         msrs->pinbased_ctls_high &=
6206                 PIN_BASED_EXT_INTR_MASK |
6207                 PIN_BASED_NMI_EXITING |
6208                 PIN_BASED_VIRTUAL_NMIS |
6209                 (enable_apicv ? PIN_BASED_POSTED_INTR : 0);
6210         msrs->pinbased_ctls_high |=
6211                 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
6212                 PIN_BASED_VMX_PREEMPTION_TIMER;
6213
6214         /* exit controls */
6215         rdmsr(MSR_IA32_VMX_EXIT_CTLS,
6216                 msrs->exit_ctls_low,
6217                 msrs->exit_ctls_high);
6218         msrs->exit_ctls_low =
6219                 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
6220
6221         msrs->exit_ctls_high &=
6222 #ifdef CONFIG_X86_64
6223                 VM_EXIT_HOST_ADDR_SPACE_SIZE |
6224 #endif
6225                 VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
6226         msrs->exit_ctls_high |=
6227                 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
6228                 VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
6229                 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
6230
6231         /* We support free control of debug control saving. */
6232         msrs->exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
6233
6234         /* entry controls */
6235         rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
6236                 msrs->entry_ctls_low,
6237                 msrs->entry_ctls_high);
6238         msrs->entry_ctls_low =
6239                 VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
6240         msrs->entry_ctls_high &=
6241 #ifdef CONFIG_X86_64
6242                 VM_ENTRY_IA32E_MODE |
6243 #endif
6244                 VM_ENTRY_LOAD_IA32_PAT;
6245         msrs->entry_ctls_high |=
6246                 (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
6247
6248         /* We support free control of debug control loading. */
6249         msrs->entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
6250
6251         /* cpu-based controls */
6252         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
6253                 msrs->procbased_ctls_low,
6254                 msrs->procbased_ctls_high);
6255         msrs->procbased_ctls_low =
6256                 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
6257         msrs->procbased_ctls_high &=
6258                 CPU_BASED_INTR_WINDOW_EXITING |
6259                 CPU_BASED_NMI_WINDOW_EXITING | CPU_BASED_USE_TSC_OFFSETTING |
6260                 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
6261                 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
6262                 CPU_BASED_CR3_STORE_EXITING |
6263 #ifdef CONFIG_X86_64
6264                 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
6265 #endif
6266                 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
6267                 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
6268                 CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
6269                 CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
6270                 CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
6271         /*
6272          * We can allow some features even when not supported by the
6273          * hardware. For example, L1 can specify an MSR bitmap - and we
6274          * can use it to avoid exits to L1 - even when L0 runs L2
6275          * without MSR bitmaps.
6276          */
6277         msrs->procbased_ctls_high |=
6278                 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
6279                 CPU_BASED_USE_MSR_BITMAPS;
6280
6281         /* We support free control of CR3 access interception. */
6282         msrs->procbased_ctls_low &=
6283                 ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
6284
6285         /*
6286          * secondary cpu-based controls.  Do not include those that
6287          * depend on CPUID bits, they are added later by vmx_cpuid_update.
6288          */
6289         if (msrs->procbased_ctls_high & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)
6290                 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
6291                       msrs->secondary_ctls_low,
6292                       msrs->secondary_ctls_high);
6293
6294         msrs->secondary_ctls_low = 0;
6295         msrs->secondary_ctls_high &=
6296                 SECONDARY_EXEC_DESC |
6297                 SECONDARY_EXEC_RDTSCP |
6298                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
6299                 SECONDARY_EXEC_WBINVD_EXITING |
6300                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
6301                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
6302                 SECONDARY_EXEC_RDRAND_EXITING |
6303                 SECONDARY_EXEC_ENABLE_INVPCID |
6304                 SECONDARY_EXEC_RDSEED_EXITING |
6305                 SECONDARY_EXEC_XSAVES;
6306
6307         /*
6308          * We can emulate "VMCS shadowing," even if the hardware
6309          * doesn't support it.
6310          */
6311         msrs->secondary_ctls_high |=
6312                 SECONDARY_EXEC_SHADOW_VMCS;
6313
6314         if (enable_ept) {
6315                 /* nested EPT: emulate EPT also to L1 */
6316                 msrs->secondary_ctls_high |=
6317                         SECONDARY_EXEC_ENABLE_EPT;
6318                 msrs->ept_caps =
6319                         VMX_EPT_PAGE_WALK_4_BIT |
6320                         VMX_EPT_PAGE_WALK_5_BIT |
6321                         VMX_EPTP_WB_BIT |
6322                         VMX_EPT_INVEPT_BIT |
6323                         VMX_EPT_EXECUTE_ONLY_BIT;
6324
6325                 msrs->ept_caps &= ept_caps;
6326                 msrs->ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
6327                         VMX_EPT_EXTENT_CONTEXT_BIT | VMX_EPT_2MB_PAGE_BIT |
6328                         VMX_EPT_1GB_PAGE_BIT;
6329                 if (enable_ept_ad_bits) {
6330                         msrs->secondary_ctls_high |=
6331                                 SECONDARY_EXEC_ENABLE_PML;
6332                         msrs->ept_caps |= VMX_EPT_AD_BIT;
6333                 }
6334         }
6335
6336         if (cpu_has_vmx_vmfunc()) {
6337                 msrs->secondary_ctls_high |=
6338                         SECONDARY_EXEC_ENABLE_VMFUNC;
6339                 /*
6340                  * Advertise EPTP switching unconditionally
6341                  * since we emulate it
6342                  */
6343                 if (enable_ept)
6344                         msrs->vmfunc_controls =
6345                                 VMX_VMFUNC_EPTP_SWITCHING;
6346         }
6347
6348         /*
6349          * Old versions of KVM use the single-context version without
6350          * checking for support, so declare that it is supported even
6351          * though it is treated as global context.  The alternative is
6352          * not failing the single-context invvpid, and it is worse.
6353          */
6354         if (enable_vpid) {
6355                 msrs->secondary_ctls_high |=
6356                         SECONDARY_EXEC_ENABLE_VPID;
6357                 msrs->vpid_caps = VMX_VPID_INVVPID_BIT |
6358                         VMX_VPID_EXTENT_SUPPORTED_MASK;
6359         }
6360
6361         if (enable_unrestricted_guest)
6362                 msrs->secondary_ctls_high |=
6363                         SECONDARY_EXEC_UNRESTRICTED_GUEST;
6364
6365         if (flexpriority_enabled)
6366                 msrs->secondary_ctls_high |=
6367                         SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6368
6369         /* miscellaneous data */
6370         rdmsr(MSR_IA32_VMX_MISC,
6371                 msrs->misc_low,
6372                 msrs->misc_high);
6373         msrs->misc_low &= VMX_MISC_SAVE_EFER_LMA;
6374         msrs->misc_low |=
6375                 MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS |
6376                 VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
6377                 VMX_MISC_ACTIVITY_HLT;
6378         msrs->misc_high = 0;
6379
6380         /*
6381          * This MSR reports some information about VMX support. We
6382          * should return information about the VMX we emulate for the
6383          * guest, and the VMCS structure we give it - not about the
6384          * VMX support of the underlying hardware.
6385          */
6386         msrs->basic =
6387                 VMCS12_REVISION |
6388                 VMX_BASIC_TRUE_CTLS |
6389                 ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
6390                 (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
6391
6392         if (cpu_has_vmx_basic_inout())
6393                 msrs->basic |= VMX_BASIC_INOUT;
6394
6395         /*
6396          * These MSRs specify bits which the guest must keep fixed on
6397          * while L1 is in VMXON mode (in L1's root mode, or running an L2).
6398          * We picked the standard core2 setting.
6399          */
6400 #define VMXON_CR0_ALWAYSON     (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
6401 #define VMXON_CR4_ALWAYSON     X86_CR4_VMXE
6402         msrs->cr0_fixed0 = VMXON_CR0_ALWAYSON;
6403         msrs->cr4_fixed0 = VMXON_CR4_ALWAYSON;
6404
6405         /* These MSRs specify bits which the guest must keep fixed off. */
6406         rdmsrl(MSR_IA32_VMX_CR0_FIXED1, msrs->cr0_fixed1);
6407         rdmsrl(MSR_IA32_VMX_CR4_FIXED1, msrs->cr4_fixed1);
6408
6409         /* highest index: VMX_PREEMPTION_TIMER_VALUE */
6410         msrs->vmcs_enum = VMCS12_MAX_FIELD_INDEX << 1;
6411 }
6412
6413 void nested_vmx_hardware_unsetup(void)
6414 {
6415         int i;
6416
6417         if (enable_shadow_vmcs) {
6418                 for (i = 0; i < VMX_BITMAP_NR; i++)
6419                         free_page((unsigned long)vmx_bitmap[i]);
6420         }
6421 }
6422
6423 __init int nested_vmx_hardware_setup(struct kvm_x86_ops *ops,
6424                                      int (*exit_handlers[])(struct kvm_vcpu *))
6425 {
6426         int i;
6427
6428         if (!cpu_has_vmx_shadow_vmcs())
6429                 enable_shadow_vmcs = 0;
6430         if (enable_shadow_vmcs) {
6431                 for (i = 0; i < VMX_BITMAP_NR; i++) {
6432                         /*
6433                          * The vmx_bitmap is not tied to a VM and so should
6434                          * not be charged to a memcg.
6435                          */
6436                         vmx_bitmap[i] = (unsigned long *)
6437                                 __get_free_page(GFP_KERNEL);
6438                         if (!vmx_bitmap[i]) {
6439                                 nested_vmx_hardware_unsetup();
6440                                 return -ENOMEM;
6441                         }
6442                 }
6443
6444                 init_vmcs_shadow_fields();
6445         }
6446
6447         exit_handlers[EXIT_REASON_VMCLEAR]      = handle_vmclear;
6448         exit_handlers[EXIT_REASON_VMLAUNCH]     = handle_vmlaunch;
6449         exit_handlers[EXIT_REASON_VMPTRLD]      = handle_vmptrld;
6450         exit_handlers[EXIT_REASON_VMPTRST]      = handle_vmptrst;
6451         exit_handlers[EXIT_REASON_VMREAD]       = handle_vmread;
6452         exit_handlers[EXIT_REASON_VMRESUME]     = handle_vmresume;
6453         exit_handlers[EXIT_REASON_VMWRITE]      = handle_vmwrite;
6454         exit_handlers[EXIT_REASON_VMOFF]        = handle_vmoff;
6455         exit_handlers[EXIT_REASON_VMON]         = handle_vmon;
6456         exit_handlers[EXIT_REASON_INVEPT]       = handle_invept;
6457         exit_handlers[EXIT_REASON_INVVPID]      = handle_invvpid;
6458         exit_handlers[EXIT_REASON_VMFUNC]       = handle_vmfunc;
6459
6460         ops->check_nested_events = vmx_check_nested_events;
6461         ops->get_nested_state = vmx_get_nested_state;
6462         ops->set_nested_state = vmx_set_nested_state;
6463         ops->get_vmcs12_pages = nested_get_vmcs12_pages;
6464         ops->nested_enable_evmcs = nested_enable_evmcs;
6465         ops->nested_get_evmcs_version = nested_get_evmcs_version;
6466
6467         return 0;
6468 }