KVM: nVMX: Drop a redundant call to vmx_get_intr_info()
[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_register_cache_reset(vcpu);
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->page_fault_error_code_mask =
1789          *              evmcs->page_fault_error_code_mask;
1790          * vmcs12->page_fault_error_code_match =
1791          *              evmcs->page_fault_error_code_match;
1792          * vmcs12->cr3_target_count = evmcs->cr3_target_count;
1793          * vmcs12->vm_exit_msr_store_count = evmcs->vm_exit_msr_store_count;
1794          * vmcs12->vm_exit_msr_load_count = evmcs->vm_exit_msr_load_count;
1795          * vmcs12->vm_entry_msr_load_count = evmcs->vm_entry_msr_load_count;
1796          */
1797
1798         /*
1799          * Read only fields:
1800          * vmcs12->guest_physical_address = evmcs->guest_physical_address;
1801          * vmcs12->vm_instruction_error = evmcs->vm_instruction_error;
1802          * vmcs12->vm_exit_reason = evmcs->vm_exit_reason;
1803          * vmcs12->vm_exit_intr_info = evmcs->vm_exit_intr_info;
1804          * vmcs12->vm_exit_intr_error_code = evmcs->vm_exit_intr_error_code;
1805          * vmcs12->idt_vectoring_info_field = evmcs->idt_vectoring_info_field;
1806          * vmcs12->idt_vectoring_error_code = evmcs->idt_vectoring_error_code;
1807          * vmcs12->vm_exit_instruction_len = evmcs->vm_exit_instruction_len;
1808          * vmcs12->vmx_instruction_info = evmcs->vmx_instruction_info;
1809          * vmcs12->exit_qualification = evmcs->exit_qualification;
1810          * vmcs12->guest_linear_address = evmcs->guest_linear_address;
1811          *
1812          * Not present in struct vmcs12:
1813          * vmcs12->exit_io_instruction_ecx = evmcs->exit_io_instruction_ecx;
1814          * vmcs12->exit_io_instruction_esi = evmcs->exit_io_instruction_esi;
1815          * vmcs12->exit_io_instruction_edi = evmcs->exit_io_instruction_edi;
1816          * vmcs12->exit_io_instruction_eip = evmcs->exit_io_instruction_eip;
1817          */
1818
1819         return 0;
1820 }
1821
1822 static int copy_vmcs12_to_enlightened(struct vcpu_vmx *vmx)
1823 {
1824         struct vmcs12 *vmcs12 = vmx->nested.cached_vmcs12;
1825         struct hv_enlightened_vmcs *evmcs = vmx->nested.hv_evmcs;
1826
1827         /*
1828          * Should not be changed by KVM:
1829          *
1830          * evmcs->host_es_selector = vmcs12->host_es_selector;
1831          * evmcs->host_cs_selector = vmcs12->host_cs_selector;
1832          * evmcs->host_ss_selector = vmcs12->host_ss_selector;
1833          * evmcs->host_ds_selector = vmcs12->host_ds_selector;
1834          * evmcs->host_fs_selector = vmcs12->host_fs_selector;
1835          * evmcs->host_gs_selector = vmcs12->host_gs_selector;
1836          * evmcs->host_tr_selector = vmcs12->host_tr_selector;
1837          * evmcs->host_ia32_pat = vmcs12->host_ia32_pat;
1838          * evmcs->host_ia32_efer = vmcs12->host_ia32_efer;
1839          * evmcs->host_cr0 = vmcs12->host_cr0;
1840          * evmcs->host_cr3 = vmcs12->host_cr3;
1841          * evmcs->host_cr4 = vmcs12->host_cr4;
1842          * evmcs->host_ia32_sysenter_esp = vmcs12->host_ia32_sysenter_esp;
1843          * evmcs->host_ia32_sysenter_eip = vmcs12->host_ia32_sysenter_eip;
1844          * evmcs->host_rip = vmcs12->host_rip;
1845          * evmcs->host_ia32_sysenter_cs = vmcs12->host_ia32_sysenter_cs;
1846          * evmcs->host_fs_base = vmcs12->host_fs_base;
1847          * evmcs->host_gs_base = vmcs12->host_gs_base;
1848          * evmcs->host_tr_base = vmcs12->host_tr_base;
1849          * evmcs->host_gdtr_base = vmcs12->host_gdtr_base;
1850          * evmcs->host_idtr_base = vmcs12->host_idtr_base;
1851          * evmcs->host_rsp = vmcs12->host_rsp;
1852          * sync_vmcs02_to_vmcs12() doesn't read these:
1853          * evmcs->io_bitmap_a = vmcs12->io_bitmap_a;
1854          * evmcs->io_bitmap_b = vmcs12->io_bitmap_b;
1855          * evmcs->msr_bitmap = vmcs12->msr_bitmap;
1856          * evmcs->ept_pointer = vmcs12->ept_pointer;
1857          * evmcs->xss_exit_bitmap = vmcs12->xss_exit_bitmap;
1858          * evmcs->vm_exit_msr_store_addr = vmcs12->vm_exit_msr_store_addr;
1859          * evmcs->vm_exit_msr_load_addr = vmcs12->vm_exit_msr_load_addr;
1860          * evmcs->vm_entry_msr_load_addr = vmcs12->vm_entry_msr_load_addr;
1861          * evmcs->tpr_threshold = vmcs12->tpr_threshold;
1862          * evmcs->virtual_processor_id = vmcs12->virtual_processor_id;
1863          * evmcs->exception_bitmap = vmcs12->exception_bitmap;
1864          * evmcs->vmcs_link_pointer = vmcs12->vmcs_link_pointer;
1865          * evmcs->pin_based_vm_exec_control = vmcs12->pin_based_vm_exec_control;
1866          * evmcs->vm_exit_controls = vmcs12->vm_exit_controls;
1867          * evmcs->secondary_vm_exec_control = vmcs12->secondary_vm_exec_control;
1868          * evmcs->page_fault_error_code_mask =
1869          *              vmcs12->page_fault_error_code_mask;
1870          * evmcs->page_fault_error_code_match =
1871          *              vmcs12->page_fault_error_code_match;
1872          * evmcs->cr3_target_count = vmcs12->cr3_target_count;
1873          * evmcs->virtual_apic_page_addr = vmcs12->virtual_apic_page_addr;
1874          * evmcs->tsc_offset = vmcs12->tsc_offset;
1875          * evmcs->guest_ia32_debugctl = vmcs12->guest_ia32_debugctl;
1876          * evmcs->cr0_guest_host_mask = vmcs12->cr0_guest_host_mask;
1877          * evmcs->cr4_guest_host_mask = vmcs12->cr4_guest_host_mask;
1878          * evmcs->cr0_read_shadow = vmcs12->cr0_read_shadow;
1879          * evmcs->cr4_read_shadow = vmcs12->cr4_read_shadow;
1880          * evmcs->vm_exit_msr_store_count = vmcs12->vm_exit_msr_store_count;
1881          * evmcs->vm_exit_msr_load_count = vmcs12->vm_exit_msr_load_count;
1882          * evmcs->vm_entry_msr_load_count = vmcs12->vm_entry_msr_load_count;
1883          *
1884          * Not present in struct vmcs12:
1885          * evmcs->exit_io_instruction_ecx = vmcs12->exit_io_instruction_ecx;
1886          * evmcs->exit_io_instruction_esi = vmcs12->exit_io_instruction_esi;
1887          * evmcs->exit_io_instruction_edi = vmcs12->exit_io_instruction_edi;
1888          * evmcs->exit_io_instruction_eip = vmcs12->exit_io_instruction_eip;
1889          */
1890
1891         evmcs->guest_es_selector = vmcs12->guest_es_selector;
1892         evmcs->guest_cs_selector = vmcs12->guest_cs_selector;
1893         evmcs->guest_ss_selector = vmcs12->guest_ss_selector;
1894         evmcs->guest_ds_selector = vmcs12->guest_ds_selector;
1895         evmcs->guest_fs_selector = vmcs12->guest_fs_selector;
1896         evmcs->guest_gs_selector = vmcs12->guest_gs_selector;
1897         evmcs->guest_ldtr_selector = vmcs12->guest_ldtr_selector;
1898         evmcs->guest_tr_selector = vmcs12->guest_tr_selector;
1899
1900         evmcs->guest_es_limit = vmcs12->guest_es_limit;
1901         evmcs->guest_cs_limit = vmcs12->guest_cs_limit;
1902         evmcs->guest_ss_limit = vmcs12->guest_ss_limit;
1903         evmcs->guest_ds_limit = vmcs12->guest_ds_limit;
1904         evmcs->guest_fs_limit = vmcs12->guest_fs_limit;
1905         evmcs->guest_gs_limit = vmcs12->guest_gs_limit;
1906         evmcs->guest_ldtr_limit = vmcs12->guest_ldtr_limit;
1907         evmcs->guest_tr_limit = vmcs12->guest_tr_limit;
1908         evmcs->guest_gdtr_limit = vmcs12->guest_gdtr_limit;
1909         evmcs->guest_idtr_limit = vmcs12->guest_idtr_limit;
1910
1911         evmcs->guest_es_ar_bytes = vmcs12->guest_es_ar_bytes;
1912         evmcs->guest_cs_ar_bytes = vmcs12->guest_cs_ar_bytes;
1913         evmcs->guest_ss_ar_bytes = vmcs12->guest_ss_ar_bytes;
1914         evmcs->guest_ds_ar_bytes = vmcs12->guest_ds_ar_bytes;
1915         evmcs->guest_fs_ar_bytes = vmcs12->guest_fs_ar_bytes;
1916         evmcs->guest_gs_ar_bytes = vmcs12->guest_gs_ar_bytes;
1917         evmcs->guest_ldtr_ar_bytes = vmcs12->guest_ldtr_ar_bytes;
1918         evmcs->guest_tr_ar_bytes = vmcs12->guest_tr_ar_bytes;
1919
1920         evmcs->guest_es_base = vmcs12->guest_es_base;
1921         evmcs->guest_cs_base = vmcs12->guest_cs_base;
1922         evmcs->guest_ss_base = vmcs12->guest_ss_base;
1923         evmcs->guest_ds_base = vmcs12->guest_ds_base;
1924         evmcs->guest_fs_base = vmcs12->guest_fs_base;
1925         evmcs->guest_gs_base = vmcs12->guest_gs_base;
1926         evmcs->guest_ldtr_base = vmcs12->guest_ldtr_base;
1927         evmcs->guest_tr_base = vmcs12->guest_tr_base;
1928         evmcs->guest_gdtr_base = vmcs12->guest_gdtr_base;
1929         evmcs->guest_idtr_base = vmcs12->guest_idtr_base;
1930
1931         evmcs->guest_ia32_pat = vmcs12->guest_ia32_pat;
1932         evmcs->guest_ia32_efer = vmcs12->guest_ia32_efer;
1933
1934         evmcs->guest_pdptr0 = vmcs12->guest_pdptr0;
1935         evmcs->guest_pdptr1 = vmcs12->guest_pdptr1;
1936         evmcs->guest_pdptr2 = vmcs12->guest_pdptr2;
1937         evmcs->guest_pdptr3 = vmcs12->guest_pdptr3;
1938
1939         evmcs->guest_pending_dbg_exceptions =
1940                 vmcs12->guest_pending_dbg_exceptions;
1941         evmcs->guest_sysenter_esp = vmcs12->guest_sysenter_esp;
1942         evmcs->guest_sysenter_eip = vmcs12->guest_sysenter_eip;
1943
1944         evmcs->guest_activity_state = vmcs12->guest_activity_state;
1945         evmcs->guest_sysenter_cs = vmcs12->guest_sysenter_cs;
1946
1947         evmcs->guest_cr0 = vmcs12->guest_cr0;
1948         evmcs->guest_cr3 = vmcs12->guest_cr3;
1949         evmcs->guest_cr4 = vmcs12->guest_cr4;
1950         evmcs->guest_dr7 = vmcs12->guest_dr7;
1951
1952         evmcs->guest_physical_address = vmcs12->guest_physical_address;
1953
1954         evmcs->vm_instruction_error = vmcs12->vm_instruction_error;
1955         evmcs->vm_exit_reason = vmcs12->vm_exit_reason;
1956         evmcs->vm_exit_intr_info = vmcs12->vm_exit_intr_info;
1957         evmcs->vm_exit_intr_error_code = vmcs12->vm_exit_intr_error_code;
1958         evmcs->idt_vectoring_info_field = vmcs12->idt_vectoring_info_field;
1959         evmcs->idt_vectoring_error_code = vmcs12->idt_vectoring_error_code;
1960         evmcs->vm_exit_instruction_len = vmcs12->vm_exit_instruction_len;
1961         evmcs->vmx_instruction_info = vmcs12->vmx_instruction_info;
1962
1963         evmcs->exit_qualification = vmcs12->exit_qualification;
1964
1965         evmcs->guest_linear_address = vmcs12->guest_linear_address;
1966         evmcs->guest_rsp = vmcs12->guest_rsp;
1967         evmcs->guest_rflags = vmcs12->guest_rflags;
1968
1969         evmcs->guest_interruptibility_info =
1970                 vmcs12->guest_interruptibility_info;
1971         evmcs->cpu_based_vm_exec_control = vmcs12->cpu_based_vm_exec_control;
1972         evmcs->vm_entry_controls = vmcs12->vm_entry_controls;
1973         evmcs->vm_entry_intr_info_field = vmcs12->vm_entry_intr_info_field;
1974         evmcs->vm_entry_exception_error_code =
1975                 vmcs12->vm_entry_exception_error_code;
1976         evmcs->vm_entry_instruction_len = vmcs12->vm_entry_instruction_len;
1977
1978         evmcs->guest_rip = vmcs12->guest_rip;
1979
1980         evmcs->guest_bndcfgs = vmcs12->guest_bndcfgs;
1981
1982         return 0;
1983 }
1984
1985 /*
1986  * This is an equivalent of the nested hypervisor executing the vmptrld
1987  * instruction.
1988  */
1989 static enum nested_evmptrld_status nested_vmx_handle_enlightened_vmptrld(
1990         struct kvm_vcpu *vcpu, bool from_launch)
1991 {
1992         struct vcpu_vmx *vmx = to_vmx(vcpu);
1993         bool evmcs_gpa_changed = false;
1994         u64 evmcs_gpa;
1995
1996         if (likely(!vmx->nested.enlightened_vmcs_enabled))
1997                 return EVMPTRLD_DISABLED;
1998
1999         if (!nested_enlightened_vmentry(vcpu, &evmcs_gpa))
2000                 return EVMPTRLD_DISABLED;
2001
2002         if (unlikely(!vmx->nested.hv_evmcs ||
2003                      evmcs_gpa != vmx->nested.hv_evmcs_vmptr)) {
2004                 if (!vmx->nested.hv_evmcs)
2005                         vmx->nested.current_vmptr = -1ull;
2006
2007                 nested_release_evmcs(vcpu);
2008
2009                 if (kvm_vcpu_map(vcpu, gpa_to_gfn(evmcs_gpa),
2010                                  &vmx->nested.hv_evmcs_map))
2011                         return EVMPTRLD_ERROR;
2012
2013                 vmx->nested.hv_evmcs = vmx->nested.hv_evmcs_map.hva;
2014
2015                 /*
2016                  * Currently, KVM only supports eVMCS version 1
2017                  * (== KVM_EVMCS_VERSION) and thus we expect guest to set this
2018                  * value to first u32 field of eVMCS which should specify eVMCS
2019                  * VersionNumber.
2020                  *
2021                  * Guest should be aware of supported eVMCS versions by host by
2022                  * examining CPUID.0x4000000A.EAX[0:15]. Host userspace VMM is
2023                  * expected to set this CPUID leaf according to the value
2024                  * returned in vmcs_version from nested_enable_evmcs().
2025                  *
2026                  * However, it turns out that Microsoft Hyper-V fails to comply
2027                  * to their own invented interface: When Hyper-V use eVMCS, it
2028                  * just sets first u32 field of eVMCS to revision_id specified
2029                  * in MSR_IA32_VMX_BASIC. Instead of used eVMCS version number
2030                  * which is one of the supported versions specified in
2031                  * CPUID.0x4000000A.EAX[0:15].
2032                  *
2033                  * To overcome Hyper-V bug, we accept here either a supported
2034                  * eVMCS version or VMCS12 revision_id as valid values for first
2035                  * u32 field of eVMCS.
2036                  */
2037                 if ((vmx->nested.hv_evmcs->revision_id != KVM_EVMCS_VERSION) &&
2038                     (vmx->nested.hv_evmcs->revision_id != VMCS12_REVISION)) {
2039                         nested_release_evmcs(vcpu);
2040                         return EVMPTRLD_VMFAIL;
2041                 }
2042
2043                 vmx->nested.dirty_vmcs12 = true;
2044                 vmx->nested.hv_evmcs_vmptr = evmcs_gpa;
2045
2046                 evmcs_gpa_changed = true;
2047                 /*
2048                  * Unlike normal vmcs12, enlightened vmcs12 is not fully
2049                  * reloaded from guest's memory (read only fields, fields not
2050                  * present in struct hv_enlightened_vmcs, ...). Make sure there
2051                  * are no leftovers.
2052                  */
2053                 if (from_launch) {
2054                         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2055                         memset(vmcs12, 0, sizeof(*vmcs12));
2056                         vmcs12->hdr.revision_id = VMCS12_REVISION;
2057                 }
2058
2059         }
2060
2061         /*
2062          * Clean fields data can't be used on VMLAUNCH and when we switch
2063          * between different L2 guests as KVM keeps a single VMCS12 per L1.
2064          */
2065         if (from_launch || evmcs_gpa_changed)
2066                 vmx->nested.hv_evmcs->hv_clean_fields &=
2067                         ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
2068
2069         return EVMPTRLD_SUCCEEDED;
2070 }
2071
2072 void nested_sync_vmcs12_to_shadow(struct kvm_vcpu *vcpu)
2073 {
2074         struct vcpu_vmx *vmx = to_vmx(vcpu);
2075
2076         if (vmx->nested.hv_evmcs) {
2077                 copy_vmcs12_to_enlightened(vmx);
2078                 /* All fields are clean */
2079                 vmx->nested.hv_evmcs->hv_clean_fields |=
2080                         HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
2081         } else {
2082                 copy_vmcs12_to_shadow(vmx);
2083         }
2084
2085         vmx->nested.need_vmcs12_to_shadow_sync = false;
2086 }
2087
2088 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
2089 {
2090         struct vcpu_vmx *vmx =
2091                 container_of(timer, struct vcpu_vmx, nested.preemption_timer);
2092
2093         vmx->nested.preemption_timer_expired = true;
2094         kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
2095         kvm_vcpu_kick(&vmx->vcpu);
2096
2097         return HRTIMER_NORESTART;
2098 }
2099
2100 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
2101 {
2102         u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
2103         struct vcpu_vmx *vmx = to_vmx(vcpu);
2104
2105         /*
2106          * A timer value of zero is architecturally guaranteed to cause
2107          * a VMExit prior to executing any instructions in the guest.
2108          */
2109         if (preemption_timeout == 0) {
2110                 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
2111                 return;
2112         }
2113
2114         if (vcpu->arch.virtual_tsc_khz == 0)
2115                 return;
2116
2117         preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
2118         preemption_timeout *= 1000000;
2119         do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
2120         hrtimer_start(&vmx->nested.preemption_timer,
2121                       ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
2122 }
2123
2124 static u64 nested_vmx_calc_efer(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
2125 {
2126         if (vmx->nested.nested_run_pending &&
2127             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
2128                 return vmcs12->guest_ia32_efer;
2129         else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
2130                 return vmx->vcpu.arch.efer | (EFER_LMA | EFER_LME);
2131         else
2132                 return vmx->vcpu.arch.efer & ~(EFER_LMA | EFER_LME);
2133 }
2134
2135 static void prepare_vmcs02_constant_state(struct vcpu_vmx *vmx)
2136 {
2137         /*
2138          * If vmcs02 hasn't been initialized, set the constant vmcs02 state
2139          * according to L0's settings (vmcs12 is irrelevant here).  Host
2140          * fields that come from L0 and are not constant, e.g. HOST_CR3,
2141          * will be set as needed prior to VMLAUNCH/VMRESUME.
2142          */
2143         if (vmx->nested.vmcs02_initialized)
2144                 return;
2145         vmx->nested.vmcs02_initialized = true;
2146
2147         /*
2148          * We don't care what the EPTP value is we just need to guarantee
2149          * it's valid so we don't get a false positive when doing early
2150          * consistency checks.
2151          */
2152         if (enable_ept && nested_early_check)
2153                 vmcs_write64(EPT_POINTER, construct_eptp(&vmx->vcpu, 0));
2154
2155         /* All VMFUNCs are currently emulated through L0 vmexits.  */
2156         if (cpu_has_vmx_vmfunc())
2157                 vmcs_write64(VM_FUNCTION_CONTROL, 0);
2158
2159         if (cpu_has_vmx_posted_intr())
2160                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
2161
2162         if (cpu_has_vmx_msr_bitmap())
2163                 vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
2164
2165         /*
2166          * The PML address never changes, so it is constant in vmcs02.
2167          * Conceptually we want to copy the PML index from vmcs01 here,
2168          * and then back to vmcs01 on nested vmexit.  But since we flush
2169          * the log and reset GUEST_PML_INDEX on each vmexit, the PML
2170          * index is also effectively constant in vmcs02.
2171          */
2172         if (enable_pml) {
2173                 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
2174                 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
2175         }
2176
2177         if (cpu_has_vmx_encls_vmexit())
2178                 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
2179
2180         /*
2181          * Set the MSR load/store lists to match L0's settings.  Only the
2182          * addresses are constant (for vmcs02), the counts can change based
2183          * on L2's behavior, e.g. switching to/from long mode.
2184          */
2185         vmcs_write64(VM_EXIT_MSR_STORE_ADDR, __pa(vmx->msr_autostore.guest.val));
2186         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
2187         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
2188
2189         vmx_set_constant_host_state(vmx);
2190 }
2191
2192 static void prepare_vmcs02_early_rare(struct vcpu_vmx *vmx,
2193                                       struct vmcs12 *vmcs12)
2194 {
2195         prepare_vmcs02_constant_state(vmx);
2196
2197         vmcs_write64(VMCS_LINK_POINTER, -1ull);
2198
2199         if (enable_vpid) {
2200                 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02)
2201                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
2202                 else
2203                         vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
2204         }
2205 }
2206
2207 static void prepare_vmcs02_early(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
2208 {
2209         u32 exec_control, vmcs12_exec_ctrl;
2210         u64 guest_efer = nested_vmx_calc_efer(vmx, vmcs12);
2211
2212         if (vmx->nested.dirty_vmcs12 || vmx->nested.hv_evmcs)
2213                 prepare_vmcs02_early_rare(vmx, vmcs12);
2214
2215         /*
2216          * PIN CONTROLS
2217          */
2218         exec_control = vmx_pin_based_exec_ctrl(vmx);
2219         exec_control |= (vmcs12->pin_based_vm_exec_control &
2220                          ~PIN_BASED_VMX_PREEMPTION_TIMER);
2221
2222         /* Posted interrupts setting is only taken from vmcs12.  */
2223         if (nested_cpu_has_posted_intr(vmcs12)) {
2224                 vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
2225                 vmx->nested.pi_pending = false;
2226         } else {
2227                 exec_control &= ~PIN_BASED_POSTED_INTR;
2228         }
2229         pin_controls_set(vmx, exec_control);
2230
2231         /*
2232          * EXEC CONTROLS
2233          */
2234         exec_control = vmx_exec_control(vmx); /* L0's desires */
2235         exec_control &= ~CPU_BASED_INTR_WINDOW_EXITING;
2236         exec_control &= ~CPU_BASED_NMI_WINDOW_EXITING;
2237         exec_control &= ~CPU_BASED_TPR_SHADOW;
2238         exec_control |= vmcs12->cpu_based_vm_exec_control;
2239
2240         vmx->nested.l1_tpr_threshold = -1;
2241         if (exec_control & CPU_BASED_TPR_SHADOW)
2242                 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
2243 #ifdef CONFIG_X86_64
2244         else
2245                 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
2246                                 CPU_BASED_CR8_STORE_EXITING;
2247 #endif
2248
2249         /*
2250          * A vmexit (to either L1 hypervisor or L0 userspace) is always needed
2251          * for I/O port accesses.
2252          */
2253         exec_control |= CPU_BASED_UNCOND_IO_EXITING;
2254         exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
2255
2256         /*
2257          * This bit will be computed in nested_get_vmcs12_pages, because
2258          * we do not have access to L1's MSR bitmap yet.  For now, keep
2259          * the same bit as before, hoping to avoid multiple VMWRITEs that
2260          * only set/clear this bit.
2261          */
2262         exec_control &= ~CPU_BASED_USE_MSR_BITMAPS;
2263         exec_control |= exec_controls_get(vmx) & CPU_BASED_USE_MSR_BITMAPS;
2264
2265         exec_controls_set(vmx, exec_control);
2266
2267         /*
2268          * SECONDARY EXEC CONTROLS
2269          */
2270         if (cpu_has_secondary_exec_ctrls()) {
2271                 exec_control = vmx->secondary_exec_control;
2272
2273                 /* Take the following fields only from vmcs12 */
2274                 exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2275                                   SECONDARY_EXEC_ENABLE_INVPCID |
2276                                   SECONDARY_EXEC_RDTSCP |
2277                                   SECONDARY_EXEC_XSAVES |
2278                                   SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE |
2279                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2280                                   SECONDARY_EXEC_APIC_REGISTER_VIRT |
2281                                   SECONDARY_EXEC_ENABLE_VMFUNC);
2282                 if (nested_cpu_has(vmcs12,
2283                                    CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
2284                         vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
2285                                 ~SECONDARY_EXEC_ENABLE_PML;
2286                         exec_control |= vmcs12_exec_ctrl;
2287                 }
2288
2289                 /* VMCS shadowing for L2 is emulated for now */
2290                 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
2291
2292                 /*
2293                  * Preset *DT exiting when emulating UMIP, so that vmx_set_cr4()
2294                  * will not have to rewrite the controls just for this bit.
2295                  */
2296                 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated() &&
2297                     (vmcs12->guest_cr4 & X86_CR4_UMIP))
2298                         exec_control |= SECONDARY_EXEC_DESC;
2299
2300                 if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
2301                         vmcs_write16(GUEST_INTR_STATUS,
2302                                 vmcs12->guest_intr_status);
2303
2304                 secondary_exec_controls_set(vmx, exec_control);
2305         }
2306
2307         /*
2308          * ENTRY CONTROLS
2309          *
2310          * vmcs12's VM_{ENTRY,EXIT}_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE
2311          * are emulated by vmx_set_efer() in prepare_vmcs02(), but speculate
2312          * on the related bits (if supported by the CPU) in the hope that
2313          * we can avoid VMWrites during vmx_set_efer().
2314          */
2315         exec_control = (vmcs12->vm_entry_controls | vmx_vmentry_ctrl()) &
2316                         ~VM_ENTRY_IA32E_MODE & ~VM_ENTRY_LOAD_IA32_EFER;
2317         if (cpu_has_load_ia32_efer()) {
2318                 if (guest_efer & EFER_LMA)
2319                         exec_control |= VM_ENTRY_IA32E_MODE;
2320                 if (guest_efer != host_efer)
2321                         exec_control |= VM_ENTRY_LOAD_IA32_EFER;
2322         }
2323         vm_entry_controls_set(vmx, exec_control);
2324
2325         /*
2326          * EXIT CONTROLS
2327          *
2328          * L2->L1 exit controls are emulated - the hardware exit is to L0 so
2329          * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
2330          * bits may be modified by vmx_set_efer() in prepare_vmcs02().
2331          */
2332         exec_control = vmx_vmexit_ctrl();
2333         if (cpu_has_load_ia32_efer() && guest_efer != host_efer)
2334                 exec_control |= VM_EXIT_LOAD_IA32_EFER;
2335         vm_exit_controls_set(vmx, exec_control);
2336
2337         /*
2338          * Interrupt/Exception Fields
2339          */
2340         if (vmx->nested.nested_run_pending) {
2341                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
2342                              vmcs12->vm_entry_intr_info_field);
2343                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
2344                              vmcs12->vm_entry_exception_error_code);
2345                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
2346                              vmcs12->vm_entry_instruction_len);
2347                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
2348                              vmcs12->guest_interruptibility_info);
2349                 vmx->loaded_vmcs->nmi_known_unmasked =
2350                         !(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
2351         } else {
2352                 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
2353         }
2354 }
2355
2356 static void prepare_vmcs02_rare(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
2357 {
2358         struct hv_enlightened_vmcs *hv_evmcs = vmx->nested.hv_evmcs;
2359
2360         if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
2361                            HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP2)) {
2362                 vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
2363                 vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
2364                 vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
2365                 vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
2366                 vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
2367                 vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
2368                 vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
2369                 vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
2370                 vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
2371                 vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
2372                 vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
2373                 vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
2374                 vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
2375                 vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
2376                 vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
2377                 vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
2378                 vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
2379                 vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
2380                 vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
2381                 vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
2382                 vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
2383                 vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
2384                 vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
2385                 vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
2386                 vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
2387                 vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
2388                 vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
2389                 vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
2390                 vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
2391                 vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
2392                 vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
2393                 vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
2394                 vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
2395                 vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
2396                 vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
2397                 vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
2398         }
2399
2400         if (!hv_evmcs || !(hv_evmcs->hv_clean_fields &
2401                            HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1)) {
2402                 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
2403                 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
2404                             vmcs12->guest_pending_dbg_exceptions);
2405                 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
2406                 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
2407
2408                 /*
2409                  * L1 may access the L2's PDPTR, so save them to construct
2410                  * vmcs12
2411                  */
2412                 if (enable_ept) {
2413                         vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
2414                         vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
2415                         vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
2416                         vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
2417                 }
2418
2419                 if (kvm_mpx_supported() && vmx->nested.nested_run_pending &&
2420                     (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
2421                         vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
2422         }
2423
2424         if (nested_cpu_has_xsaves(vmcs12))
2425                 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
2426
2427         /*
2428          * Whether page-faults are trapped is determined by a combination of
2429          * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
2430          * If enable_ept, L0 doesn't care about page faults and we should
2431          * set all of these to L1's desires. However, if !enable_ept, L0 does
2432          * care about (at least some) page faults, and because it is not easy
2433          * (if at all possible?) to merge L0 and L1's desires, we simply ask
2434          * to exit on each and every L2 page fault. This is done by setting
2435          * MASK=MATCH=0 and (see below) EB.PF=1.
2436          * Note that below we don't need special code to set EB.PF beyond the
2437          * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
2438          * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
2439          * !enable_ept, EB.PF is 1, so the "or" will always be 1.
2440          */
2441         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
2442                 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
2443         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
2444                 enable_ept ? vmcs12->page_fault_error_code_match : 0);
2445
2446         if (cpu_has_vmx_apicv()) {
2447                 vmcs_write64(EOI_EXIT_BITMAP0, vmcs12->eoi_exit_bitmap0);
2448                 vmcs_write64(EOI_EXIT_BITMAP1, vmcs12->eoi_exit_bitmap1);
2449                 vmcs_write64(EOI_EXIT_BITMAP2, vmcs12->eoi_exit_bitmap2);
2450                 vmcs_write64(EOI_EXIT_BITMAP3, vmcs12->eoi_exit_bitmap3);
2451         }
2452
2453         /*
2454          * Make sure the msr_autostore list is up to date before we set the
2455          * count in the vmcs02.
2456          */
2457         prepare_vmx_msr_autostore_list(&vmx->vcpu, MSR_IA32_TSC);
2458
2459         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, vmx->msr_autostore.guest.nr);
2460         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
2461         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
2462
2463         set_cr4_guest_host_mask(vmx);
2464 }
2465
2466 /*
2467  * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
2468  * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
2469  * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
2470  * guest in a way that will both be appropriate to L1's requests, and our
2471  * needs. In addition to modifying the active vmcs (which is vmcs02), this
2472  * function also has additional necessary side-effects, like setting various
2473  * vcpu->arch fields.
2474  * Returns 0 on success, 1 on failure. Invalid state exit qualification code
2475  * is assigned to entry_failure_code on failure.
2476  */
2477 static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
2478                           u32 *entry_failure_code)
2479 {
2480         struct vcpu_vmx *vmx = to_vmx(vcpu);
2481         struct hv_enlightened_vmcs *hv_evmcs = vmx->nested.hv_evmcs;
2482         bool load_guest_pdptrs_vmcs12 = false;
2483
2484         if (vmx->nested.dirty_vmcs12 || hv_evmcs) {
2485                 prepare_vmcs02_rare(vmx, vmcs12);
2486                 vmx->nested.dirty_vmcs12 = false;
2487
2488                 load_guest_pdptrs_vmcs12 = !hv_evmcs ||
2489                         !(hv_evmcs->hv_clean_fields &
2490                           HV_VMX_ENLIGHTENED_CLEAN_FIELD_GUEST_GRP1);
2491         }
2492
2493         if (vmx->nested.nested_run_pending &&
2494             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
2495                 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
2496                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
2497         } else {
2498                 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
2499                 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
2500         }
2501         if (kvm_mpx_supported() && (!vmx->nested.nested_run_pending ||
2502             !(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)))
2503                 vmcs_write64(GUEST_BNDCFGS, vmx->nested.vmcs01_guest_bndcfgs);
2504         vmx_set_rflags(vcpu, vmcs12->guest_rflags);
2505
2506         /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
2507          * bitwise-or of what L1 wants to trap for L2, and what we want to
2508          * trap. Note that CR0.TS also needs updating - we do this later.
2509          */
2510         update_exception_bitmap(vcpu);
2511         vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
2512         vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
2513
2514         if (vmx->nested.nested_run_pending &&
2515             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
2516                 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
2517                 vcpu->arch.pat = vmcs12->guest_ia32_pat;
2518         } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2519                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
2520         }
2521
2522         vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
2523
2524         if (kvm_has_tsc_control)
2525                 decache_tsc_multiplier(vmx);
2526
2527         nested_vmx_transition_tlb_flush(vcpu, vmcs12, true);
2528
2529         if (nested_cpu_has_ept(vmcs12))
2530                 nested_ept_init_mmu_context(vcpu);
2531
2532         /*
2533          * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
2534          * bits which we consider mandatory enabled.
2535          * The CR0_READ_SHADOW is what L2 should have expected to read given
2536          * the specifications by L1; It's not enough to take
2537          * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
2538          * have more bits than L1 expected.
2539          */
2540         vmx_set_cr0(vcpu, vmcs12->guest_cr0);
2541         vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
2542
2543         vmx_set_cr4(vcpu, vmcs12->guest_cr4);
2544         vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
2545
2546         vcpu->arch.efer = nested_vmx_calc_efer(vmx, vmcs12);
2547         /* Note: may modify VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
2548         vmx_set_efer(vcpu, vcpu->arch.efer);
2549
2550         /*
2551          * Guest state is invalid and unrestricted guest is disabled,
2552          * which means L1 attempted VMEntry to L2 with invalid state.
2553          * Fail the VMEntry.
2554          */
2555         if (vmx->emulation_required) {
2556                 *entry_failure_code = ENTRY_FAIL_DEFAULT;
2557                 return -EINVAL;
2558         }
2559
2560         /* Shadow page tables on either EPT or shadow page tables. */
2561         if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
2562                                 entry_failure_code))
2563                 return -EINVAL;
2564
2565         /*
2566          * Immediately write vmcs02.GUEST_CR3.  It will be propagated to vmcs12
2567          * on nested VM-Exit, which can occur without actually running L2 and
2568          * thus without hitting vmx_load_mmu_pgd(), e.g. if L1 is entering L2 with
2569          * vmcs12.GUEST_ACTIVITYSTATE=HLT, in which case KVM will intercept the
2570          * transition to HLT instead of running L2.
2571          */
2572         if (enable_ept)
2573                 vmcs_writel(GUEST_CR3, vmcs12->guest_cr3);
2574
2575         /* Late preparation of GUEST_PDPTRs now that EFER and CRs are set. */
2576         if (load_guest_pdptrs_vmcs12 && nested_cpu_has_ept(vmcs12) &&
2577             is_pae_paging(vcpu)) {
2578                 vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
2579                 vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
2580                 vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
2581                 vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
2582         }
2583
2584         if (!enable_ept)
2585                 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
2586
2587         if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL) &&
2588             WARN_ON_ONCE(kvm_set_msr(vcpu, MSR_CORE_PERF_GLOBAL_CTRL,
2589                                      vmcs12->guest_ia32_perf_global_ctrl)))
2590                 return -EINVAL;
2591
2592         kvm_rsp_write(vcpu, vmcs12->guest_rsp);
2593         kvm_rip_write(vcpu, vmcs12->guest_rip);
2594         return 0;
2595 }
2596
2597 static int nested_vmx_check_nmi_controls(struct vmcs12 *vmcs12)
2598 {
2599         if (CC(!nested_cpu_has_nmi_exiting(vmcs12) &&
2600                nested_cpu_has_virtual_nmis(vmcs12)))
2601                 return -EINVAL;
2602
2603         if (CC(!nested_cpu_has_virtual_nmis(vmcs12) &&
2604                nested_cpu_has(vmcs12, CPU_BASED_NMI_WINDOW_EXITING)))
2605                 return -EINVAL;
2606
2607         return 0;
2608 }
2609
2610 static bool nested_vmx_check_eptp(struct kvm_vcpu *vcpu, u64 new_eptp)
2611 {
2612         struct vcpu_vmx *vmx = to_vmx(vcpu);
2613         int maxphyaddr = cpuid_maxphyaddr(vcpu);
2614
2615         /* Check for memory type validity */
2616         switch (new_eptp & VMX_EPTP_MT_MASK) {
2617         case VMX_EPTP_MT_UC:
2618                 if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPTP_UC_BIT)))
2619                         return false;
2620                 break;
2621         case VMX_EPTP_MT_WB:
2622                 if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPTP_WB_BIT)))
2623                         return false;
2624                 break;
2625         default:
2626                 return false;
2627         }
2628
2629         /* Page-walk levels validity. */
2630         switch (new_eptp & VMX_EPTP_PWL_MASK) {
2631         case VMX_EPTP_PWL_5:
2632                 if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPT_PAGE_WALK_5_BIT)))
2633                         return false;
2634                 break;
2635         case VMX_EPTP_PWL_4:
2636                 if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPT_PAGE_WALK_4_BIT)))
2637                         return false;
2638                 break;
2639         default:
2640                 return false;
2641         }
2642
2643         /* Reserved bits should not be set */
2644         if (CC(new_eptp >> maxphyaddr || ((new_eptp >> 7) & 0x1f)))
2645                 return false;
2646
2647         /* AD, if set, should be supported */
2648         if (new_eptp & VMX_EPTP_AD_ENABLE_BIT) {
2649                 if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPT_AD_BIT)))
2650                         return false;
2651         }
2652
2653         return true;
2654 }
2655
2656 /*
2657  * Checks related to VM-Execution Control Fields
2658  */
2659 static int nested_check_vm_execution_controls(struct kvm_vcpu *vcpu,
2660                                               struct vmcs12 *vmcs12)
2661 {
2662         struct vcpu_vmx *vmx = to_vmx(vcpu);
2663
2664         if (CC(!vmx_control_verify(vmcs12->pin_based_vm_exec_control,
2665                                    vmx->nested.msrs.pinbased_ctls_low,
2666                                    vmx->nested.msrs.pinbased_ctls_high)) ||
2667             CC(!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
2668                                    vmx->nested.msrs.procbased_ctls_low,
2669                                    vmx->nested.msrs.procbased_ctls_high)))
2670                 return -EINVAL;
2671
2672         if (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
2673             CC(!vmx_control_verify(vmcs12->secondary_vm_exec_control,
2674                                    vmx->nested.msrs.secondary_ctls_low,
2675                                    vmx->nested.msrs.secondary_ctls_high)))
2676                 return -EINVAL;
2677
2678         if (CC(vmcs12->cr3_target_count > nested_cpu_vmx_misc_cr3_count(vcpu)) ||
2679             nested_vmx_check_io_bitmap_controls(vcpu, vmcs12) ||
2680             nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12) ||
2681             nested_vmx_check_tpr_shadow_controls(vcpu, vmcs12) ||
2682             nested_vmx_check_apic_access_controls(vcpu, vmcs12) ||
2683             nested_vmx_check_apicv_controls(vcpu, vmcs12) ||
2684             nested_vmx_check_nmi_controls(vmcs12) ||
2685             nested_vmx_check_pml_controls(vcpu, vmcs12) ||
2686             nested_vmx_check_unrestricted_guest_controls(vcpu, vmcs12) ||
2687             nested_vmx_check_mode_based_ept_exec_controls(vcpu, vmcs12) ||
2688             nested_vmx_check_shadow_vmcs_controls(vcpu, vmcs12) ||
2689             CC(nested_cpu_has_vpid(vmcs12) && !vmcs12->virtual_processor_id))
2690                 return -EINVAL;
2691
2692         if (!nested_cpu_has_preemption_timer(vmcs12) &&
2693             nested_cpu_has_save_preemption_timer(vmcs12))
2694                 return -EINVAL;
2695
2696         if (nested_cpu_has_ept(vmcs12) &&
2697             CC(!nested_vmx_check_eptp(vcpu, vmcs12->ept_pointer)))
2698                 return -EINVAL;
2699
2700         if (nested_cpu_has_vmfunc(vmcs12)) {
2701                 if (CC(vmcs12->vm_function_control &
2702                        ~vmx->nested.msrs.vmfunc_controls))
2703                         return -EINVAL;
2704
2705                 if (nested_cpu_has_eptp_switching(vmcs12)) {
2706                         if (CC(!nested_cpu_has_ept(vmcs12)) ||
2707                             CC(!page_address_valid(vcpu, vmcs12->eptp_list_address)))
2708                                 return -EINVAL;
2709                 }
2710         }
2711
2712         return 0;
2713 }
2714
2715 /*
2716  * Checks related to VM-Exit Control Fields
2717  */
2718 static int nested_check_vm_exit_controls(struct kvm_vcpu *vcpu,
2719                                          struct vmcs12 *vmcs12)
2720 {
2721         struct vcpu_vmx *vmx = to_vmx(vcpu);
2722
2723         if (CC(!vmx_control_verify(vmcs12->vm_exit_controls,
2724                                     vmx->nested.msrs.exit_ctls_low,
2725                                     vmx->nested.msrs.exit_ctls_high)) ||
2726             CC(nested_vmx_check_exit_msr_switch_controls(vcpu, vmcs12)))
2727                 return -EINVAL;
2728
2729         return 0;
2730 }
2731
2732 /*
2733  * Checks related to VM-Entry Control Fields
2734  */
2735 static int nested_check_vm_entry_controls(struct kvm_vcpu *vcpu,
2736                                           struct vmcs12 *vmcs12)
2737 {
2738         struct vcpu_vmx *vmx = to_vmx(vcpu);
2739
2740         if (CC(!vmx_control_verify(vmcs12->vm_entry_controls,
2741                                     vmx->nested.msrs.entry_ctls_low,
2742                                     vmx->nested.msrs.entry_ctls_high)))
2743                 return -EINVAL;
2744
2745         /*
2746          * From the Intel SDM, volume 3:
2747          * Fields relevant to VM-entry event injection must be set properly.
2748          * These fields are the VM-entry interruption-information field, the
2749          * VM-entry exception error code, and the VM-entry instruction length.
2750          */
2751         if (vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) {
2752                 u32 intr_info = vmcs12->vm_entry_intr_info_field;
2753                 u8 vector = intr_info & INTR_INFO_VECTOR_MASK;
2754                 u32 intr_type = intr_info & INTR_INFO_INTR_TYPE_MASK;
2755                 bool has_error_code = intr_info & INTR_INFO_DELIVER_CODE_MASK;
2756                 bool should_have_error_code;
2757                 bool urg = nested_cpu_has2(vmcs12,
2758                                            SECONDARY_EXEC_UNRESTRICTED_GUEST);
2759                 bool prot_mode = !urg || vmcs12->guest_cr0 & X86_CR0_PE;
2760
2761                 /* VM-entry interruption-info field: interruption type */
2762                 if (CC(intr_type == INTR_TYPE_RESERVED) ||
2763                     CC(intr_type == INTR_TYPE_OTHER_EVENT &&
2764                        !nested_cpu_supports_monitor_trap_flag(vcpu)))
2765                         return -EINVAL;
2766
2767                 /* VM-entry interruption-info field: vector */
2768                 if (CC(intr_type == INTR_TYPE_NMI_INTR && vector != NMI_VECTOR) ||
2769                     CC(intr_type == INTR_TYPE_HARD_EXCEPTION && vector > 31) ||
2770                     CC(intr_type == INTR_TYPE_OTHER_EVENT && vector != 0))
2771                         return -EINVAL;
2772
2773                 /* VM-entry interruption-info field: deliver error code */
2774                 should_have_error_code =
2775                         intr_type == INTR_TYPE_HARD_EXCEPTION && prot_mode &&
2776                         x86_exception_has_error_code(vector);
2777                 if (CC(has_error_code != should_have_error_code))
2778                         return -EINVAL;
2779
2780                 /* VM-entry exception error code */
2781                 if (CC(has_error_code &&
2782                        vmcs12->vm_entry_exception_error_code & GENMASK(31, 16)))
2783                         return -EINVAL;
2784
2785                 /* VM-entry interruption-info field: reserved bits */
2786                 if (CC(intr_info & INTR_INFO_RESVD_BITS_MASK))
2787                         return -EINVAL;
2788
2789                 /* VM-entry instruction length */
2790                 switch (intr_type) {
2791                 case INTR_TYPE_SOFT_EXCEPTION:
2792                 case INTR_TYPE_SOFT_INTR:
2793                 case INTR_TYPE_PRIV_SW_EXCEPTION:
2794                         if (CC(vmcs12->vm_entry_instruction_len > 15) ||
2795                             CC(vmcs12->vm_entry_instruction_len == 0 &&
2796                             CC(!nested_cpu_has_zero_length_injection(vcpu))))
2797                                 return -EINVAL;
2798                 }
2799         }
2800
2801         if (nested_vmx_check_entry_msr_switch_controls(vcpu, vmcs12))
2802                 return -EINVAL;
2803
2804         return 0;
2805 }
2806
2807 static int nested_vmx_check_controls(struct kvm_vcpu *vcpu,
2808                                      struct vmcs12 *vmcs12)
2809 {
2810         if (nested_check_vm_execution_controls(vcpu, vmcs12) ||
2811             nested_check_vm_exit_controls(vcpu, vmcs12) ||
2812             nested_check_vm_entry_controls(vcpu, vmcs12))
2813                 return -EINVAL;
2814
2815         if (to_vmx(vcpu)->nested.enlightened_vmcs_enabled)
2816                 return nested_evmcs_check_controls(vmcs12);
2817
2818         return 0;
2819 }
2820
2821 static int nested_vmx_check_host_state(struct kvm_vcpu *vcpu,
2822                                        struct vmcs12 *vmcs12)
2823 {
2824         bool ia32e;
2825
2826         if (CC(!nested_host_cr0_valid(vcpu, vmcs12->host_cr0)) ||
2827             CC(!nested_host_cr4_valid(vcpu, vmcs12->host_cr4)) ||
2828             CC(!nested_cr3_valid(vcpu, vmcs12->host_cr3)))
2829                 return -EINVAL;
2830
2831         if (CC(is_noncanonical_address(vmcs12->host_ia32_sysenter_esp, vcpu)) ||
2832             CC(is_noncanonical_address(vmcs12->host_ia32_sysenter_eip, vcpu)))
2833                 return -EINVAL;
2834
2835         if ((vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) &&
2836             CC(!kvm_pat_valid(vmcs12->host_ia32_pat)))
2837                 return -EINVAL;
2838
2839         if ((vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL) &&
2840             CC(!kvm_valid_perf_global_ctrl(vcpu_to_pmu(vcpu),
2841                                            vmcs12->host_ia32_perf_global_ctrl)))
2842                 return -EINVAL;
2843
2844 #ifdef CONFIG_X86_64
2845         ia32e = !!(vcpu->arch.efer & EFER_LMA);
2846 #else
2847         ia32e = false;
2848 #endif
2849
2850         if (ia32e) {
2851                 if (CC(!(vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)) ||
2852                     CC(!(vmcs12->host_cr4 & X86_CR4_PAE)))
2853                         return -EINVAL;
2854         } else {
2855                 if (CC(vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE) ||
2856                     CC(vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) ||
2857                     CC(vmcs12->host_cr4 & X86_CR4_PCIDE) ||
2858                     CC((vmcs12->host_rip) >> 32))
2859                         return -EINVAL;
2860         }
2861
2862         if (CC(vmcs12->host_cs_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2863             CC(vmcs12->host_ss_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2864             CC(vmcs12->host_ds_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2865             CC(vmcs12->host_es_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2866             CC(vmcs12->host_fs_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2867             CC(vmcs12->host_gs_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2868             CC(vmcs12->host_tr_selector & (SEGMENT_RPL_MASK | SEGMENT_TI_MASK)) ||
2869             CC(vmcs12->host_cs_selector == 0) ||
2870             CC(vmcs12->host_tr_selector == 0) ||
2871             CC(vmcs12->host_ss_selector == 0 && !ia32e))
2872                 return -EINVAL;
2873
2874         if (CC(is_noncanonical_address(vmcs12->host_fs_base, vcpu)) ||
2875             CC(is_noncanonical_address(vmcs12->host_gs_base, vcpu)) ||
2876             CC(is_noncanonical_address(vmcs12->host_gdtr_base, vcpu)) ||
2877             CC(is_noncanonical_address(vmcs12->host_idtr_base, vcpu)) ||
2878             CC(is_noncanonical_address(vmcs12->host_tr_base, vcpu)) ||
2879             CC(is_noncanonical_address(vmcs12->host_rip, vcpu)))
2880                 return -EINVAL;
2881
2882         /*
2883          * If the load IA32_EFER VM-exit control is 1, bits reserved in the
2884          * IA32_EFER MSR must be 0 in the field for that register. In addition,
2885          * the values of the LMA and LME bits in the field must each be that of
2886          * the host address-space size VM-exit control.
2887          */
2888         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
2889                 if (CC(!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer)) ||
2890                     CC(ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA)) ||
2891                     CC(ia32e != !!(vmcs12->host_ia32_efer & EFER_LME)))
2892                         return -EINVAL;
2893         }
2894
2895         return 0;
2896 }
2897
2898 static int nested_vmx_check_vmcs_link_ptr(struct kvm_vcpu *vcpu,
2899                                           struct vmcs12 *vmcs12)
2900 {
2901         int r = 0;
2902         struct vmcs12 *shadow;
2903         struct kvm_host_map map;
2904
2905         if (vmcs12->vmcs_link_pointer == -1ull)
2906                 return 0;
2907
2908         if (CC(!page_address_valid(vcpu, vmcs12->vmcs_link_pointer)))
2909                 return -EINVAL;
2910
2911         if (CC(kvm_vcpu_map(vcpu, gpa_to_gfn(vmcs12->vmcs_link_pointer), &map)))
2912                 return -EINVAL;
2913
2914         shadow = map.hva;
2915
2916         if (CC(shadow->hdr.revision_id != VMCS12_REVISION) ||
2917             CC(shadow->hdr.shadow_vmcs != nested_cpu_has_shadow_vmcs(vmcs12)))
2918                 r = -EINVAL;
2919
2920         kvm_vcpu_unmap(vcpu, &map, false);
2921         return r;
2922 }
2923
2924 /*
2925  * Checks related to Guest Non-register State
2926  */
2927 static int nested_check_guest_non_reg_state(struct vmcs12 *vmcs12)
2928 {
2929         if (CC(vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
2930                vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT))
2931                 return -EINVAL;
2932
2933         return 0;
2934 }
2935
2936 static int nested_vmx_check_guest_state(struct kvm_vcpu *vcpu,
2937                                         struct vmcs12 *vmcs12,
2938                                         u32 *exit_qual)
2939 {
2940         bool ia32e;
2941
2942         *exit_qual = ENTRY_FAIL_DEFAULT;
2943
2944         if (CC(!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0)) ||
2945             CC(!nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4)))
2946                 return -EINVAL;
2947
2948         if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) &&
2949             CC(!kvm_dr7_valid(vmcs12->guest_dr7)))
2950                 return -EINVAL;
2951
2952         if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT) &&
2953             CC(!kvm_pat_valid(vmcs12->guest_ia32_pat)))
2954                 return -EINVAL;
2955
2956         if (nested_vmx_check_vmcs_link_ptr(vcpu, vmcs12)) {
2957                 *exit_qual = ENTRY_FAIL_VMCS_LINK_PTR;
2958                 return -EINVAL;
2959         }
2960
2961         if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL) &&
2962             CC(!kvm_valid_perf_global_ctrl(vcpu_to_pmu(vcpu),
2963                                            vmcs12->guest_ia32_perf_global_ctrl)))
2964                 return -EINVAL;
2965
2966         /*
2967          * If the load IA32_EFER VM-entry control is 1, the following checks
2968          * are performed on the field for the IA32_EFER MSR:
2969          * - Bits reserved in the IA32_EFER MSR must be 0.
2970          * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
2971          *   the IA-32e mode guest VM-exit control. It must also be identical
2972          *   to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
2973          *   CR0.PG) is 1.
2974          */
2975         if (to_vmx(vcpu)->nested.nested_run_pending &&
2976             (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {
2977                 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
2978                 if (CC(!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer)) ||
2979                     CC(ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA)) ||
2980                     CC(((vmcs12->guest_cr0 & X86_CR0_PG) &&
2981                      ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME))))
2982                         return -EINVAL;
2983         }
2984
2985         if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS) &&
2986             (CC(is_noncanonical_address(vmcs12->guest_bndcfgs & PAGE_MASK, vcpu)) ||
2987              CC((vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD))))
2988                 return -EINVAL;
2989
2990         if (nested_check_guest_non_reg_state(vmcs12))
2991                 return -EINVAL;
2992
2993         return 0;
2994 }
2995
2996 static int nested_vmx_check_vmentry_hw(struct kvm_vcpu *vcpu)
2997 {
2998         struct vcpu_vmx *vmx = to_vmx(vcpu);
2999         unsigned long cr3, cr4;
3000         bool vm_fail;
3001
3002         if (!nested_early_check)
3003                 return 0;
3004
3005         if (vmx->msr_autoload.host.nr)
3006                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
3007         if (vmx->msr_autoload.guest.nr)
3008                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
3009
3010         preempt_disable();
3011
3012         vmx_prepare_switch_to_guest(vcpu);
3013
3014         /*
3015          * Induce a consistency check VMExit by clearing bit 1 in GUEST_RFLAGS,
3016          * which is reserved to '1' by hardware.  GUEST_RFLAGS is guaranteed to
3017          * be written (by prepare_vmcs02()) before the "real" VMEnter, i.e.
3018          * there is no need to preserve other bits or save/restore the field.
3019          */
3020         vmcs_writel(GUEST_RFLAGS, 0);
3021
3022         cr3 = __get_current_cr3_fast();
3023         if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
3024                 vmcs_writel(HOST_CR3, cr3);
3025                 vmx->loaded_vmcs->host_state.cr3 = cr3;
3026         }
3027
3028         cr4 = cr4_read_shadow();
3029         if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
3030                 vmcs_writel(HOST_CR4, cr4);
3031                 vmx->loaded_vmcs->host_state.cr4 = cr4;
3032         }
3033
3034         asm(
3035                 "sub $%c[wordsize], %%" _ASM_SP "\n\t" /* temporarily adjust RSP for CALL */
3036                 "cmp %%" _ASM_SP ", %c[host_state_rsp](%[loaded_vmcs]) \n\t"
3037                 "je 1f \n\t"
3038                 __ex("vmwrite %%" _ASM_SP ", %[HOST_RSP]") "\n\t"
3039                 "mov %%" _ASM_SP ", %c[host_state_rsp](%[loaded_vmcs]) \n\t"
3040                 "1: \n\t"
3041                 "add $%c[wordsize], %%" _ASM_SP "\n\t" /* un-adjust RSP */
3042
3043                 /* Check if vmlaunch or vmresume is needed */
3044                 "cmpb $0, %c[launched](%[loaded_vmcs])\n\t"
3045
3046                 /*
3047                  * VMLAUNCH and VMRESUME clear RFLAGS.{CF,ZF} on VM-Exit, set
3048                  * RFLAGS.CF on VM-Fail Invalid and set RFLAGS.ZF on VM-Fail
3049                  * Valid.  vmx_vmenter() directly "returns" RFLAGS, and so the
3050                  * results of VM-Enter is captured via CC_{SET,OUT} to vm_fail.
3051                  */
3052                 "call vmx_vmenter\n\t"
3053
3054                 CC_SET(be)
3055               : ASM_CALL_CONSTRAINT, CC_OUT(be) (vm_fail)
3056               : [HOST_RSP]"r"((unsigned long)HOST_RSP),
3057                 [loaded_vmcs]"r"(vmx->loaded_vmcs),
3058                 [launched]"i"(offsetof(struct loaded_vmcs, launched)),
3059                 [host_state_rsp]"i"(offsetof(struct loaded_vmcs, host_state.rsp)),
3060                 [wordsize]"i"(sizeof(ulong))
3061               : "memory"
3062         );
3063
3064         if (vmx->msr_autoload.host.nr)
3065                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
3066         if (vmx->msr_autoload.guest.nr)
3067                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
3068
3069         if (vm_fail) {
3070                 u32 error = vmcs_read32(VM_INSTRUCTION_ERROR);
3071
3072                 preempt_enable();
3073
3074                 trace_kvm_nested_vmenter_failed(
3075                         "early hardware check VM-instruction error: ", error);
3076                 WARN_ON_ONCE(error != VMXERR_ENTRY_INVALID_CONTROL_FIELD);
3077                 return 1;
3078         }
3079
3080         /*
3081          * VMExit clears RFLAGS.IF and DR7, even on a consistency check.
3082          */
3083         local_irq_enable();
3084         if (hw_breakpoint_active())
3085                 set_debugreg(__this_cpu_read(cpu_dr7), 7);
3086         preempt_enable();
3087
3088         /*
3089          * A non-failing VMEntry means we somehow entered guest mode with
3090          * an illegal RIP, and that's just the tip of the iceberg.  There
3091          * is no telling what memory has been modified or what state has
3092          * been exposed to unknown code.  Hitting this all but guarantees
3093          * a (very critical) hardware issue.
3094          */
3095         WARN_ON(!(vmcs_read32(VM_EXIT_REASON) &
3096                 VMX_EXIT_REASONS_FAILED_VMENTRY));
3097
3098         return 0;
3099 }
3100
3101 static bool nested_get_vmcs12_pages(struct kvm_vcpu *vcpu)
3102 {
3103         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3104         struct vcpu_vmx *vmx = to_vmx(vcpu);
3105         struct kvm_host_map *map;
3106         struct page *page;
3107         u64 hpa;
3108
3109         /*
3110          * hv_evmcs may end up being not mapped after migration (when
3111          * L2 was running), map it here to make sure vmcs12 changes are
3112          * properly reflected.
3113          */
3114         if (vmx->nested.enlightened_vmcs_enabled && !vmx->nested.hv_evmcs) {
3115                 enum nested_evmptrld_status evmptrld_status =
3116                         nested_vmx_handle_enlightened_vmptrld(vcpu, false);
3117
3118                 if (evmptrld_status == EVMPTRLD_VMFAIL ||
3119                     evmptrld_status == EVMPTRLD_ERROR) {
3120                         pr_debug_ratelimited("%s: enlightened vmptrld failed\n",
3121                                              __func__);
3122                         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3123                         vcpu->run->internal.suberror =
3124                                 KVM_INTERNAL_ERROR_EMULATION;
3125                         vcpu->run->internal.ndata = 0;
3126                         return false;
3127                 }
3128         }
3129
3130         if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
3131                 /*
3132                  * Translate L1 physical address to host physical
3133                  * address for vmcs02. Keep the page pinned, so this
3134                  * physical address remains valid. We keep a reference
3135                  * to it so we can release it later.
3136                  */
3137                 if (vmx->nested.apic_access_page) { /* shouldn't happen */
3138                         kvm_release_page_clean(vmx->nested.apic_access_page);
3139                         vmx->nested.apic_access_page = NULL;
3140                 }
3141                 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->apic_access_addr);
3142                 if (!is_error_page(page)) {
3143                         vmx->nested.apic_access_page = page;
3144                         hpa = page_to_phys(vmx->nested.apic_access_page);
3145                         vmcs_write64(APIC_ACCESS_ADDR, hpa);
3146                 } else {
3147                         pr_debug_ratelimited("%s: no backing 'struct page' for APIC-access address in vmcs12\n",
3148                                              __func__);
3149                         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3150                         vcpu->run->internal.suberror =
3151                                 KVM_INTERNAL_ERROR_EMULATION;
3152                         vcpu->run->internal.ndata = 0;
3153                         return false;
3154                 }
3155         }
3156
3157         if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
3158                 map = &vmx->nested.virtual_apic_map;
3159
3160                 if (!kvm_vcpu_map(vcpu, gpa_to_gfn(vmcs12->virtual_apic_page_addr), map)) {
3161                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, pfn_to_hpa(map->pfn));
3162                 } else if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING) &&
3163                            nested_cpu_has(vmcs12, CPU_BASED_CR8_STORE_EXITING) &&
3164                            !nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
3165                         /*
3166                          * The processor will never use the TPR shadow, simply
3167                          * clear the bit from the execution control.  Such a
3168                          * configuration is useless, but it happens in tests.
3169                          * For any other configuration, failing the vm entry is
3170                          * _not_ what the processor does but it's basically the
3171                          * only possibility we have.
3172                          */
3173                         exec_controls_clearbit(vmx, CPU_BASED_TPR_SHADOW);
3174                 } else {
3175                         /*
3176                          * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR to
3177                          * force VM-Entry to fail.
3178                          */
3179                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
3180                 }
3181         }
3182
3183         if (nested_cpu_has_posted_intr(vmcs12)) {
3184                 map = &vmx->nested.pi_desc_map;
3185
3186                 if (!kvm_vcpu_map(vcpu, gpa_to_gfn(vmcs12->posted_intr_desc_addr), map)) {
3187                         vmx->nested.pi_desc =
3188                                 (struct pi_desc *)(((void *)map->hva) +
3189                                 offset_in_page(vmcs12->posted_intr_desc_addr));
3190                         vmcs_write64(POSTED_INTR_DESC_ADDR,
3191                                      pfn_to_hpa(map->pfn) + offset_in_page(vmcs12->posted_intr_desc_addr));
3192                 }
3193         }
3194         if (nested_vmx_prepare_msr_bitmap(vcpu, vmcs12))
3195                 exec_controls_setbit(vmx, CPU_BASED_USE_MSR_BITMAPS);
3196         else
3197                 exec_controls_clearbit(vmx, CPU_BASED_USE_MSR_BITMAPS);
3198         return true;
3199 }
3200
3201 /*
3202  * Intel's VMX Instruction Reference specifies a common set of prerequisites
3203  * for running VMX instructions (except VMXON, whose prerequisites are
3204  * slightly different). It also specifies what exception to inject otherwise.
3205  * Note that many of these exceptions have priority over VM exits, so they
3206  * don't have to be checked again here.
3207  */
3208 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
3209 {
3210         if (!to_vmx(vcpu)->nested.vmxon) {
3211                 kvm_queue_exception(vcpu, UD_VECTOR);
3212                 return 0;
3213         }
3214
3215         if (vmx_get_cpl(vcpu)) {
3216                 kvm_inject_gp(vcpu, 0);
3217                 return 0;
3218         }
3219
3220         return 1;
3221 }
3222
3223 static u8 vmx_has_apicv_interrupt(struct kvm_vcpu *vcpu)
3224 {
3225         u8 rvi = vmx_get_rvi();
3226         u8 vppr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_PROCPRI);
3227
3228         return ((rvi & 0xf0) > (vppr & 0xf0));
3229 }
3230
3231 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
3232                                    struct vmcs12 *vmcs12);
3233
3234 /*
3235  * If from_vmentry is false, this is being called from state restore (either RSM
3236  * or KVM_SET_NESTED_STATE).  Otherwise it's called from vmlaunch/vmresume.
3237  *
3238  * Returns:
3239  *      NVMX_VMENTRY_SUCCESS: Entered VMX non-root mode
3240  *      NVMX_VMENTRY_VMFAIL:  Consistency check VMFail
3241  *      NVMX_VMENTRY_VMEXIT:  Consistency check VMExit
3242  *      NVMX_VMENTRY_KVM_INTERNAL_ERROR: KVM internal error
3243  */
3244 enum nvmx_vmentry_status nested_vmx_enter_non_root_mode(struct kvm_vcpu *vcpu,
3245                                                         bool from_vmentry)
3246 {
3247         struct vcpu_vmx *vmx = to_vmx(vcpu);
3248         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3249         bool evaluate_pending_interrupts;
3250         u32 exit_reason = EXIT_REASON_INVALID_STATE;
3251         u32 exit_qual;
3252
3253         if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
3254                 kvm_vcpu_flush_tlb_current(vcpu);
3255
3256         evaluate_pending_interrupts = exec_controls_get(vmx) &
3257                 (CPU_BASED_INTR_WINDOW_EXITING | CPU_BASED_NMI_WINDOW_EXITING);
3258         if (likely(!evaluate_pending_interrupts) && kvm_vcpu_apicv_active(vcpu))
3259                 evaluate_pending_interrupts |= vmx_has_apicv_interrupt(vcpu);
3260
3261         if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
3262                 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
3263         if (kvm_mpx_supported() &&
3264                 !(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
3265                 vmx->nested.vmcs01_guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
3266
3267         /*
3268          * Overwrite vmcs01.GUEST_CR3 with L1's CR3 if EPT is disabled *and*
3269          * nested early checks are disabled.  In the event of a "late" VM-Fail,
3270          * i.e. a VM-Fail detected by hardware but not KVM, KVM must unwind its
3271          * software model to the pre-VMEntry host state.  When EPT is disabled,
3272          * GUEST_CR3 holds KVM's shadow CR3, not L1's "real" CR3, which causes
3273          * nested_vmx_restore_host_state() to corrupt vcpu->arch.cr3.  Stuffing
3274          * vmcs01.GUEST_CR3 results in the unwind naturally setting arch.cr3 to
3275          * the correct value.  Smashing vmcs01.GUEST_CR3 is safe because nested
3276          * VM-Exits, and the unwind, reset KVM's MMU, i.e. vmcs01.GUEST_CR3 is
3277          * guaranteed to be overwritten with a shadow CR3 prior to re-entering
3278          * L1.  Don't stuff vmcs01.GUEST_CR3 when using nested early checks as
3279          * KVM modifies vcpu->arch.cr3 if and only if the early hardware checks
3280          * pass, and early VM-Fails do not reset KVM's MMU, i.e. the VM-Fail
3281          * path would need to manually save/restore vmcs01.GUEST_CR3.
3282          */
3283         if (!enable_ept && !nested_early_check)
3284                 vmcs_writel(GUEST_CR3, vcpu->arch.cr3);
3285
3286         vmx_switch_vmcs(vcpu, &vmx->nested.vmcs02);
3287
3288         prepare_vmcs02_early(vmx, vmcs12);
3289
3290         if (from_vmentry) {
3291                 if (unlikely(!nested_get_vmcs12_pages(vcpu)))
3292                         return NVMX_VMENTRY_KVM_INTERNAL_ERROR;
3293
3294                 if (nested_vmx_check_vmentry_hw(vcpu)) {
3295                         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
3296                         return NVMX_VMENTRY_VMFAIL;
3297                 }
3298
3299                 if (nested_vmx_check_guest_state(vcpu, vmcs12, &exit_qual))
3300                         goto vmentry_fail_vmexit;
3301         }
3302
3303         enter_guest_mode(vcpu);
3304         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING)
3305                 vcpu->arch.tsc_offset += vmcs12->tsc_offset;
3306
3307         if (prepare_vmcs02(vcpu, vmcs12, &exit_qual))
3308                 goto vmentry_fail_vmexit_guest_mode;
3309
3310         if (from_vmentry) {
3311                 exit_reason = EXIT_REASON_MSR_LOAD_FAIL;
3312                 exit_qual = nested_vmx_load_msr(vcpu,
3313                                                 vmcs12->vm_entry_msr_load_addr,
3314                                                 vmcs12->vm_entry_msr_load_count);
3315                 if (exit_qual)
3316                         goto vmentry_fail_vmexit_guest_mode;
3317         } else {
3318                 /*
3319                  * The MMU is not initialized to point at the right entities yet and
3320                  * "get pages" would need to read data from the guest (i.e. we will
3321                  * need to perform gpa to hpa translation). Request a call
3322                  * to nested_get_vmcs12_pages before the next VM-entry.  The MSRs
3323                  * have already been set at vmentry time and should not be reset.
3324                  */
3325                 kvm_make_request(KVM_REQ_GET_VMCS12_PAGES, vcpu);
3326         }
3327
3328         /*
3329          * If L1 had a pending IRQ/NMI until it executed
3330          * VMLAUNCH/VMRESUME which wasn't delivered because it was
3331          * disallowed (e.g. interrupts disabled), L0 needs to
3332          * evaluate if this pending event should cause an exit from L2
3333          * to L1 or delivered directly to L2 (e.g. In case L1 don't
3334          * intercept EXTERNAL_INTERRUPT).
3335          *
3336          * Usually this would be handled by the processor noticing an
3337          * IRQ/NMI window request, or checking RVI during evaluation of
3338          * pending virtual interrupts.  However, this setting was done
3339          * on VMCS01 and now VMCS02 is active instead. Thus, we force L0
3340          * to perform pending event evaluation by requesting a KVM_REQ_EVENT.
3341          */
3342         if (unlikely(evaluate_pending_interrupts))
3343                 kvm_make_request(KVM_REQ_EVENT, vcpu);
3344
3345         /*
3346          * Do not start the preemption timer hrtimer until after we know
3347          * we are successful, so that only nested_vmx_vmexit needs to cancel
3348          * the timer.
3349          */
3350         vmx->nested.preemption_timer_expired = false;
3351         if (nested_cpu_has_preemption_timer(vmcs12))
3352                 vmx_start_preemption_timer(vcpu);
3353
3354         /*
3355          * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
3356          * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
3357          * returned as far as L1 is concerned. It will only return (and set
3358          * the success flag) when L2 exits (see nested_vmx_vmexit()).
3359          */
3360         return NVMX_VMENTRY_SUCCESS;
3361
3362         /*
3363          * A failed consistency check that leads to a VMExit during L1's
3364          * VMEnter to L2 is a variation of a normal VMexit, as explained in
3365          * 26.7 "VM-entry failures during or after loading guest state".
3366          */
3367 vmentry_fail_vmexit_guest_mode:
3368         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING)
3369                 vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
3370         leave_guest_mode(vcpu);
3371
3372 vmentry_fail_vmexit:
3373         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
3374
3375         if (!from_vmentry)
3376                 return NVMX_VMENTRY_VMEXIT;
3377
3378         load_vmcs12_host_state(vcpu, vmcs12);
3379         vmcs12->vm_exit_reason = exit_reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
3380         vmcs12->exit_qualification = exit_qual;
3381         if (enable_shadow_vmcs || vmx->nested.hv_evmcs)
3382                 vmx->nested.need_vmcs12_to_shadow_sync = true;
3383         return NVMX_VMENTRY_VMEXIT;
3384 }
3385
3386 /*
3387  * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
3388  * for running an L2 nested guest.
3389  */
3390 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
3391 {
3392         struct vmcs12 *vmcs12;
3393         enum nvmx_vmentry_status status;
3394         struct vcpu_vmx *vmx = to_vmx(vcpu);
3395         u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
3396         enum nested_evmptrld_status evmptrld_status;
3397
3398         if (!nested_vmx_check_permission(vcpu))
3399                 return 1;
3400
3401         evmptrld_status = nested_vmx_handle_enlightened_vmptrld(vcpu, launch);
3402         if (evmptrld_status == EVMPTRLD_ERROR) {
3403                 kvm_queue_exception(vcpu, UD_VECTOR);
3404                 return 1;
3405         } else if (evmptrld_status == EVMPTRLD_VMFAIL) {
3406                 return nested_vmx_failInvalid(vcpu);
3407         }
3408
3409         if (!vmx->nested.hv_evmcs && vmx->nested.current_vmptr == -1ull)
3410                 return nested_vmx_failInvalid(vcpu);
3411
3412         vmcs12 = get_vmcs12(vcpu);
3413
3414         /*
3415          * Can't VMLAUNCH or VMRESUME a shadow VMCS. Despite the fact
3416          * that there *is* a valid VMCS pointer, RFLAGS.CF is set
3417          * rather than RFLAGS.ZF, and no error number is stored to the
3418          * VM-instruction error field.
3419          */
3420         if (vmcs12->hdr.shadow_vmcs)
3421                 return nested_vmx_failInvalid(vcpu);
3422
3423         if (vmx->nested.hv_evmcs) {
3424                 copy_enlightened_to_vmcs12(vmx);
3425                 /* Enlightened VMCS doesn't have launch state */
3426                 vmcs12->launch_state = !launch;
3427         } else if (enable_shadow_vmcs) {
3428                 copy_shadow_to_vmcs12(vmx);
3429         }
3430
3431         /*
3432          * The nested entry process starts with enforcing various prerequisites
3433          * on vmcs12 as required by the Intel SDM, and act appropriately when
3434          * they fail: As the SDM explains, some conditions should cause the
3435          * instruction to fail, while others will cause the instruction to seem
3436          * to succeed, but return an EXIT_REASON_INVALID_STATE.
3437          * To speed up the normal (success) code path, we should avoid checking
3438          * for misconfigurations which will anyway be caught by the processor
3439          * when using the merged vmcs02.
3440          */
3441         if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS)
3442                 return nested_vmx_failValid(vcpu,
3443                         VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
3444
3445         if (vmcs12->launch_state == launch)
3446                 return nested_vmx_failValid(vcpu,
3447                         launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
3448                                : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
3449
3450         if (nested_vmx_check_controls(vcpu, vmcs12))
3451                 return nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
3452
3453         if (nested_vmx_check_host_state(vcpu, vmcs12))
3454                 return nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
3455
3456         /*
3457          * We're finally done with prerequisite checking, and can start with
3458          * the nested entry.
3459          */
3460         vmx->nested.nested_run_pending = 1;
3461         status = nested_vmx_enter_non_root_mode(vcpu, true);
3462         if (unlikely(status != NVMX_VMENTRY_SUCCESS))
3463                 goto vmentry_failed;
3464
3465         /* Hide L1D cache contents from the nested guest.  */
3466         vmx->vcpu.arch.l1tf_flush_l1d = true;
3467
3468         /*
3469          * Must happen outside of nested_vmx_enter_non_root_mode() as it will
3470          * also be used as part of restoring nVMX state for
3471          * snapshot restore (migration).
3472          *
3473          * In this flow, it is assumed that vmcs12 cache was
3474          * trasferred as part of captured nVMX state and should
3475          * therefore not be read from guest memory (which may not
3476          * exist on destination host yet).
3477          */
3478         nested_cache_shadow_vmcs12(vcpu, vmcs12);
3479
3480         /*
3481          * If we're entering a halted L2 vcpu and the L2 vcpu won't be
3482          * awakened by event injection or by an NMI-window VM-exit or
3483          * by an interrupt-window VM-exit, halt the vcpu.
3484          */
3485         if ((vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT) &&
3486             !(vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) &&
3487             !(vmcs12->cpu_based_vm_exec_control & CPU_BASED_NMI_WINDOW_EXITING) &&
3488             !((vmcs12->cpu_based_vm_exec_control & CPU_BASED_INTR_WINDOW_EXITING) &&
3489               (vmcs12->guest_rflags & X86_EFLAGS_IF))) {
3490                 vmx->nested.nested_run_pending = 0;
3491                 return kvm_vcpu_halt(vcpu);
3492         }
3493         return 1;
3494
3495 vmentry_failed:
3496         vmx->nested.nested_run_pending = 0;
3497         if (status == NVMX_VMENTRY_KVM_INTERNAL_ERROR)
3498                 return 0;
3499         if (status == NVMX_VMENTRY_VMEXIT)
3500                 return 1;
3501         WARN_ON_ONCE(status != NVMX_VMENTRY_VMFAIL);
3502         return nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
3503 }
3504
3505 /*
3506  * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
3507  * because L2 may have changed some cr0 bits directly (CR0_GUEST_HOST_MASK).
3508  * This function returns the new value we should put in vmcs12.guest_cr0.
3509  * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
3510  *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
3511  *     available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
3512  *     didn't trap the bit, because if L1 did, so would L0).
3513  *  2. Bits that L1 asked to trap (and therefore L0 also did) could not have
3514  *     been modified by L2, and L1 knows it. So just leave the old value of
3515  *     the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
3516  *     isn't relevant, because if L0 traps this bit it can set it to anything.
3517  *  3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
3518  *     changed these bits, and therefore they need to be updated, but L0
3519  *     didn't necessarily allow them to be changed in GUEST_CR0 - and rather
3520  *     put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
3521  */
3522 static inline unsigned long
3523 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
3524 {
3525         return
3526         /*1*/   (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
3527         /*2*/   (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
3528         /*3*/   (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
3529                         vcpu->arch.cr0_guest_owned_bits));
3530 }
3531
3532 static inline unsigned long
3533 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
3534 {
3535         return
3536         /*1*/   (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
3537         /*2*/   (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
3538         /*3*/   (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
3539                         vcpu->arch.cr4_guest_owned_bits));
3540 }
3541
3542 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
3543                                       struct vmcs12 *vmcs12)
3544 {
3545         u32 idt_vectoring;
3546         unsigned int nr;
3547
3548         if (vcpu->arch.exception.injected) {
3549                 nr = vcpu->arch.exception.nr;
3550                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
3551
3552                 if (kvm_exception_is_soft(nr)) {
3553                         vmcs12->vm_exit_instruction_len =
3554                                 vcpu->arch.event_exit_inst_len;
3555                         idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
3556                 } else
3557                         idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
3558
3559                 if (vcpu->arch.exception.has_error_code) {
3560                         idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
3561                         vmcs12->idt_vectoring_error_code =
3562                                 vcpu->arch.exception.error_code;
3563                 }
3564
3565                 vmcs12->idt_vectoring_info_field = idt_vectoring;
3566         } else if (vcpu->arch.nmi_injected) {
3567                 vmcs12->idt_vectoring_info_field =
3568                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
3569         } else if (vcpu->arch.interrupt.injected) {
3570                 nr = vcpu->arch.interrupt.nr;
3571                 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
3572
3573                 if (vcpu->arch.interrupt.soft) {
3574                         idt_vectoring |= INTR_TYPE_SOFT_INTR;
3575                         vmcs12->vm_entry_instruction_len =
3576                                 vcpu->arch.event_exit_inst_len;
3577                 } else
3578                         idt_vectoring |= INTR_TYPE_EXT_INTR;
3579
3580                 vmcs12->idt_vectoring_info_field = idt_vectoring;
3581         }
3582 }
3583
3584
3585 void nested_mark_vmcs12_pages_dirty(struct kvm_vcpu *vcpu)
3586 {
3587         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3588         gfn_t gfn;
3589
3590         /*
3591          * Don't need to mark the APIC access page dirty; it is never
3592          * written to by the CPU during APIC virtualization.
3593          */
3594
3595         if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
3596                 gfn = vmcs12->virtual_apic_page_addr >> PAGE_SHIFT;
3597                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3598         }
3599
3600         if (nested_cpu_has_posted_intr(vmcs12)) {
3601                 gfn = vmcs12->posted_intr_desc_addr >> PAGE_SHIFT;
3602                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3603         }
3604 }
3605
3606 static void vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
3607 {
3608         struct vcpu_vmx *vmx = to_vmx(vcpu);
3609         int max_irr;
3610         void *vapic_page;
3611         u16 status;
3612
3613         if (!vmx->nested.pi_desc || !vmx->nested.pi_pending)
3614                 return;
3615
3616         vmx->nested.pi_pending = false;
3617         if (!pi_test_and_clear_on(vmx->nested.pi_desc))
3618                 return;
3619
3620         max_irr = find_last_bit((unsigned long *)vmx->nested.pi_desc->pir, 256);
3621         if (max_irr != 256) {
3622                 vapic_page = vmx->nested.virtual_apic_map.hva;
3623                 if (!vapic_page)
3624                         return;
3625
3626                 __kvm_apic_update_irr(vmx->nested.pi_desc->pir,
3627                         vapic_page, &max_irr);
3628                 status = vmcs_read16(GUEST_INTR_STATUS);
3629                 if ((u8)max_irr > ((u8)status & 0xff)) {
3630                         status &= ~0xff;
3631                         status |= (u8)max_irr;
3632                         vmcs_write16(GUEST_INTR_STATUS, status);
3633                 }
3634         }
3635
3636         nested_mark_vmcs12_pages_dirty(vcpu);
3637 }
3638
3639 static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
3640                                                unsigned long exit_qual)
3641 {
3642         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3643         unsigned int nr = vcpu->arch.exception.nr;
3644         u32 intr_info = nr | INTR_INFO_VALID_MASK;
3645
3646         if (vcpu->arch.exception.has_error_code) {
3647                 vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code;
3648                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
3649         }
3650
3651         if (kvm_exception_is_soft(nr))
3652                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
3653         else
3654                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
3655
3656         if (!(vmcs12->idt_vectoring_info_field & VECTORING_INFO_VALID_MASK) &&
3657             vmx_get_nmi_mask(vcpu))
3658                 intr_info |= INTR_INFO_UNBLOCK_NMI;
3659
3660         nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI, intr_info, exit_qual);
3661 }
3662
3663 /*
3664  * Returns true if a debug trap is pending delivery.
3665  *
3666  * In KVM, debug traps bear an exception payload. As such, the class of a #DB
3667  * exception may be inferred from the presence of an exception payload.
3668  */
3669 static inline bool vmx_pending_dbg_trap(struct kvm_vcpu *vcpu)
3670 {
3671         return vcpu->arch.exception.pending &&
3672                         vcpu->arch.exception.nr == DB_VECTOR &&
3673                         vcpu->arch.exception.payload;
3674 }
3675
3676 /*
3677  * Certain VM-exits set the 'pending debug exceptions' field to indicate a
3678  * recognized #DB (data or single-step) that has yet to be delivered. Since KVM
3679  * represents these debug traps with a payload that is said to be compatible
3680  * with the 'pending debug exceptions' field, write the payload to the VMCS
3681  * field if a VM-exit is delivered before the debug trap.
3682  */
3683 static void nested_vmx_update_pending_dbg(struct kvm_vcpu *vcpu)
3684 {
3685         if (vmx_pending_dbg_trap(vcpu))
3686                 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
3687                             vcpu->arch.exception.payload);
3688 }
3689
3690 static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
3691 {
3692         struct vcpu_vmx *vmx = to_vmx(vcpu);
3693         unsigned long exit_qual;
3694         bool block_nested_events =
3695             vmx->nested.nested_run_pending || kvm_event_needs_reinjection(vcpu);
3696         bool mtf_pending = vmx->nested.mtf_pending;
3697         struct kvm_lapic *apic = vcpu->arch.apic;
3698
3699         /*
3700          * Clear the MTF state. If a higher priority VM-exit is delivered first,
3701          * this state is discarded.
3702          */
3703         if (!block_nested_events)
3704                 vmx->nested.mtf_pending = false;
3705
3706         if (lapic_in_kernel(vcpu) &&
3707                 test_bit(KVM_APIC_INIT, &apic->pending_events)) {
3708                 if (block_nested_events)
3709                         return -EBUSY;
3710                 nested_vmx_update_pending_dbg(vcpu);
3711                 clear_bit(KVM_APIC_INIT, &apic->pending_events);
3712                 nested_vmx_vmexit(vcpu, EXIT_REASON_INIT_SIGNAL, 0, 0);
3713                 return 0;
3714         }
3715
3716         /*
3717          * Process any exceptions that are not debug traps before MTF.
3718          */
3719         if (vcpu->arch.exception.pending &&
3720             !vmx_pending_dbg_trap(vcpu) &&
3721             nested_vmx_check_exception(vcpu, &exit_qual)) {
3722                 if (block_nested_events)
3723                         return -EBUSY;
3724                 nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
3725                 return 0;
3726         }
3727
3728         if (mtf_pending) {
3729                 if (block_nested_events)
3730                         return -EBUSY;
3731                 nested_vmx_update_pending_dbg(vcpu);
3732                 nested_vmx_vmexit(vcpu, EXIT_REASON_MONITOR_TRAP_FLAG, 0, 0);
3733                 return 0;
3734         }
3735
3736         if (vcpu->arch.exception.pending &&
3737             nested_vmx_check_exception(vcpu, &exit_qual)) {
3738                 if (block_nested_events)
3739                         return -EBUSY;
3740                 nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
3741                 return 0;
3742         }
3743
3744         if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
3745             vmx->nested.preemption_timer_expired) {
3746                 if (block_nested_events)
3747                         return -EBUSY;
3748                 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
3749                 return 0;
3750         }
3751
3752         if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
3753                 if (block_nested_events)
3754                         return -EBUSY;
3755                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
3756                                   NMI_VECTOR | INTR_TYPE_NMI_INTR |
3757                                   INTR_INFO_VALID_MASK, 0);
3758                 /*
3759                  * The NMI-triggered VM exit counts as injection:
3760                  * clear this one and block further NMIs.
3761                  */
3762                 vcpu->arch.nmi_pending = 0;
3763                 vmx_set_nmi_mask(vcpu, true);
3764                 return 0;
3765         }
3766
3767         if (kvm_cpu_has_interrupt(vcpu) && nested_exit_on_intr(vcpu)) {
3768                 if (block_nested_events)
3769                         return -EBUSY;
3770                 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
3771                 return 0;
3772         }
3773
3774         vmx_complete_nested_posted_interrupt(vcpu);
3775         return 0;
3776 }
3777
3778 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
3779 {
3780         ktime_t remaining =
3781                 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
3782         u64 value;
3783
3784         if (ktime_to_ns(remaining) <= 0)
3785                 return 0;
3786
3787         value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
3788         do_div(value, 1000000);
3789         return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
3790 }
3791
3792 static bool is_vmcs12_ext_field(unsigned long field)
3793 {
3794         switch (field) {
3795         case GUEST_ES_SELECTOR:
3796         case GUEST_CS_SELECTOR:
3797         case GUEST_SS_SELECTOR:
3798         case GUEST_DS_SELECTOR:
3799         case GUEST_FS_SELECTOR:
3800         case GUEST_GS_SELECTOR:
3801         case GUEST_LDTR_SELECTOR:
3802         case GUEST_TR_SELECTOR:
3803         case GUEST_ES_LIMIT:
3804         case GUEST_CS_LIMIT:
3805         case GUEST_SS_LIMIT:
3806         case GUEST_DS_LIMIT:
3807         case GUEST_FS_LIMIT:
3808         case GUEST_GS_LIMIT:
3809         case GUEST_LDTR_LIMIT:
3810         case GUEST_TR_LIMIT:
3811         case GUEST_GDTR_LIMIT:
3812         case GUEST_IDTR_LIMIT:
3813         case GUEST_ES_AR_BYTES:
3814         case GUEST_DS_AR_BYTES:
3815         case GUEST_FS_AR_BYTES:
3816         case GUEST_GS_AR_BYTES:
3817         case GUEST_LDTR_AR_BYTES:
3818         case GUEST_TR_AR_BYTES:
3819         case GUEST_ES_BASE:
3820         case GUEST_CS_BASE:
3821         case GUEST_SS_BASE:
3822         case GUEST_DS_BASE:
3823         case GUEST_FS_BASE:
3824         case GUEST_GS_BASE:
3825         case GUEST_LDTR_BASE:
3826         case GUEST_TR_BASE:
3827         case GUEST_GDTR_BASE:
3828         case GUEST_IDTR_BASE:
3829         case GUEST_PENDING_DBG_EXCEPTIONS:
3830         case GUEST_BNDCFGS:
3831                 return true;
3832         default:
3833                 break;
3834         }
3835
3836         return false;
3837 }
3838
3839 static void sync_vmcs02_to_vmcs12_rare(struct kvm_vcpu *vcpu,
3840                                        struct vmcs12 *vmcs12)
3841 {
3842         struct vcpu_vmx *vmx = to_vmx(vcpu);
3843
3844         vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
3845         vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
3846         vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
3847         vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
3848         vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
3849         vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
3850         vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
3851         vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
3852         vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
3853         vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
3854         vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
3855         vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
3856         vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
3857         vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
3858         vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
3859         vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
3860         vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
3861         vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
3862         vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
3863         vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
3864         vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
3865         vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
3866         vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
3867         vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
3868         vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
3869         vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
3870         vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
3871         vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
3872         vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
3873         vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
3874         vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
3875         vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
3876         vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
3877         vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
3878         vmcs12->guest_pending_dbg_exceptions =
3879                 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
3880         if (kvm_mpx_supported())
3881                 vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
3882
3883         vmx->nested.need_sync_vmcs02_to_vmcs12_rare = false;
3884 }
3885
3886 static void copy_vmcs02_to_vmcs12_rare(struct kvm_vcpu *vcpu,
3887                                        struct vmcs12 *vmcs12)
3888 {
3889         struct vcpu_vmx *vmx = to_vmx(vcpu);
3890         int cpu;
3891
3892         if (!vmx->nested.need_sync_vmcs02_to_vmcs12_rare)
3893                 return;
3894
3895
3896         WARN_ON_ONCE(vmx->loaded_vmcs != &vmx->vmcs01);
3897
3898         cpu = get_cpu();
3899         vmx->loaded_vmcs = &vmx->nested.vmcs02;
3900         vmx_vcpu_load(&vmx->vcpu, cpu);
3901
3902         sync_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
3903
3904         vmx->loaded_vmcs = &vmx->vmcs01;
3905         vmx_vcpu_load(&vmx->vcpu, cpu);
3906         put_cpu();
3907 }
3908
3909 /*
3910  * Update the guest state fields of vmcs12 to reflect changes that
3911  * occurred while L2 was running. (The "IA-32e mode guest" bit of the
3912  * VM-entry controls is also updated, since this is really a guest
3913  * state bit.)
3914  */
3915 static void sync_vmcs02_to_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
3916 {
3917         struct vcpu_vmx *vmx = to_vmx(vcpu);
3918
3919         if (vmx->nested.hv_evmcs)
3920                 sync_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
3921
3922         vmx->nested.need_sync_vmcs02_to_vmcs12_rare = !vmx->nested.hv_evmcs;
3923
3924         vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
3925         vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
3926
3927         vmcs12->guest_rsp = kvm_rsp_read(vcpu);
3928         vmcs12->guest_rip = kvm_rip_read(vcpu);
3929         vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
3930
3931         vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
3932         vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
3933
3934         vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
3935         vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
3936         vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
3937
3938         vmcs12->guest_interruptibility_info =
3939                 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
3940
3941         if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
3942                 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
3943         else
3944                 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
3945
3946         if (nested_cpu_has_preemption_timer(vmcs12) &&
3947             vmcs12->vm_exit_controls & VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
3948                         vmcs12->vmx_preemption_timer_value =
3949                                 vmx_get_preemption_timer_value(vcpu);
3950
3951         /*
3952          * In some cases (usually, nested EPT), L2 is allowed to change its
3953          * own CR3 without exiting. If it has changed it, we must keep it.
3954          * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
3955          * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
3956          *
3957          * Additionally, restore L2's PDPTR to vmcs12.
3958          */
3959         if (enable_ept) {
3960                 vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
3961                 if (nested_cpu_has_ept(vmcs12) && is_pae_paging(vcpu)) {
3962                         vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
3963                         vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
3964                         vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
3965                         vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
3966                 }
3967         }
3968
3969         vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
3970
3971         if (nested_cpu_has_vid(vmcs12))
3972                 vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
3973
3974         vmcs12->vm_entry_controls =
3975                 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
3976                 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
3977
3978         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS)
3979                 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
3980
3981         if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
3982                 vmcs12->guest_ia32_efer = vcpu->arch.efer;
3983 }
3984
3985 /*
3986  * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
3987  * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
3988  * and this function updates it to reflect the changes to the guest state while
3989  * L2 was running (and perhaps made some exits which were handled directly by L0
3990  * without going back to L1), and to reflect the exit reason.
3991  * Note that we do not have to copy here all VMCS fields, just those that
3992  * could have changed by the L2 guest or the exit - i.e., the guest-state and
3993  * exit-information fields only. Other fields are modified by L1 with VMWRITE,
3994  * which already writes to vmcs12 directly.
3995  */
3996 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
3997                            u32 vm_exit_reason, u32 exit_intr_info,
3998                            unsigned long exit_qualification)
3999 {
4000         /* update exit information fields: */
4001         vmcs12->vm_exit_reason = vm_exit_reason;
4002         vmcs12->exit_qualification = exit_qualification;
4003         vmcs12->vm_exit_intr_info = exit_intr_info;
4004
4005         vmcs12->idt_vectoring_info_field = 0;
4006         vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4007         vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
4008
4009         if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
4010                 vmcs12->launch_state = 1;
4011
4012                 /* vm_entry_intr_info_field is cleared on exit. Emulate this
4013                  * instead of reading the real value. */
4014                 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
4015
4016                 /*
4017                  * Transfer the event that L0 or L1 may wanted to inject into
4018                  * L2 to IDT_VECTORING_INFO_FIELD.
4019                  */
4020                 vmcs12_save_pending_event(vcpu, vmcs12);
4021
4022                 /*
4023                  * According to spec, there's no need to store the guest's
4024                  * MSRs if the exit is due to a VM-entry failure that occurs
4025                  * during or after loading the guest state. Since this exit
4026                  * does not fall in that category, we need to save the MSRs.
4027                  */
4028                 if (nested_vmx_store_msr(vcpu,
4029                                          vmcs12->vm_exit_msr_store_addr,
4030                                          vmcs12->vm_exit_msr_store_count))
4031                         nested_vmx_abort(vcpu,
4032                                          VMX_ABORT_SAVE_GUEST_MSR_FAIL);
4033         }
4034
4035         /*
4036          * Drop what we picked up for L2 via vmx_complete_interrupts. It is
4037          * preserved above and would only end up incorrectly in L1.
4038          */
4039         vcpu->arch.nmi_injected = false;
4040         kvm_clear_exception_queue(vcpu);
4041         kvm_clear_interrupt_queue(vcpu);
4042 }
4043
4044 /*
4045  * A part of what we need to when the nested L2 guest exits and we want to
4046  * run its L1 parent, is to reset L1's guest state to the host state specified
4047  * in vmcs12.
4048  * This function is to be called not only on normal nested exit, but also on
4049  * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
4050  * Failures During or After Loading Guest State").
4051  * This function should be called when the active VMCS is L1's (vmcs01).
4052  */
4053 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
4054                                    struct vmcs12 *vmcs12)
4055 {
4056         struct kvm_segment seg;
4057         u32 entry_failure_code;
4058
4059         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
4060                 vcpu->arch.efer = vmcs12->host_ia32_efer;
4061         else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
4062                 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
4063         else
4064                 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
4065         vmx_set_efer(vcpu, vcpu->arch.efer);
4066
4067         kvm_rsp_write(vcpu, vmcs12->host_rsp);
4068         kvm_rip_write(vcpu, vmcs12->host_rip);
4069         vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
4070         vmx_set_interrupt_shadow(vcpu, 0);
4071
4072         /*
4073          * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
4074          * actually changed, because vmx_set_cr0 refers to efer set above.
4075          *
4076          * CR0_GUEST_HOST_MASK is already set in the original vmcs01
4077          * (KVM doesn't change it);
4078          */
4079         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
4080         vmx_set_cr0(vcpu, vmcs12->host_cr0);
4081
4082         /* Same as above - no reason to call set_cr4_guest_host_mask().  */
4083         vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
4084         vmx_set_cr4(vcpu, vmcs12->host_cr4);
4085
4086         nested_ept_uninit_mmu_context(vcpu);
4087
4088         /*
4089          * Only PDPTE load can fail as the value of cr3 was checked on entry and
4090          * couldn't have changed.
4091          */
4092         if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
4093                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
4094
4095         if (!enable_ept)
4096                 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
4097
4098         nested_vmx_transition_tlb_flush(vcpu, vmcs12, false);
4099
4100         vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
4101         vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
4102         vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
4103         vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
4104         vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
4105         vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
4106         vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
4107
4108         /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1.  */
4109         if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
4110                 vmcs_write64(GUEST_BNDCFGS, 0);
4111
4112         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
4113                 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
4114                 vcpu->arch.pat = vmcs12->host_ia32_pat;
4115         }
4116         if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
4117                 WARN_ON_ONCE(kvm_set_msr(vcpu, MSR_CORE_PERF_GLOBAL_CTRL,
4118                                          vmcs12->host_ia32_perf_global_ctrl));
4119
4120         /* Set L1 segment info according to Intel SDM
4121             27.5.2 Loading Host Segment and Descriptor-Table Registers */
4122         seg = (struct kvm_segment) {
4123                 .base = 0,
4124                 .limit = 0xFFFFFFFF,
4125                 .selector = vmcs12->host_cs_selector,
4126                 .type = 11,
4127                 .present = 1,
4128                 .s = 1,
4129                 .g = 1
4130         };
4131         if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
4132                 seg.l = 1;
4133         else
4134                 seg.db = 1;
4135         vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
4136         seg = (struct kvm_segment) {
4137                 .base = 0,
4138                 .limit = 0xFFFFFFFF,
4139                 .type = 3,
4140                 .present = 1,
4141                 .s = 1,
4142                 .db = 1,
4143                 .g = 1
4144         };
4145         seg.selector = vmcs12->host_ds_selector;
4146         vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
4147         seg.selector = vmcs12->host_es_selector;
4148         vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
4149         seg.selector = vmcs12->host_ss_selector;
4150         vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
4151         seg.selector = vmcs12->host_fs_selector;
4152         seg.base = vmcs12->host_fs_base;
4153         vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
4154         seg.selector = vmcs12->host_gs_selector;
4155         seg.base = vmcs12->host_gs_base;
4156         vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
4157         seg = (struct kvm_segment) {
4158                 .base = vmcs12->host_tr_base,
4159                 .limit = 0x67,
4160                 .selector = vmcs12->host_tr_selector,
4161                 .type = 11,
4162                 .present = 1
4163         };
4164         vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
4165
4166         kvm_set_dr(vcpu, 7, 0x400);
4167         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4168
4169         if (cpu_has_vmx_msr_bitmap())
4170                 vmx_update_msr_bitmap(vcpu);
4171
4172         if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
4173                                 vmcs12->vm_exit_msr_load_count))
4174                 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
4175 }
4176
4177 static inline u64 nested_vmx_get_vmcs01_guest_efer(struct vcpu_vmx *vmx)
4178 {
4179         struct shared_msr_entry *efer_msr;
4180         unsigned int i;
4181
4182         if (vm_entry_controls_get(vmx) & VM_ENTRY_LOAD_IA32_EFER)
4183                 return vmcs_read64(GUEST_IA32_EFER);
4184
4185         if (cpu_has_load_ia32_efer())
4186                 return host_efer;
4187
4188         for (i = 0; i < vmx->msr_autoload.guest.nr; ++i) {
4189                 if (vmx->msr_autoload.guest.val[i].index == MSR_EFER)
4190                         return vmx->msr_autoload.guest.val[i].value;
4191         }
4192
4193         efer_msr = find_msr_entry(vmx, MSR_EFER);
4194         if (efer_msr)
4195                 return efer_msr->data;
4196
4197         return host_efer;
4198 }
4199
4200 static void nested_vmx_restore_host_state(struct kvm_vcpu *vcpu)
4201 {
4202         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4203         struct vcpu_vmx *vmx = to_vmx(vcpu);
4204         struct vmx_msr_entry g, h;
4205         gpa_t gpa;
4206         u32 i, j;
4207
4208         vcpu->arch.pat = vmcs_read64(GUEST_IA32_PAT);
4209
4210         if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
4211                 /*
4212                  * L1's host DR7 is lost if KVM_GUESTDBG_USE_HW_BP is set
4213                  * as vmcs01.GUEST_DR7 contains a userspace defined value
4214                  * and vcpu->arch.dr7 is not squirreled away before the
4215                  * nested VMENTER (not worth adding a variable in nested_vmx).
4216                  */
4217                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
4218                         kvm_set_dr(vcpu, 7, DR7_FIXED_1);
4219                 else
4220                         WARN_ON(kvm_set_dr(vcpu, 7, vmcs_readl(GUEST_DR7)));
4221         }
4222
4223         /*
4224          * Note that calling vmx_set_{efer,cr0,cr4} is important as they
4225          * handle a variety of side effects to KVM's software model.
4226          */
4227         vmx_set_efer(vcpu, nested_vmx_get_vmcs01_guest_efer(vmx));
4228
4229         vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
4230         vmx_set_cr0(vcpu, vmcs_readl(CR0_READ_SHADOW));
4231
4232         vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
4233         vmx_set_cr4(vcpu, vmcs_readl(CR4_READ_SHADOW));
4234
4235         nested_ept_uninit_mmu_context(vcpu);
4236         vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
4237         kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
4238
4239         /*
4240          * Use ept_save_pdptrs(vcpu) to load the MMU's cached PDPTRs
4241          * from vmcs01 (if necessary).  The PDPTRs are not loaded on
4242          * VMFail, like everything else we just need to ensure our
4243          * software model is up-to-date.
4244          */
4245         if (enable_ept && is_pae_paging(vcpu))
4246                 ept_save_pdptrs(vcpu);
4247
4248         kvm_mmu_reset_context(vcpu);
4249
4250         if (cpu_has_vmx_msr_bitmap())
4251                 vmx_update_msr_bitmap(vcpu);
4252
4253         /*
4254          * This nasty bit of open coding is a compromise between blindly
4255          * loading L1's MSRs using the exit load lists (incorrect emulation
4256          * of VMFail), leaving the nested VM's MSRs in the software model
4257          * (incorrect behavior) and snapshotting the modified MSRs (too
4258          * expensive since the lists are unbound by hardware).  For each
4259          * MSR that was (prematurely) loaded from the nested VMEntry load
4260          * list, reload it from the exit load list if it exists and differs
4261          * from the guest value.  The intent is to stuff host state as
4262          * silently as possible, not to fully process the exit load list.
4263          */
4264         for (i = 0; i < vmcs12->vm_entry_msr_load_count; i++) {
4265                 gpa = vmcs12->vm_entry_msr_load_addr + (i * sizeof(g));
4266                 if (kvm_vcpu_read_guest(vcpu, gpa, &g, sizeof(g))) {
4267                         pr_debug_ratelimited(
4268                                 "%s read MSR index failed (%u, 0x%08llx)\n",
4269                                 __func__, i, gpa);
4270                         goto vmabort;
4271                 }
4272
4273                 for (j = 0; j < vmcs12->vm_exit_msr_load_count; j++) {
4274                         gpa = vmcs12->vm_exit_msr_load_addr + (j * sizeof(h));
4275                         if (kvm_vcpu_read_guest(vcpu, gpa, &h, sizeof(h))) {
4276                                 pr_debug_ratelimited(
4277                                         "%s read MSR failed (%u, 0x%08llx)\n",
4278                                         __func__, j, gpa);
4279                                 goto vmabort;
4280                         }
4281                         if (h.index != g.index)
4282                                 continue;
4283                         if (h.value == g.value)
4284                                 break;
4285
4286                         if (nested_vmx_load_msr_check(vcpu, &h)) {
4287                                 pr_debug_ratelimited(
4288                                         "%s check failed (%u, 0x%x, 0x%x)\n",
4289                                         __func__, j, h.index, h.reserved);
4290                                 goto vmabort;
4291                         }
4292
4293                         if (kvm_set_msr(vcpu, h.index, h.value)) {
4294                                 pr_debug_ratelimited(
4295                                         "%s WRMSR failed (%u, 0x%x, 0x%llx)\n",
4296                                         __func__, j, h.index, h.value);
4297                                 goto vmabort;
4298                         }
4299                 }
4300         }
4301
4302         return;
4303
4304 vmabort:
4305         nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
4306 }
4307
4308 /*
4309  * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
4310  * and modify vmcs12 to make it see what it would expect to see there if
4311  * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
4312  */
4313 void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 vm_exit_reason,
4314                        u32 exit_intr_info, unsigned long exit_qualification)
4315 {
4316         struct vcpu_vmx *vmx = to_vmx(vcpu);
4317         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4318
4319         /* trying to cancel vmlaunch/vmresume is a bug */
4320         WARN_ON_ONCE(vmx->nested.nested_run_pending);
4321
4322         /* Service the TLB flush request for L2 before switching to L1. */
4323         if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
4324                 kvm_vcpu_flush_tlb_current(vcpu);
4325
4326         leave_guest_mode(vcpu);
4327
4328         if (nested_cpu_has_preemption_timer(vmcs12))
4329                 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
4330
4331         if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING)
4332                 vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
4333
4334         if (likely(!vmx->fail)) {
4335                 sync_vmcs02_to_vmcs12(vcpu, vmcs12);
4336
4337                 if (vm_exit_reason != -1)
4338                         prepare_vmcs12(vcpu, vmcs12, vm_exit_reason,
4339                                        exit_intr_info, exit_qualification);
4340
4341                 /*
4342                  * Must happen outside of sync_vmcs02_to_vmcs12() as it will
4343                  * also be used to capture vmcs12 cache as part of
4344                  * capturing nVMX state for snapshot (migration).
4345                  *
4346                  * Otherwise, this flush will dirty guest memory at a
4347                  * point it is already assumed by user-space to be
4348                  * immutable.
4349                  */
4350                 nested_flush_cached_shadow_vmcs12(vcpu, vmcs12);
4351         } else {
4352                 /*
4353                  * The only expected VM-instruction error is "VM entry with
4354                  * invalid control field(s)." Anything else indicates a
4355                  * problem with L0.  And we should never get here with a
4356                  * VMFail of any type if early consistency checks are enabled.
4357                  */
4358                 WARN_ON_ONCE(vmcs_read32(VM_INSTRUCTION_ERROR) !=
4359                              VMXERR_ENTRY_INVALID_CONTROL_FIELD);
4360                 WARN_ON_ONCE(nested_early_check);
4361         }
4362
4363         vmx_switch_vmcs(vcpu, &vmx->vmcs01);
4364
4365         /* Update any VMCS fields that might have changed while L2 ran */
4366         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
4367         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
4368         vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
4369         if (vmx->nested.l1_tpr_threshold != -1)
4370                 vmcs_write32(TPR_THRESHOLD, vmx->nested.l1_tpr_threshold);
4371
4372         if (kvm_has_tsc_control)
4373                 decache_tsc_multiplier(vmx);
4374
4375         if (vmx->nested.change_vmcs01_virtual_apic_mode) {
4376                 vmx->nested.change_vmcs01_virtual_apic_mode = false;
4377                 vmx_set_virtual_apic_mode(vcpu);
4378         }
4379
4380         /* Unpin physical memory we referred to in vmcs02 */
4381         if (vmx->nested.apic_access_page) {
4382                 kvm_release_page_clean(vmx->nested.apic_access_page);
4383                 vmx->nested.apic_access_page = NULL;
4384         }
4385         kvm_vcpu_unmap(vcpu, &vmx->nested.virtual_apic_map, true);
4386         kvm_vcpu_unmap(vcpu, &vmx->nested.pi_desc_map, true);
4387         vmx->nested.pi_desc = NULL;
4388
4389         if (vmx->nested.reload_vmcs01_apic_access_page) {
4390                 vmx->nested.reload_vmcs01_apic_access_page = false;
4391                 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4392         }
4393
4394         if ((vm_exit_reason != -1) &&
4395             (enable_shadow_vmcs || vmx->nested.hv_evmcs))
4396                 vmx->nested.need_vmcs12_to_shadow_sync = true;
4397
4398         /* in case we halted in L2 */
4399         vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
4400
4401         if (likely(!vmx->fail)) {
4402                 if ((u16)vm_exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT &&
4403                     nested_exit_intr_ack_set(vcpu)) {
4404                         int irq = kvm_cpu_get_interrupt(vcpu);
4405                         WARN_ON(irq < 0);
4406                         vmcs12->vm_exit_intr_info = irq |
4407                                 INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
4408                 }
4409
4410                 if (vm_exit_reason != -1)
4411                         trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
4412                                                        vmcs12->exit_qualification,
4413                                                        vmcs12->idt_vectoring_info_field,
4414                                                        vmcs12->vm_exit_intr_info,
4415                                                        vmcs12->vm_exit_intr_error_code,
4416                                                        KVM_ISA_VMX);
4417
4418                 load_vmcs12_host_state(vcpu, vmcs12);
4419
4420                 return;
4421         }
4422
4423         /*
4424          * After an early L2 VM-entry failure, we're now back
4425          * in L1 which thinks it just finished a VMLAUNCH or
4426          * VMRESUME instruction, so we need to set the failure
4427          * flag and the VM-instruction error field of the VMCS
4428          * accordingly, and skip the emulated instruction.
4429          */
4430         (void)nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
4431
4432         /*
4433          * Restore L1's host state to KVM's software model.  We're here
4434          * because a consistency check was caught by hardware, which
4435          * means some amount of guest state has been propagated to KVM's
4436          * model and needs to be unwound to the host's state.
4437          */
4438         nested_vmx_restore_host_state(vcpu);
4439
4440         vmx->fail = 0;
4441 }
4442
4443 /*
4444  * Decode the memory-address operand of a vmx instruction, as recorded on an
4445  * exit caused by such an instruction (run by a guest hypervisor).
4446  * On success, returns 0. When the operand is invalid, returns 1 and throws
4447  * #UD, #GP, or #SS.
4448  */
4449 int get_vmx_mem_address(struct kvm_vcpu *vcpu, unsigned long exit_qualification,
4450                         u32 vmx_instruction_info, bool wr, int len, gva_t *ret)
4451 {
4452         gva_t off;
4453         bool exn;
4454         struct kvm_segment s;
4455
4456         /*
4457          * According to Vol. 3B, "Information for VM Exits Due to Instruction
4458          * Execution", on an exit, vmx_instruction_info holds most of the
4459          * addressing components of the operand. Only the displacement part
4460          * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
4461          * For how an actual address is calculated from all these components,
4462          * refer to Vol. 1, "Operand Addressing".
4463          */
4464         int  scaling = vmx_instruction_info & 3;
4465         int  addr_size = (vmx_instruction_info >> 7) & 7;
4466         bool is_reg = vmx_instruction_info & (1u << 10);
4467         int  seg_reg = (vmx_instruction_info >> 15) & 7;
4468         int  index_reg = (vmx_instruction_info >> 18) & 0xf;
4469         bool index_is_valid = !(vmx_instruction_info & (1u << 22));
4470         int  base_reg       = (vmx_instruction_info >> 23) & 0xf;
4471         bool base_is_valid  = !(vmx_instruction_info & (1u << 27));
4472
4473         if (is_reg) {
4474                 kvm_queue_exception(vcpu, UD_VECTOR);
4475                 return 1;
4476         }
4477
4478         /* Addr = segment_base + offset */
4479         /* offset = base + [index * scale] + displacement */
4480         off = exit_qualification; /* holds the displacement */
4481         if (addr_size == 1)
4482                 off = (gva_t)sign_extend64(off, 31);
4483         else if (addr_size == 0)
4484                 off = (gva_t)sign_extend64(off, 15);
4485         if (base_is_valid)
4486                 off += kvm_register_read(vcpu, base_reg);
4487         if (index_is_valid)
4488                 off += kvm_register_read(vcpu, index_reg) << scaling;
4489         vmx_get_segment(vcpu, &s, seg_reg);
4490
4491         /*
4492          * The effective address, i.e. @off, of a memory operand is truncated
4493          * based on the address size of the instruction.  Note that this is
4494          * the *effective address*, i.e. the address prior to accounting for
4495          * the segment's base.
4496          */
4497         if (addr_size == 1) /* 32 bit */
4498                 off &= 0xffffffff;
4499         else if (addr_size == 0) /* 16 bit */
4500                 off &= 0xffff;
4501
4502         /* Checks for #GP/#SS exceptions. */
4503         exn = false;
4504         if (is_long_mode(vcpu)) {
4505                 /*
4506                  * The virtual/linear address is never truncated in 64-bit
4507                  * mode, e.g. a 32-bit address size can yield a 64-bit virtual
4508                  * address when using FS/GS with a non-zero base.
4509                  */
4510                 if (seg_reg == VCPU_SREG_FS || seg_reg == VCPU_SREG_GS)
4511                         *ret = s.base + off;
4512                 else
4513                         *ret = off;
4514
4515                 /* Long mode: #GP(0)/#SS(0) if the memory address is in a
4516                  * non-canonical form. This is the only check on the memory
4517                  * destination for long mode!
4518                  */
4519                 exn = is_noncanonical_address(*ret, vcpu);
4520         } else {
4521                 /*
4522                  * When not in long mode, the virtual/linear address is
4523                  * unconditionally truncated to 32 bits regardless of the
4524                  * address size.
4525                  */
4526                 *ret = (s.base + off) & 0xffffffff;
4527
4528                 /* Protected mode: apply checks for segment validity in the
4529                  * following order:
4530                  * - segment type check (#GP(0) may be thrown)
4531                  * - usability check (#GP(0)/#SS(0))
4532                  * - limit check (#GP(0)/#SS(0))
4533                  */
4534                 if (wr)
4535                         /* #GP(0) if the destination operand is located in a
4536                          * read-only data segment or any code segment.
4537                          */
4538                         exn = ((s.type & 0xa) == 0 || (s.type & 8));
4539                 else
4540                         /* #GP(0) if the source operand is located in an
4541                          * execute-only code segment
4542                          */
4543                         exn = ((s.type & 0xa) == 8);
4544                 if (exn) {
4545                         kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
4546                         return 1;
4547                 }
4548                 /* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
4549                  */
4550                 exn = (s.unusable != 0);
4551
4552                 /*
4553                  * Protected mode: #GP(0)/#SS(0) if the memory operand is
4554                  * outside the segment limit.  All CPUs that support VMX ignore
4555                  * limit checks for flat segments, i.e. segments with base==0,
4556                  * limit==0xffffffff and of type expand-up data or code.
4557                  */
4558                 if (!(s.base == 0 && s.limit == 0xffffffff &&
4559                      ((s.type & 8) || !(s.type & 4))))
4560                         exn = exn || ((u64)off + len - 1 > s.limit);
4561         }
4562         if (exn) {
4563                 kvm_queue_exception_e(vcpu,
4564                                       seg_reg == VCPU_SREG_SS ?
4565                                                 SS_VECTOR : GP_VECTOR,
4566                                       0);
4567                 return 1;
4568         }
4569
4570         return 0;
4571 }
4572
4573 void nested_vmx_pmu_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
4574 {
4575         struct vcpu_vmx *vmx;
4576
4577         if (!nested_vmx_allowed(vcpu))
4578                 return;
4579
4580         vmx = to_vmx(vcpu);
4581         if (kvm_x86_ops.pmu_ops->is_valid_msr(vcpu, MSR_CORE_PERF_GLOBAL_CTRL)) {
4582                 vmx->nested.msrs.entry_ctls_high |=
4583                                 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
4584                 vmx->nested.msrs.exit_ctls_high |=
4585                                 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
4586         } else {
4587                 vmx->nested.msrs.entry_ctls_high &=
4588                                 ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
4589                 vmx->nested.msrs.exit_ctls_high &=
4590                                 ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
4591         }
4592 }
4593
4594 static int nested_vmx_get_vmptr(struct kvm_vcpu *vcpu, gpa_t *vmpointer)
4595 {
4596         gva_t gva;
4597         struct x86_exception e;
4598
4599         if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
4600                                 vmcs_read32(VMX_INSTRUCTION_INFO), false,
4601                                 sizeof(*vmpointer), &gva))
4602                 return 1;
4603
4604         if (kvm_read_guest_virt(vcpu, gva, vmpointer, sizeof(*vmpointer), &e)) {
4605                 kvm_inject_emulated_page_fault(vcpu, &e);
4606                 return 1;
4607         }
4608
4609         return 0;
4610 }
4611
4612 /*
4613  * Allocate a shadow VMCS and associate it with the currently loaded
4614  * VMCS, unless such a shadow VMCS already exists. The newly allocated
4615  * VMCS is also VMCLEARed, so that it is ready for use.
4616  */
4617 static struct vmcs *alloc_shadow_vmcs(struct kvm_vcpu *vcpu)
4618 {
4619         struct vcpu_vmx *vmx = to_vmx(vcpu);
4620         struct loaded_vmcs *loaded_vmcs = vmx->loaded_vmcs;
4621
4622         /*
4623          * We should allocate a shadow vmcs for vmcs01 only when L1
4624          * executes VMXON and free it when L1 executes VMXOFF.
4625          * As it is invalid to execute VMXON twice, we shouldn't reach
4626          * here when vmcs01 already have an allocated shadow vmcs.
4627          */
4628         WARN_ON(loaded_vmcs == &vmx->vmcs01 && loaded_vmcs->shadow_vmcs);
4629
4630         if (!loaded_vmcs->shadow_vmcs) {
4631                 loaded_vmcs->shadow_vmcs = alloc_vmcs(true);
4632                 if (loaded_vmcs->shadow_vmcs)
4633                         vmcs_clear(loaded_vmcs->shadow_vmcs);
4634         }
4635         return loaded_vmcs->shadow_vmcs;
4636 }
4637
4638 static int enter_vmx_operation(struct kvm_vcpu *vcpu)
4639 {
4640         struct vcpu_vmx *vmx = to_vmx(vcpu);
4641         int r;
4642
4643         r = alloc_loaded_vmcs(&vmx->nested.vmcs02);
4644         if (r < 0)
4645                 goto out_vmcs02;
4646
4647         vmx->nested.cached_vmcs12 = kzalloc(VMCS12_SIZE, GFP_KERNEL_ACCOUNT);
4648         if (!vmx->nested.cached_vmcs12)
4649                 goto out_cached_vmcs12;
4650
4651         vmx->nested.cached_shadow_vmcs12 = kzalloc(VMCS12_SIZE, GFP_KERNEL_ACCOUNT);
4652         if (!vmx->nested.cached_shadow_vmcs12)
4653                 goto out_cached_shadow_vmcs12;
4654
4655         if (enable_shadow_vmcs && !alloc_shadow_vmcs(vcpu))
4656                 goto out_shadow_vmcs;
4657
4658         hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
4659                      HRTIMER_MODE_REL_PINNED);
4660         vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
4661
4662         vmx->nested.vpid02 = allocate_vpid();
4663
4664         vmx->nested.vmcs02_initialized = false;
4665         vmx->nested.vmxon = true;
4666
4667         if (vmx_pt_mode_is_host_guest()) {
4668                 vmx->pt_desc.guest.ctl = 0;
4669                 pt_update_intercept_for_msr(vmx);
4670         }
4671
4672         return 0;
4673
4674 out_shadow_vmcs:
4675         kfree(vmx->nested.cached_shadow_vmcs12);
4676
4677 out_cached_shadow_vmcs12:
4678         kfree(vmx->nested.cached_vmcs12);
4679
4680 out_cached_vmcs12:
4681         free_loaded_vmcs(&vmx->nested.vmcs02);
4682
4683 out_vmcs02:
4684         return -ENOMEM;
4685 }
4686
4687 /*
4688  * Emulate the VMXON instruction.
4689  * Currently, we just remember that VMX is active, and do not save or even
4690  * inspect the argument to VMXON (the so-called "VMXON pointer") because we
4691  * do not currently need to store anything in that guest-allocated memory
4692  * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
4693  * argument is different from the VMXON pointer (which the spec says they do).
4694  */
4695 static int handle_vmon(struct kvm_vcpu *vcpu)
4696 {
4697         int ret;
4698         gpa_t vmptr;
4699         uint32_t revision;
4700         struct vcpu_vmx *vmx = to_vmx(vcpu);
4701         const u64 VMXON_NEEDED_FEATURES = FEAT_CTL_LOCKED
4702                 | FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
4703
4704         /*
4705          * The Intel VMX Instruction Reference lists a bunch of bits that are
4706          * prerequisite to running VMXON, most notably cr4.VMXE must be set to
4707          * 1 (see vmx_set_cr4() for when we allow the guest to set this).
4708          * Otherwise, we should fail with #UD.  But most faulting conditions
4709          * have already been checked by hardware, prior to the VM-exit for
4710          * VMXON.  We do test guest cr4.VMXE because processor CR4 always has
4711          * that bit set to 1 in non-root mode.
4712          */
4713         if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) {
4714                 kvm_queue_exception(vcpu, UD_VECTOR);
4715                 return 1;
4716         }
4717
4718         /* CPL=0 must be checked manually. */
4719         if (vmx_get_cpl(vcpu)) {
4720                 kvm_inject_gp(vcpu, 0);
4721                 return 1;
4722         }
4723
4724         if (vmx->nested.vmxon)
4725                 return nested_vmx_failValid(vcpu,
4726                         VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
4727
4728         if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
4729                         != VMXON_NEEDED_FEATURES) {
4730                 kvm_inject_gp(vcpu, 0);
4731                 return 1;
4732         }
4733
4734         if (nested_vmx_get_vmptr(vcpu, &vmptr))
4735                 return 1;
4736
4737         /*
4738          * SDM 3: 24.11.5
4739          * The first 4 bytes of VMXON region contain the supported
4740          * VMCS revision identifier
4741          *
4742          * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
4743          * which replaces physical address width with 32
4744          */
4745         if (!page_address_valid(vcpu, vmptr))
4746                 return nested_vmx_failInvalid(vcpu);
4747
4748         if (kvm_read_guest(vcpu->kvm, vmptr, &revision, sizeof(revision)) ||
4749             revision != VMCS12_REVISION)
4750                 return nested_vmx_failInvalid(vcpu);
4751
4752         vmx->nested.vmxon_ptr = vmptr;
4753         ret = enter_vmx_operation(vcpu);
4754         if (ret)
4755                 return ret;
4756
4757         return nested_vmx_succeed(vcpu);
4758 }
4759
4760 static inline void nested_release_vmcs12(struct kvm_vcpu *vcpu)
4761 {
4762         struct vcpu_vmx *vmx = to_vmx(vcpu);
4763
4764         if (vmx->nested.current_vmptr == -1ull)
4765                 return;
4766
4767         copy_vmcs02_to_vmcs12_rare(vcpu, get_vmcs12(vcpu));
4768
4769         if (enable_shadow_vmcs) {
4770                 /* copy to memory all shadowed fields in case
4771                    they were modified */
4772                 copy_shadow_to_vmcs12(vmx);
4773                 vmx_disable_shadow_vmcs(vmx);
4774         }
4775         vmx->nested.posted_intr_nv = -1;
4776
4777         /* Flush VMCS12 to guest memory */
4778         kvm_vcpu_write_guest_page(vcpu,
4779                                   vmx->nested.current_vmptr >> PAGE_SHIFT,
4780                                   vmx->nested.cached_vmcs12, 0, VMCS12_SIZE);
4781
4782         kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
4783
4784         vmx->nested.current_vmptr = -1ull;
4785 }
4786
4787 /* Emulate the VMXOFF instruction */
4788 static int handle_vmoff(struct kvm_vcpu *vcpu)
4789 {
4790         if (!nested_vmx_check_permission(vcpu))
4791                 return 1;
4792
4793         free_nested(vcpu);
4794
4795         /* Process a latched INIT during time CPU was in VMX operation */
4796         kvm_make_request(KVM_REQ_EVENT, vcpu);
4797
4798         return nested_vmx_succeed(vcpu);
4799 }
4800
4801 /* Emulate the VMCLEAR instruction */
4802 static int handle_vmclear(struct kvm_vcpu *vcpu)
4803 {
4804         struct vcpu_vmx *vmx = to_vmx(vcpu);
4805         u32 zero = 0;
4806         gpa_t vmptr;
4807         u64 evmcs_gpa;
4808
4809         if (!nested_vmx_check_permission(vcpu))
4810                 return 1;
4811
4812         if (nested_vmx_get_vmptr(vcpu, &vmptr))
4813                 return 1;
4814
4815         if (!page_address_valid(vcpu, vmptr))
4816                 return nested_vmx_failValid(vcpu,
4817                         VMXERR_VMCLEAR_INVALID_ADDRESS);
4818
4819         if (vmptr == vmx->nested.vmxon_ptr)
4820                 return nested_vmx_failValid(vcpu,
4821                         VMXERR_VMCLEAR_VMXON_POINTER);
4822
4823         /*
4824          * When Enlightened VMEntry is enabled on the calling CPU we treat
4825          * memory area pointer by vmptr as Enlightened VMCS (as there's no good
4826          * way to distinguish it from VMCS12) and we must not corrupt it by
4827          * writing to the non-existent 'launch_state' field. The area doesn't
4828          * have to be the currently active EVMCS on the calling CPU and there's
4829          * nothing KVM has to do to transition it from 'active' to 'non-active'
4830          * state. It is possible that the area will stay mapped as
4831          * vmx->nested.hv_evmcs but this shouldn't be a problem.
4832          */
4833         if (likely(!vmx->nested.enlightened_vmcs_enabled ||
4834                    !nested_enlightened_vmentry(vcpu, &evmcs_gpa))) {
4835                 if (vmptr == vmx->nested.current_vmptr)
4836                         nested_release_vmcs12(vcpu);
4837
4838                 kvm_vcpu_write_guest(vcpu,
4839                                      vmptr + offsetof(struct vmcs12,
4840                                                       launch_state),
4841                                      &zero, sizeof(zero));
4842         }
4843
4844         return nested_vmx_succeed(vcpu);
4845 }
4846
4847 /* Emulate the VMLAUNCH instruction */
4848 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
4849 {
4850         return nested_vmx_run(vcpu, true);
4851 }
4852
4853 /* Emulate the VMRESUME instruction */
4854 static int handle_vmresume(struct kvm_vcpu *vcpu)
4855 {
4856
4857         return nested_vmx_run(vcpu, false);
4858 }
4859
4860 static int handle_vmread(struct kvm_vcpu *vcpu)
4861 {
4862         struct vmcs12 *vmcs12 = is_guest_mode(vcpu) ? get_shadow_vmcs12(vcpu)
4863                                                     : get_vmcs12(vcpu);
4864         unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
4865         u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
4866         struct vcpu_vmx *vmx = to_vmx(vcpu);
4867         struct x86_exception e;
4868         unsigned long field;
4869         u64 value;
4870         gva_t gva = 0;
4871         short offset;
4872         int len;
4873
4874         if (!nested_vmx_check_permission(vcpu))
4875                 return 1;
4876
4877         /*
4878          * In VMX non-root operation, when the VMCS-link pointer is -1ull,
4879          * any VMREAD sets the ALU flags for VMfailInvalid.
4880          */
4881         if (vmx->nested.current_vmptr == -1ull ||
4882             (is_guest_mode(vcpu) &&
4883              get_vmcs12(vcpu)->vmcs_link_pointer == -1ull))
4884                 return nested_vmx_failInvalid(vcpu);
4885
4886         /* Decode instruction info and find the field to read */
4887         field = kvm_register_readl(vcpu, (((instr_info) >> 28) & 0xf));
4888
4889         offset = vmcs_field_to_offset(field);
4890         if (offset < 0)
4891                 return nested_vmx_failValid(vcpu,
4892                         VMXERR_UNSUPPORTED_VMCS_COMPONENT);
4893
4894         if (!is_guest_mode(vcpu) && is_vmcs12_ext_field(field))
4895                 copy_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
4896
4897         /* Read the field, zero-extended to a u64 value */
4898         value = vmcs12_read_any(vmcs12, field, offset);
4899
4900         /*
4901          * Now copy part of this value to register or memory, as requested.
4902          * Note that the number of bits actually copied is 32 or 64 depending
4903          * on the guest's mode (32 or 64 bit), not on the given field's length.
4904          */
4905         if (instr_info & BIT(10)) {
4906                 kvm_register_writel(vcpu, (((instr_info) >> 3) & 0xf), value);
4907         } else {
4908                 len = is_64_bit_mode(vcpu) ? 8 : 4;
4909                 if (get_vmx_mem_address(vcpu, exit_qualification,
4910                                         instr_info, true, len, &gva))
4911                         return 1;
4912                 /* _system ok, nested_vmx_check_permission has verified cpl=0 */
4913                 if (kvm_write_guest_virt_system(vcpu, gva, &value, len, &e)) {
4914                         kvm_inject_emulated_page_fault(vcpu, &e);
4915                         return 1;
4916                 }
4917         }
4918
4919         return nested_vmx_succeed(vcpu);
4920 }
4921
4922 static bool is_shadow_field_rw(unsigned long field)
4923 {
4924         switch (field) {
4925 #define SHADOW_FIELD_RW(x, y) case x:
4926 #include "vmcs_shadow_fields.h"
4927                 return true;
4928         default:
4929                 break;
4930         }
4931         return false;
4932 }
4933
4934 static bool is_shadow_field_ro(unsigned long field)
4935 {
4936         switch (field) {
4937 #define SHADOW_FIELD_RO(x, y) case x:
4938 #include "vmcs_shadow_fields.h"
4939                 return true;
4940         default:
4941                 break;
4942         }
4943         return false;
4944 }
4945
4946 static int handle_vmwrite(struct kvm_vcpu *vcpu)
4947 {
4948         struct vmcs12 *vmcs12 = is_guest_mode(vcpu) ? get_shadow_vmcs12(vcpu)
4949                                                     : get_vmcs12(vcpu);
4950         unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
4951         u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
4952         struct vcpu_vmx *vmx = to_vmx(vcpu);
4953         struct x86_exception e;
4954         unsigned long field;
4955         short offset;
4956         gva_t gva;
4957         int len;
4958
4959         /*
4960          * The value to write might be 32 or 64 bits, depending on L1's long
4961          * mode, and eventually we need to write that into a field of several
4962          * possible lengths. The code below first zero-extends the value to 64
4963          * bit (value), and then copies only the appropriate number of
4964          * bits into the vmcs12 field.
4965          */
4966         u64 value = 0;
4967
4968         if (!nested_vmx_check_permission(vcpu))
4969                 return 1;
4970
4971         /*
4972          * In VMX non-root operation, when the VMCS-link pointer is -1ull,
4973          * any VMWRITE sets the ALU flags for VMfailInvalid.
4974          */
4975         if (vmx->nested.current_vmptr == -1ull ||
4976             (is_guest_mode(vcpu) &&
4977              get_vmcs12(vcpu)->vmcs_link_pointer == -1ull))
4978                 return nested_vmx_failInvalid(vcpu);
4979
4980         if (instr_info & BIT(10))
4981                 value = kvm_register_readl(vcpu, (((instr_info) >> 3) & 0xf));
4982         else {
4983                 len = is_64_bit_mode(vcpu) ? 8 : 4;
4984                 if (get_vmx_mem_address(vcpu, exit_qualification,
4985                                         instr_info, false, len, &gva))
4986                         return 1;
4987                 if (kvm_read_guest_virt(vcpu, gva, &value, len, &e)) {
4988                         kvm_inject_emulated_page_fault(vcpu, &e);
4989                         return 1;
4990                 }
4991         }
4992
4993         field = kvm_register_readl(vcpu, (((instr_info) >> 28) & 0xf));
4994
4995         offset = vmcs_field_to_offset(field);
4996         if (offset < 0)
4997                 return nested_vmx_failValid(vcpu,
4998                         VMXERR_UNSUPPORTED_VMCS_COMPONENT);
4999
5000         /*
5001          * If the vCPU supports "VMWRITE to any supported field in the
5002          * VMCS," then the "read-only" fields are actually read/write.
5003          */
5004         if (vmcs_field_readonly(field) &&
5005             !nested_cpu_has_vmwrite_any_field(vcpu))
5006                 return nested_vmx_failValid(vcpu,
5007                         VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
5008
5009         /*
5010          * Ensure vmcs12 is up-to-date before any VMWRITE that dirties
5011          * vmcs12, else we may crush a field or consume a stale value.
5012          */
5013         if (!is_guest_mode(vcpu) && !is_shadow_field_rw(field))
5014                 copy_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
5015
5016         /*
5017          * Some Intel CPUs intentionally drop the reserved bits of the AR byte
5018          * fields on VMWRITE.  Emulate this behavior to ensure consistent KVM
5019          * behavior regardless of the underlying hardware, e.g. if an AR_BYTE
5020          * field is intercepted for VMWRITE but not VMREAD (in L1), then VMREAD
5021          * from L1 will return a different value than VMREAD from L2 (L1 sees
5022          * the stripped down value, L2 sees the full value as stored by KVM).
5023          */
5024         if (field >= GUEST_ES_AR_BYTES && field <= GUEST_TR_AR_BYTES)
5025                 value &= 0x1f0ff;
5026
5027         vmcs12_write_any(vmcs12, field, offset, value);
5028
5029         /*
5030          * Do not track vmcs12 dirty-state if in guest-mode as we actually
5031          * dirty shadow vmcs12 instead of vmcs12.  Fields that can be updated
5032          * by L1 without a vmexit are always updated in the vmcs02, i.e. don't
5033          * "dirty" vmcs12, all others go down the prepare_vmcs02() slow path.
5034          */
5035         if (!is_guest_mode(vcpu) && !is_shadow_field_rw(field)) {
5036                 /*
5037                  * L1 can read these fields without exiting, ensure the
5038                  * shadow VMCS is up-to-date.
5039                  */
5040                 if (enable_shadow_vmcs && is_shadow_field_ro(field)) {
5041                         preempt_disable();
5042                         vmcs_load(vmx->vmcs01.shadow_vmcs);
5043
5044                         __vmcs_writel(field, value);
5045
5046                         vmcs_clear(vmx->vmcs01.shadow_vmcs);
5047                         vmcs_load(vmx->loaded_vmcs->vmcs);
5048                         preempt_enable();
5049                 }
5050                 vmx->nested.dirty_vmcs12 = true;
5051         }
5052
5053         return nested_vmx_succeed(vcpu);
5054 }
5055
5056 static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
5057 {
5058         vmx->nested.current_vmptr = vmptr;
5059         if (enable_shadow_vmcs) {
5060                 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_SHADOW_VMCS);
5061                 vmcs_write64(VMCS_LINK_POINTER,
5062                              __pa(vmx->vmcs01.shadow_vmcs));
5063                 vmx->nested.need_vmcs12_to_shadow_sync = true;
5064         }
5065         vmx->nested.dirty_vmcs12 = true;
5066 }
5067
5068 /* Emulate the VMPTRLD instruction */
5069 static int handle_vmptrld(struct kvm_vcpu *vcpu)
5070 {
5071         struct vcpu_vmx *vmx = to_vmx(vcpu);
5072         gpa_t vmptr;
5073
5074         if (!nested_vmx_check_permission(vcpu))
5075                 return 1;
5076
5077         if (nested_vmx_get_vmptr(vcpu, &vmptr))
5078                 return 1;
5079
5080         if (!page_address_valid(vcpu, vmptr))
5081                 return nested_vmx_failValid(vcpu,
5082                         VMXERR_VMPTRLD_INVALID_ADDRESS);
5083
5084         if (vmptr == vmx->nested.vmxon_ptr)
5085                 return nested_vmx_failValid(vcpu,
5086                         VMXERR_VMPTRLD_VMXON_POINTER);
5087
5088         /* Forbid normal VMPTRLD if Enlightened version was used */
5089         if (vmx->nested.hv_evmcs)
5090                 return 1;
5091
5092         if (vmx->nested.current_vmptr != vmptr) {
5093                 struct kvm_host_map map;
5094                 struct vmcs12 *new_vmcs12;
5095
5096                 if (kvm_vcpu_map(vcpu, gpa_to_gfn(vmptr), &map)) {
5097                         /*
5098                          * Reads from an unbacked page return all 1s,
5099                          * which means that the 32 bits located at the
5100                          * given physical address won't match the required
5101                          * VMCS12_REVISION identifier.
5102                          */
5103                         return nested_vmx_failValid(vcpu,
5104                                 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
5105                 }
5106
5107                 new_vmcs12 = map.hva;
5108
5109                 if (new_vmcs12->hdr.revision_id != VMCS12_REVISION ||
5110                     (new_vmcs12->hdr.shadow_vmcs &&
5111                      !nested_cpu_has_vmx_shadow_vmcs(vcpu))) {
5112                         kvm_vcpu_unmap(vcpu, &map, false);
5113                         return nested_vmx_failValid(vcpu,
5114                                 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
5115                 }
5116
5117                 nested_release_vmcs12(vcpu);
5118
5119                 /*
5120                  * Load VMCS12 from guest memory since it is not already
5121                  * cached.
5122                  */
5123                 memcpy(vmx->nested.cached_vmcs12, new_vmcs12, VMCS12_SIZE);
5124                 kvm_vcpu_unmap(vcpu, &map, false);
5125
5126                 set_current_vmptr(vmx, vmptr);
5127         }
5128
5129         return nested_vmx_succeed(vcpu);
5130 }
5131
5132 /* Emulate the VMPTRST instruction */
5133 static int handle_vmptrst(struct kvm_vcpu *vcpu)
5134 {
5135         unsigned long exit_qual = vmx_get_exit_qual(vcpu);
5136         u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5137         gpa_t current_vmptr = to_vmx(vcpu)->nested.current_vmptr;
5138         struct x86_exception e;
5139         gva_t gva;
5140
5141         if (!nested_vmx_check_permission(vcpu))
5142                 return 1;
5143
5144         if (unlikely(to_vmx(vcpu)->nested.hv_evmcs))
5145                 return 1;
5146
5147         if (get_vmx_mem_address(vcpu, exit_qual, instr_info,
5148                                 true, sizeof(gpa_t), &gva))
5149                 return 1;
5150         /* *_system ok, nested_vmx_check_permission has verified cpl=0 */
5151         if (kvm_write_guest_virt_system(vcpu, gva, (void *)&current_vmptr,
5152                                         sizeof(gpa_t), &e)) {
5153                 kvm_inject_emulated_page_fault(vcpu, &e);
5154                 return 1;
5155         }
5156         return nested_vmx_succeed(vcpu);
5157 }
5158
5159 #define EPTP_PA_MASK   GENMASK_ULL(51, 12)
5160
5161 static bool nested_ept_root_matches(hpa_t root_hpa, u64 root_eptp, u64 eptp)
5162 {
5163         return VALID_PAGE(root_hpa) &&
5164                 ((root_eptp & EPTP_PA_MASK) == (eptp & EPTP_PA_MASK));
5165 }
5166
5167 /* Emulate the INVEPT instruction */
5168 static int handle_invept(struct kvm_vcpu *vcpu)
5169 {
5170         struct vcpu_vmx *vmx = to_vmx(vcpu);
5171         u32 vmx_instruction_info, types;
5172         unsigned long type, roots_to_free;
5173         struct kvm_mmu *mmu;
5174         gva_t gva;
5175         struct x86_exception e;
5176         struct {
5177                 u64 eptp, gpa;
5178         } operand;
5179         int i;
5180
5181         if (!(vmx->nested.msrs.secondary_ctls_high &
5182               SECONDARY_EXEC_ENABLE_EPT) ||
5183             !(vmx->nested.msrs.ept_caps & VMX_EPT_INVEPT_BIT)) {
5184                 kvm_queue_exception(vcpu, UD_VECTOR);
5185                 return 1;
5186         }
5187
5188         if (!nested_vmx_check_permission(vcpu))
5189                 return 1;
5190
5191         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5192         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5193
5194         types = (vmx->nested.msrs.ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
5195
5196         if (type >= 32 || !(types & (1 << type)))
5197                 return nested_vmx_failValid(vcpu,
5198                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
5199
5200         /* According to the Intel VMX instruction reference, the memory
5201          * operand is read even if it isn't needed (e.g., for type==global)
5202          */
5203         if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5204                         vmx_instruction_info, false, sizeof(operand), &gva))
5205                 return 1;
5206         if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
5207                 kvm_inject_emulated_page_fault(vcpu, &e);
5208                 return 1;
5209         }
5210
5211         /*
5212          * Nested EPT roots are always held through guest_mmu,
5213          * not root_mmu.
5214          */
5215         mmu = &vcpu->arch.guest_mmu;
5216
5217         switch (type) {
5218         case VMX_EPT_EXTENT_CONTEXT:
5219                 if (!nested_vmx_check_eptp(vcpu, operand.eptp))
5220                         return nested_vmx_failValid(vcpu,
5221                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
5222
5223                 roots_to_free = 0;
5224                 if (nested_ept_root_matches(mmu->root_hpa, mmu->root_pgd,
5225                                             operand.eptp))
5226                         roots_to_free |= KVM_MMU_ROOT_CURRENT;
5227
5228                 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5229                         if (nested_ept_root_matches(mmu->prev_roots[i].hpa,
5230                                                     mmu->prev_roots[i].pgd,
5231                                                     operand.eptp))
5232                                 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5233                 }
5234                 break;
5235         case VMX_EPT_EXTENT_GLOBAL:
5236                 roots_to_free = KVM_MMU_ROOTS_ALL;
5237                 break;
5238         default:
5239                 BUG_ON(1);
5240                 break;
5241         }
5242
5243         if (roots_to_free)
5244                 kvm_mmu_free_roots(vcpu, mmu, roots_to_free);
5245
5246         return nested_vmx_succeed(vcpu);
5247 }
5248
5249 static int handle_invvpid(struct kvm_vcpu *vcpu)
5250 {
5251         struct vcpu_vmx *vmx = to_vmx(vcpu);
5252         u32 vmx_instruction_info;
5253         unsigned long type, types;
5254         gva_t gva;
5255         struct x86_exception e;
5256         struct {
5257                 u64 vpid;
5258                 u64 gla;
5259         } operand;
5260         u16 vpid02;
5261
5262         if (!(vmx->nested.msrs.secondary_ctls_high &
5263               SECONDARY_EXEC_ENABLE_VPID) ||
5264                         !(vmx->nested.msrs.vpid_caps & VMX_VPID_INVVPID_BIT)) {
5265                 kvm_queue_exception(vcpu, UD_VECTOR);
5266                 return 1;
5267         }
5268
5269         if (!nested_vmx_check_permission(vcpu))
5270                 return 1;
5271
5272         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5273         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5274
5275         types = (vmx->nested.msrs.vpid_caps &
5276                         VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
5277
5278         if (type >= 32 || !(types & (1 << type)))
5279                 return nested_vmx_failValid(vcpu,
5280                         VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
5281
5282         /* according to the intel vmx instruction reference, the memory
5283          * operand is read even if it isn't needed (e.g., for type==global)
5284          */
5285         if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5286                         vmx_instruction_info, false, sizeof(operand), &gva))
5287                 return 1;
5288         if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
5289                 kvm_inject_emulated_page_fault(vcpu, &e);
5290                 return 1;
5291         }
5292         if (operand.vpid >> 16)
5293                 return nested_vmx_failValid(vcpu,
5294                         VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
5295
5296         vpid02 = nested_get_vpid02(vcpu);
5297         switch (type) {
5298         case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
5299                 if (!operand.vpid ||
5300                     is_noncanonical_address(operand.gla, vcpu))
5301                         return nested_vmx_failValid(vcpu,
5302                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
5303                 vpid_sync_vcpu_addr(vpid02, operand.gla);
5304                 break;
5305         case VMX_VPID_EXTENT_SINGLE_CONTEXT:
5306         case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
5307                 if (!operand.vpid)
5308                         return nested_vmx_failValid(vcpu,
5309                                 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
5310                 vpid_sync_context(vpid02);
5311                 break;
5312         case VMX_VPID_EXTENT_ALL_CONTEXT:
5313                 vpid_sync_context(vpid02);
5314                 break;
5315         default:
5316                 WARN_ON_ONCE(1);
5317                 return kvm_skip_emulated_instruction(vcpu);
5318         }
5319
5320         /*
5321          * Sync the shadow page tables if EPT is disabled, L1 is invalidating
5322          * linear mappings for L2 (tagged with L2's VPID).  Free all roots as
5323          * VPIDs are not tracked in the MMU role.
5324          *
5325          * Note, this operates on root_mmu, not guest_mmu, as L1 and L2 share
5326          * an MMU when EPT is disabled.
5327          *
5328          * TODO: sync only the affected SPTEs for INVDIVIDUAL_ADDR.
5329          */
5330         if (!enable_ept)
5331                 kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu,
5332                                    KVM_MMU_ROOTS_ALL);
5333
5334         return nested_vmx_succeed(vcpu);
5335 }
5336
5337 static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
5338                                      struct vmcs12 *vmcs12)
5339 {
5340         u32 index = kvm_rcx_read(vcpu);
5341         u64 new_eptp;
5342         bool accessed_dirty;
5343         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
5344
5345         if (!nested_cpu_has_eptp_switching(vmcs12) ||
5346             !nested_cpu_has_ept(vmcs12))
5347                 return 1;
5348
5349         if (index >= VMFUNC_EPTP_ENTRIES)
5350                 return 1;
5351
5352
5353         if (kvm_vcpu_read_guest_page(vcpu, vmcs12->eptp_list_address >> PAGE_SHIFT,
5354                                      &new_eptp, index * 8, 8))
5355                 return 1;
5356
5357         accessed_dirty = !!(new_eptp & VMX_EPTP_AD_ENABLE_BIT);
5358
5359         /*
5360          * If the (L2) guest does a vmfunc to the currently
5361          * active ept pointer, we don't have to do anything else
5362          */
5363         if (vmcs12->ept_pointer != new_eptp) {
5364                 if (!nested_vmx_check_eptp(vcpu, new_eptp))
5365                         return 1;
5366
5367                 kvm_mmu_unload(vcpu);
5368                 mmu->ept_ad = accessed_dirty;
5369                 mmu->mmu_role.base.ad_disabled = !accessed_dirty;
5370                 vmcs12->ept_pointer = new_eptp;
5371                 /*
5372                  * TODO: Check what's the correct approach in case
5373                  * mmu reload fails. Currently, we just let the next
5374                  * reload potentially fail
5375                  */
5376                 kvm_mmu_reload(vcpu);
5377         }
5378
5379         return 0;
5380 }
5381
5382 static int handle_vmfunc(struct kvm_vcpu *vcpu)
5383 {
5384         struct vcpu_vmx *vmx = to_vmx(vcpu);
5385         struct vmcs12 *vmcs12;
5386         u32 function = kvm_rax_read(vcpu);
5387
5388         /*
5389          * VMFUNC is only supported for nested guests, but we always enable the
5390          * secondary control for simplicity; for non-nested mode, fake that we
5391          * didn't by injecting #UD.
5392          */
5393         if (!is_guest_mode(vcpu)) {
5394                 kvm_queue_exception(vcpu, UD_VECTOR);
5395                 return 1;
5396         }
5397
5398         vmcs12 = get_vmcs12(vcpu);
5399         if ((vmcs12->vm_function_control & (1 << function)) == 0)
5400                 goto fail;
5401
5402         switch (function) {
5403         case 0:
5404                 if (nested_vmx_eptp_switching(vcpu, vmcs12))
5405                         goto fail;
5406                 break;
5407         default:
5408                 goto fail;
5409         }
5410         return kvm_skip_emulated_instruction(vcpu);
5411
5412 fail:
5413         nested_vmx_vmexit(vcpu, vmx->exit_reason,
5414                           vmx_get_intr_info(vcpu),
5415                           vmx_get_exit_qual(vcpu));
5416         return 1;
5417 }
5418
5419 /*
5420  * Return true if an IO instruction with the specified port and size should cause
5421  * a VM-exit into L1.
5422  */
5423 bool nested_vmx_check_io_bitmaps(struct kvm_vcpu *vcpu, unsigned int port,
5424                                  int size)
5425 {
5426         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5427         gpa_t bitmap, last_bitmap;
5428         u8 b;
5429
5430         last_bitmap = (gpa_t)-1;
5431         b = -1;
5432
5433         while (size > 0) {
5434                 if (port < 0x8000)
5435                         bitmap = vmcs12->io_bitmap_a;
5436                 else if (port < 0x10000)
5437                         bitmap = vmcs12->io_bitmap_b;
5438                 else
5439                         return true;
5440                 bitmap += (port & 0x7fff) / 8;
5441
5442                 if (last_bitmap != bitmap)
5443                         if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
5444                                 return true;
5445                 if (b & (1 << (port & 7)))
5446                         return true;
5447
5448                 port++;
5449                 size--;
5450                 last_bitmap = bitmap;
5451         }
5452
5453         return false;
5454 }
5455
5456 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
5457                                        struct vmcs12 *vmcs12)
5458 {
5459         unsigned long exit_qualification;
5460         unsigned short port;
5461         int size;
5462
5463         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
5464                 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
5465
5466         exit_qualification = vmx_get_exit_qual(vcpu);
5467
5468         port = exit_qualification >> 16;
5469         size = (exit_qualification & 7) + 1;
5470
5471         return nested_vmx_check_io_bitmaps(vcpu, port, size);
5472 }
5473
5474 /*
5475  * Return 1 if we should exit from L2 to L1 to handle an MSR access,
5476  * rather than handle it ourselves in L0. I.e., check whether L1 expressed
5477  * disinterest in the current event (read or write a specific MSR) by using an
5478  * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
5479  */
5480 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
5481         struct vmcs12 *vmcs12, u32 exit_reason)
5482 {
5483         u32 msr_index = kvm_rcx_read(vcpu);
5484         gpa_t bitmap;
5485
5486         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
5487                 return true;
5488
5489         /*
5490          * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
5491          * for the four combinations of read/write and low/high MSR numbers.
5492          * First we need to figure out which of the four to use:
5493          */
5494         bitmap = vmcs12->msr_bitmap;
5495         if (exit_reason == EXIT_REASON_MSR_WRITE)
5496                 bitmap += 2048;
5497         if (msr_index >= 0xc0000000) {
5498                 msr_index -= 0xc0000000;
5499                 bitmap += 1024;
5500         }
5501
5502         /* Then read the msr_index'th bit from this bitmap: */
5503         if (msr_index < 1024*8) {
5504                 unsigned char b;
5505                 if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
5506                         return true;
5507                 return 1 & (b >> (msr_index & 7));
5508         } else
5509                 return true; /* let L1 handle the wrong parameter */
5510 }
5511
5512 /*
5513  * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
5514  * rather than handle it ourselves in L0. I.e., check if L1 wanted to
5515  * intercept (via guest_host_mask etc.) the current event.
5516  */
5517 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
5518         struct vmcs12 *vmcs12)
5519 {
5520         unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5521         int cr = exit_qualification & 15;
5522         int reg;
5523         unsigned long val;
5524
5525         switch ((exit_qualification >> 4) & 3) {
5526         case 0: /* mov to cr */
5527                 reg = (exit_qualification >> 8) & 15;
5528                 val = kvm_register_readl(vcpu, reg);
5529                 switch (cr) {
5530                 case 0:
5531                         if (vmcs12->cr0_guest_host_mask &
5532                             (val ^ vmcs12->cr0_read_shadow))
5533                                 return true;
5534                         break;
5535                 case 3:
5536                         if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
5537                                 return true;
5538                         break;
5539                 case 4:
5540                         if (vmcs12->cr4_guest_host_mask &
5541                             (vmcs12->cr4_read_shadow ^ val))
5542                                 return true;
5543                         break;
5544                 case 8:
5545                         if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
5546                                 return true;
5547                         break;
5548                 }
5549                 break;
5550         case 2: /* clts */
5551                 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
5552                     (vmcs12->cr0_read_shadow & X86_CR0_TS))
5553                         return true;
5554                 break;
5555         case 1: /* mov from cr */
5556                 switch (cr) {
5557                 case 3:
5558                         if (vmcs12->cpu_based_vm_exec_control &
5559                             CPU_BASED_CR3_STORE_EXITING)
5560                                 return true;
5561                         break;
5562                 case 8:
5563                         if (vmcs12->cpu_based_vm_exec_control &
5564                             CPU_BASED_CR8_STORE_EXITING)
5565                                 return true;
5566                         break;
5567                 }
5568                 break;
5569         case 3: /* lmsw */
5570                 /*
5571                  * lmsw can change bits 1..3 of cr0, and only set bit 0 of
5572                  * cr0. Other attempted changes are ignored, with no exit.
5573                  */
5574                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5575                 if (vmcs12->cr0_guest_host_mask & 0xe &
5576                     (val ^ vmcs12->cr0_read_shadow))
5577                         return true;
5578                 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
5579                     !(vmcs12->cr0_read_shadow & 0x1) &&
5580                     (val & 0x1))
5581                         return true;
5582                 break;
5583         }
5584         return false;
5585 }
5586
5587 static bool nested_vmx_exit_handled_vmcs_access(struct kvm_vcpu *vcpu,
5588         struct vmcs12 *vmcs12, gpa_t bitmap)
5589 {
5590         u32 vmx_instruction_info;
5591         unsigned long field;
5592         u8 b;
5593
5594         if (!nested_cpu_has_shadow_vmcs(vmcs12))
5595                 return true;
5596
5597         /* Decode instruction info and find the field to access */
5598         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5599         field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
5600
5601         /* Out-of-range fields always cause a VM exit from L2 to L1 */
5602         if (field >> 15)
5603                 return true;
5604
5605         if (kvm_vcpu_read_guest(vcpu, bitmap + field/8, &b, 1))
5606                 return true;
5607
5608         return 1 & (b >> (field & 7));
5609 }
5610
5611 static bool nested_vmx_exit_handled_mtf(struct vmcs12 *vmcs12)
5612 {
5613         u32 entry_intr_info = vmcs12->vm_entry_intr_info_field;
5614
5615         if (nested_cpu_has_mtf(vmcs12))
5616                 return true;
5617
5618         /*
5619          * An MTF VM-exit may be injected into the guest by setting the
5620          * interruption-type to 7 (other event) and the vector field to 0. Such
5621          * is the case regardless of the 'monitor trap flag' VM-execution
5622          * control.
5623          */
5624         return entry_intr_info == (INTR_INFO_VALID_MASK
5625                                    | INTR_TYPE_OTHER_EVENT);
5626 }
5627
5628 /*
5629  * Return true if L0 wants to handle an exit from L2 regardless of whether or not
5630  * L1 wants the exit.  Only call this when in is_guest_mode (L2).
5631  */
5632 static bool nested_vmx_l0_wants_exit(struct kvm_vcpu *vcpu, u32 exit_reason)
5633 {
5634         u32 intr_info;
5635
5636         switch (exit_reason) {
5637         case EXIT_REASON_EXCEPTION_NMI:
5638                 intr_info = vmx_get_intr_info(vcpu);
5639                 if (is_nmi(intr_info))
5640                         return true;
5641                 else if (is_page_fault(intr_info))
5642                         return vcpu->arch.apf.host_apf_reason || !enable_ept;
5643                 else if (is_debug(intr_info) &&
5644                          vcpu->guest_debug &
5645                          (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
5646                         return true;
5647                 else if (is_breakpoint(intr_info) &&
5648                          vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
5649                         return true;
5650                 return false;
5651         case EXIT_REASON_EXTERNAL_INTERRUPT:
5652                 return true;
5653         case EXIT_REASON_MCE_DURING_VMENTRY:
5654                 return true;
5655         case EXIT_REASON_EPT_VIOLATION:
5656                 /*
5657                  * L0 always deals with the EPT violation. If nested EPT is
5658                  * used, and the nested mmu code discovers that the address is
5659                  * missing in the guest EPT table (EPT12), the EPT violation
5660                  * will be injected with nested_ept_inject_page_fault()
5661                  */
5662                 return true;
5663         case EXIT_REASON_EPT_MISCONFIG:
5664                 /*
5665                  * L2 never uses directly L1's EPT, but rather L0's own EPT
5666                  * table (shadow on EPT) or a merged EPT table that L0 built
5667                  * (EPT on EPT). So any problems with the structure of the
5668                  * table is L0's fault.
5669                  */
5670                 return true;
5671         case EXIT_REASON_PREEMPTION_TIMER:
5672                 return true;
5673         case EXIT_REASON_PML_FULL:
5674                 /* We emulate PML support to L1. */
5675                 return true;
5676         case EXIT_REASON_VMFUNC:
5677                 /* VM functions are emulated through L2->L0 vmexits. */
5678                 return true;
5679         case EXIT_REASON_ENCLS:
5680                 /* SGX is never exposed to L1 */
5681                 return true;
5682         default:
5683                 break;
5684         }
5685         return false;
5686 }
5687
5688 /*
5689  * Return 1 if L1 wants to intercept an exit from L2.  Only call this when in
5690  * is_guest_mode (L2).
5691  */
5692 static bool nested_vmx_l1_wants_exit(struct kvm_vcpu *vcpu, u32 exit_reason)
5693 {
5694         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5695         u32 intr_info;
5696
5697         switch (exit_reason) {
5698         case EXIT_REASON_EXCEPTION_NMI:
5699                 intr_info = vmx_get_intr_info(vcpu);
5700                 if (is_nmi(intr_info))
5701                         return true;
5702                 else if (is_page_fault(intr_info))
5703                         return true;
5704                 return vmcs12->exception_bitmap &
5705                                 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
5706         case EXIT_REASON_EXTERNAL_INTERRUPT:
5707                 return nested_exit_on_intr(vcpu);
5708         case EXIT_REASON_TRIPLE_FAULT:
5709                 return true;
5710         case EXIT_REASON_INTERRUPT_WINDOW:
5711                 return nested_cpu_has(vmcs12, CPU_BASED_INTR_WINDOW_EXITING);
5712         case EXIT_REASON_NMI_WINDOW:
5713                 return nested_cpu_has(vmcs12, CPU_BASED_NMI_WINDOW_EXITING);
5714         case EXIT_REASON_TASK_SWITCH:
5715                 return true;
5716         case EXIT_REASON_CPUID:
5717                 return true;
5718         case EXIT_REASON_HLT:
5719                 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
5720         case EXIT_REASON_INVD:
5721                 return true;
5722         case EXIT_REASON_INVLPG:
5723                 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
5724         case EXIT_REASON_RDPMC:
5725                 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
5726         case EXIT_REASON_RDRAND:
5727                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDRAND_EXITING);
5728         case EXIT_REASON_RDSEED:
5729                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDSEED_EXITING);
5730         case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
5731                 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
5732         case EXIT_REASON_VMREAD:
5733                 return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
5734                         vmcs12->vmread_bitmap);
5735         case EXIT_REASON_VMWRITE:
5736                 return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
5737                         vmcs12->vmwrite_bitmap);
5738         case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
5739         case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
5740         case EXIT_REASON_VMPTRST: case EXIT_REASON_VMRESUME:
5741         case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
5742         case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
5743                 /*
5744                  * VMX instructions trap unconditionally. This allows L1 to
5745                  * emulate them for its L2 guest, i.e., allows 3-level nesting!
5746                  */
5747                 return true;
5748         case EXIT_REASON_CR_ACCESS:
5749                 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
5750         case EXIT_REASON_DR_ACCESS:
5751                 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
5752         case EXIT_REASON_IO_INSTRUCTION:
5753                 return nested_vmx_exit_handled_io(vcpu, vmcs12);
5754         case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
5755                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
5756         case EXIT_REASON_MSR_READ:
5757         case EXIT_REASON_MSR_WRITE:
5758                 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
5759         case EXIT_REASON_INVALID_STATE:
5760                 return true;
5761         case EXIT_REASON_MWAIT_INSTRUCTION:
5762                 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
5763         case EXIT_REASON_MONITOR_TRAP_FLAG:
5764                 return nested_vmx_exit_handled_mtf(vmcs12);
5765         case EXIT_REASON_MONITOR_INSTRUCTION:
5766                 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
5767         case EXIT_REASON_PAUSE_INSTRUCTION:
5768                 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
5769                         nested_cpu_has2(vmcs12,
5770                                 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
5771         case EXIT_REASON_MCE_DURING_VMENTRY:
5772                 return true;
5773         case EXIT_REASON_TPR_BELOW_THRESHOLD:
5774                 return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
5775         case EXIT_REASON_APIC_ACCESS:
5776         case EXIT_REASON_APIC_WRITE:
5777         case EXIT_REASON_EOI_INDUCED:
5778                 /*
5779                  * The controls for "virtualize APIC accesses," "APIC-
5780                  * register virtualization," and "virtual-interrupt
5781                  * delivery" only come from vmcs12.
5782                  */
5783                 return true;
5784         case EXIT_REASON_INVPCID:
5785                 return
5786                         nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_INVPCID) &&
5787                         nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
5788         case EXIT_REASON_WBINVD:
5789                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
5790         case EXIT_REASON_XSETBV:
5791                 return true;
5792         case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
5793                 /*
5794                  * This should never happen, since it is not possible to
5795                  * set XSS to a non-zero value---neither in L1 nor in L2.
5796                  * If if it were, XSS would have to be checked against
5797                  * the XSS exit bitmap in vmcs12.
5798                  */
5799                 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
5800         case EXIT_REASON_UMWAIT:
5801         case EXIT_REASON_TPAUSE:
5802                 return nested_cpu_has2(vmcs12,
5803                         SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE);
5804         default:
5805                 return true;
5806         }
5807 }
5808
5809 /*
5810  * Conditionally reflect a VM-Exit into L1.  Returns %true if the VM-Exit was
5811  * reflected into L1.
5812  */
5813 bool nested_vmx_reflect_vmexit(struct kvm_vcpu *vcpu)
5814 {
5815         struct vcpu_vmx *vmx = to_vmx(vcpu);
5816         u32 exit_reason = vmx->exit_reason;
5817         u32 exit_intr_info, exit_qual;
5818
5819         WARN_ON_ONCE(vmx->nested.nested_run_pending);
5820
5821         /*
5822          * Late nested VM-Fail shares the same flow as nested VM-Exit since KVM
5823          * has already loaded L2's state.
5824          */
5825         if (unlikely(vmx->fail)) {
5826                 trace_kvm_nested_vmenter_failed(
5827                         "hardware VM-instruction error: ",
5828                         vmcs_read32(VM_INSTRUCTION_ERROR));
5829                 exit_intr_info = 0;
5830                 exit_qual = 0;
5831                 goto reflect_vmexit;
5832         }
5833
5834         exit_intr_info = vmx_get_intr_info(vcpu);
5835         exit_qual = vmx_get_exit_qual(vcpu);
5836
5837         trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason, exit_qual,
5838                                 vmx->idt_vectoring_info, exit_intr_info,
5839                                 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5840                                 KVM_ISA_VMX);
5841
5842         /* If L0 (KVM) wants the exit, it trumps L1's desires. */
5843         if (nested_vmx_l0_wants_exit(vcpu, exit_reason))
5844                 return false;
5845
5846         /* If L1 doesn't want the exit, handle it in L0. */
5847         if (!nested_vmx_l1_wants_exit(vcpu, exit_reason))
5848                 return false;
5849
5850         /*
5851          * vmcs.VM_EXIT_INTR_INFO is only valid for EXCEPTION_NMI exits.  For
5852          * EXTERNAL_INTERRUPT, the value for vmcs12->vm_exit_intr_info would
5853          * need to be synthesized by querying the in-kernel LAPIC, but external
5854          * interrupts are never reflected to L1 so it's a non-issue.
5855          */
5856         if ((exit_intr_info &
5857              (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
5858             (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) {
5859                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5860
5861                 vmcs12->vm_exit_intr_error_code =
5862                         vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5863         }
5864
5865 reflect_vmexit:
5866         nested_vmx_vmexit(vcpu, exit_reason, exit_intr_info, exit_qual);
5867         return true;
5868 }
5869
5870 static int vmx_get_nested_state(struct kvm_vcpu *vcpu,
5871                                 struct kvm_nested_state __user *user_kvm_nested_state,
5872                                 u32 user_data_size)
5873 {
5874         struct vcpu_vmx *vmx;
5875         struct vmcs12 *vmcs12;
5876         struct kvm_nested_state kvm_state = {
5877                 .flags = 0,
5878                 .format = KVM_STATE_NESTED_FORMAT_VMX,
5879                 .size = sizeof(kvm_state),
5880                 .hdr.vmx.vmxon_pa = -1ull,
5881                 .hdr.vmx.vmcs12_pa = -1ull,
5882         };
5883         struct kvm_vmx_nested_state_data __user *user_vmx_nested_state =
5884                 &user_kvm_nested_state->data.vmx[0];
5885
5886         if (!vcpu)
5887                 return kvm_state.size + sizeof(*user_vmx_nested_state);
5888
5889         vmx = to_vmx(vcpu);
5890         vmcs12 = get_vmcs12(vcpu);
5891
5892         if (nested_vmx_allowed(vcpu) &&
5893             (vmx->nested.vmxon || vmx->nested.smm.vmxon)) {
5894                 kvm_state.hdr.vmx.vmxon_pa = vmx->nested.vmxon_ptr;
5895                 kvm_state.hdr.vmx.vmcs12_pa = vmx->nested.current_vmptr;
5896
5897                 if (vmx_has_valid_vmcs12(vcpu)) {
5898                         kvm_state.size += sizeof(user_vmx_nested_state->vmcs12);
5899
5900                         if (vmx->nested.hv_evmcs)
5901                                 kvm_state.flags |= KVM_STATE_NESTED_EVMCS;
5902
5903                         if (is_guest_mode(vcpu) &&
5904                             nested_cpu_has_shadow_vmcs(vmcs12) &&
5905                             vmcs12->vmcs_link_pointer != -1ull)
5906                                 kvm_state.size += sizeof(user_vmx_nested_state->shadow_vmcs12);
5907                 }
5908
5909                 if (vmx->nested.smm.vmxon)
5910                         kvm_state.hdr.vmx.smm.flags |= KVM_STATE_NESTED_SMM_VMXON;
5911
5912                 if (vmx->nested.smm.guest_mode)
5913                         kvm_state.hdr.vmx.smm.flags |= KVM_STATE_NESTED_SMM_GUEST_MODE;
5914
5915                 if (is_guest_mode(vcpu)) {
5916                         kvm_state.flags |= KVM_STATE_NESTED_GUEST_MODE;
5917
5918                         if (vmx->nested.nested_run_pending)
5919                                 kvm_state.flags |= KVM_STATE_NESTED_RUN_PENDING;
5920
5921                         if (vmx->nested.mtf_pending)
5922                                 kvm_state.flags |= KVM_STATE_NESTED_MTF_PENDING;
5923                 }
5924         }
5925
5926         if (user_data_size < kvm_state.size)
5927                 goto out;
5928
5929         if (copy_to_user(user_kvm_nested_state, &kvm_state, sizeof(kvm_state)))
5930                 return -EFAULT;
5931
5932         if (!vmx_has_valid_vmcs12(vcpu))
5933                 goto out;
5934
5935         /*
5936          * When running L2, the authoritative vmcs12 state is in the
5937          * vmcs02. When running L1, the authoritative vmcs12 state is
5938          * in the shadow or enlightened vmcs linked to vmcs01, unless
5939          * need_vmcs12_to_shadow_sync is set, in which case, the authoritative
5940          * vmcs12 state is in the vmcs12 already.
5941          */
5942         if (is_guest_mode(vcpu)) {
5943                 sync_vmcs02_to_vmcs12(vcpu, vmcs12);
5944                 sync_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
5945         } else if (!vmx->nested.need_vmcs12_to_shadow_sync) {
5946                 if (vmx->nested.hv_evmcs)
5947                         copy_enlightened_to_vmcs12(vmx);
5948                 else if (enable_shadow_vmcs)
5949                         copy_shadow_to_vmcs12(vmx);
5950         }
5951
5952         BUILD_BUG_ON(sizeof(user_vmx_nested_state->vmcs12) < VMCS12_SIZE);
5953         BUILD_BUG_ON(sizeof(user_vmx_nested_state->shadow_vmcs12) < VMCS12_SIZE);
5954
5955         /*
5956          * Copy over the full allocated size of vmcs12 rather than just the size
5957          * of the struct.
5958          */
5959         if (copy_to_user(user_vmx_nested_state->vmcs12, vmcs12, VMCS12_SIZE))
5960                 return -EFAULT;
5961
5962         if (nested_cpu_has_shadow_vmcs(vmcs12) &&
5963             vmcs12->vmcs_link_pointer != -1ull) {
5964                 if (copy_to_user(user_vmx_nested_state->shadow_vmcs12,
5965                                  get_shadow_vmcs12(vcpu), VMCS12_SIZE))
5966                         return -EFAULT;
5967         }
5968
5969 out:
5970         return kvm_state.size;
5971 }
5972
5973 /*
5974  * Forcibly leave nested mode in order to be able to reset the VCPU later on.
5975  */
5976 void vmx_leave_nested(struct kvm_vcpu *vcpu)
5977 {
5978         if (is_guest_mode(vcpu)) {
5979                 to_vmx(vcpu)->nested.nested_run_pending = 0;
5980                 nested_vmx_vmexit(vcpu, -1, 0, 0);
5981         }
5982         free_nested(vcpu);
5983 }
5984
5985 static int vmx_set_nested_state(struct kvm_vcpu *vcpu,
5986                                 struct kvm_nested_state __user *user_kvm_nested_state,
5987                                 struct kvm_nested_state *kvm_state)
5988 {
5989         struct vcpu_vmx *vmx = to_vmx(vcpu);
5990         struct vmcs12 *vmcs12;
5991         u32 exit_qual;
5992         struct kvm_vmx_nested_state_data __user *user_vmx_nested_state =
5993                 &user_kvm_nested_state->data.vmx[0];
5994         int ret;
5995
5996         if (kvm_state->format != KVM_STATE_NESTED_FORMAT_VMX)
5997                 return -EINVAL;
5998
5999         if (kvm_state->hdr.vmx.vmxon_pa == -1ull) {
6000                 if (kvm_state->hdr.vmx.smm.flags)
6001                         return -EINVAL;
6002
6003                 if (kvm_state->hdr.vmx.vmcs12_pa != -1ull)
6004                         return -EINVAL;
6005
6006                 /*
6007                  * KVM_STATE_NESTED_EVMCS used to signal that KVM should
6008                  * enable eVMCS capability on vCPU. However, since then
6009                  * code was changed such that flag signals vmcs12 should
6010                  * be copied into eVMCS in guest memory.
6011                  *
6012                  * To preserve backwards compatability, allow user
6013                  * to set this flag even when there is no VMXON region.
6014                  */
6015                 if (kvm_state->flags & ~KVM_STATE_NESTED_EVMCS)
6016                         return -EINVAL;
6017         } else {
6018                 if (!nested_vmx_allowed(vcpu))
6019                         return -EINVAL;
6020
6021                 if (!page_address_valid(vcpu, kvm_state->hdr.vmx.vmxon_pa))
6022                         return -EINVAL;
6023         }
6024
6025         if ((kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
6026             (kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
6027                 return -EINVAL;
6028
6029         if (kvm_state->hdr.vmx.smm.flags &
6030             ~(KVM_STATE_NESTED_SMM_GUEST_MODE | KVM_STATE_NESTED_SMM_VMXON))
6031                 return -EINVAL;
6032
6033         /*
6034          * SMM temporarily disables VMX, so we cannot be in guest mode,
6035          * nor can VMLAUNCH/VMRESUME be pending.  Outside SMM, SMM flags
6036          * must be zero.
6037          */
6038         if (is_smm(vcpu) ?
6039                 (kvm_state->flags &
6040                  (KVM_STATE_NESTED_GUEST_MODE | KVM_STATE_NESTED_RUN_PENDING))
6041                 : kvm_state->hdr.vmx.smm.flags)
6042                 return -EINVAL;
6043
6044         if ((kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
6045             !(kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON))
6046                 return -EINVAL;
6047
6048         if ((kvm_state->flags & KVM_STATE_NESTED_EVMCS) &&
6049                 (!nested_vmx_allowed(vcpu) || !vmx->nested.enlightened_vmcs_enabled))
6050                         return -EINVAL;
6051
6052         vmx_leave_nested(vcpu);
6053
6054         if (kvm_state->hdr.vmx.vmxon_pa == -1ull)
6055                 return 0;
6056
6057         vmx->nested.vmxon_ptr = kvm_state->hdr.vmx.vmxon_pa;
6058         ret = enter_vmx_operation(vcpu);
6059         if (ret)
6060                 return ret;
6061
6062         /* Empty 'VMXON' state is permitted */
6063         if (kvm_state->size < sizeof(*kvm_state) + sizeof(*vmcs12))
6064                 return 0;
6065
6066         if (kvm_state->hdr.vmx.vmcs12_pa != -1ull) {
6067                 if (kvm_state->hdr.vmx.vmcs12_pa == kvm_state->hdr.vmx.vmxon_pa ||
6068                     !page_address_valid(vcpu, kvm_state->hdr.vmx.vmcs12_pa))
6069                         return -EINVAL;
6070
6071                 set_current_vmptr(vmx, kvm_state->hdr.vmx.vmcs12_pa);
6072         } else if (kvm_state->flags & KVM_STATE_NESTED_EVMCS) {
6073                 /*
6074                  * nested_vmx_handle_enlightened_vmptrld() cannot be called
6075                  * directly from here as HV_X64_MSR_VP_ASSIST_PAGE may not be
6076                  * restored yet. EVMCS will be mapped from
6077                  * nested_get_vmcs12_pages().
6078                  */
6079                 kvm_make_request(KVM_REQ_GET_VMCS12_PAGES, vcpu);
6080         } else {
6081                 return -EINVAL;
6082         }
6083
6084         if (kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON) {
6085                 vmx->nested.smm.vmxon = true;
6086                 vmx->nested.vmxon = false;
6087
6088                 if (kvm_state->hdr.vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE)
6089                         vmx->nested.smm.guest_mode = true;
6090         }
6091
6092         vmcs12 = get_vmcs12(vcpu);
6093         if (copy_from_user(vmcs12, user_vmx_nested_state->vmcs12, sizeof(*vmcs12)))
6094                 return -EFAULT;
6095
6096         if (vmcs12->hdr.revision_id != VMCS12_REVISION)
6097                 return -EINVAL;
6098
6099         if (!(kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
6100                 return 0;
6101
6102         vmx->nested.nested_run_pending =
6103                 !!(kvm_state->flags & KVM_STATE_NESTED_RUN_PENDING);
6104
6105         vmx->nested.mtf_pending =
6106                 !!(kvm_state->flags & KVM_STATE_NESTED_MTF_PENDING);
6107
6108         ret = -EINVAL;
6109         if (nested_cpu_has_shadow_vmcs(vmcs12) &&
6110             vmcs12->vmcs_link_pointer != -1ull) {
6111                 struct vmcs12 *shadow_vmcs12 = get_shadow_vmcs12(vcpu);
6112
6113                 if (kvm_state->size <
6114                     sizeof(*kvm_state) +
6115                     sizeof(user_vmx_nested_state->vmcs12) + sizeof(*shadow_vmcs12))
6116                         goto error_guest_mode;
6117
6118                 if (copy_from_user(shadow_vmcs12,
6119                                    user_vmx_nested_state->shadow_vmcs12,
6120                                    sizeof(*shadow_vmcs12))) {
6121                         ret = -EFAULT;
6122                         goto error_guest_mode;
6123                 }
6124
6125                 if (shadow_vmcs12->hdr.revision_id != VMCS12_REVISION ||
6126                     !shadow_vmcs12->hdr.shadow_vmcs)
6127                         goto error_guest_mode;
6128         }
6129
6130         if (nested_vmx_check_controls(vcpu, vmcs12) ||
6131             nested_vmx_check_host_state(vcpu, vmcs12) ||
6132             nested_vmx_check_guest_state(vcpu, vmcs12, &exit_qual))
6133                 goto error_guest_mode;
6134
6135         vmx->nested.dirty_vmcs12 = true;
6136         ret = nested_vmx_enter_non_root_mode(vcpu, false);
6137         if (ret)
6138                 goto error_guest_mode;
6139
6140         return 0;
6141
6142 error_guest_mode:
6143         vmx->nested.nested_run_pending = 0;
6144         return ret;
6145 }
6146
6147 void nested_vmx_set_vmcs_shadowing_bitmap(void)
6148 {
6149         if (enable_shadow_vmcs) {
6150                 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
6151                 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
6152         }
6153 }
6154
6155 /*
6156  * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
6157  * returned for the various VMX controls MSRs when nested VMX is enabled.
6158  * The same values should also be used to verify that vmcs12 control fields are
6159  * valid during nested entry from L1 to L2.
6160  * Each of these control msrs has a low and high 32-bit half: A low bit is on
6161  * if the corresponding bit in the (32-bit) control field *must* be on, and a
6162  * bit in the high half is on if the corresponding bit in the control field
6163  * may be on. See also vmx_control_verify().
6164  */
6165 void nested_vmx_setup_ctls_msrs(struct nested_vmx_msrs *msrs, u32 ept_caps)
6166 {
6167         /*
6168          * Note that as a general rule, the high half of the MSRs (bits in
6169          * the control fields which may be 1) should be initialized by the
6170          * intersection of the underlying hardware's MSR (i.e., features which
6171          * can be supported) and the list of features we want to expose -
6172          * because they are known to be properly supported in our code.
6173          * Also, usually, the low half of the MSRs (bits which must be 1) can
6174          * be set to 0, meaning that L1 may turn off any of these bits. The
6175          * reason is that if one of these bits is necessary, it will appear
6176          * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
6177          * fields of vmcs01 and vmcs02, will turn these bits off - and
6178          * nested_vmx_l1_wants_exit() will not pass related exits to L1.
6179          * These rules have exceptions below.
6180          */
6181
6182         /* pin-based controls */
6183         rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
6184                 msrs->pinbased_ctls_low,
6185                 msrs->pinbased_ctls_high);
6186         msrs->pinbased_ctls_low |=
6187                 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
6188         msrs->pinbased_ctls_high &=
6189                 PIN_BASED_EXT_INTR_MASK |
6190                 PIN_BASED_NMI_EXITING |
6191                 PIN_BASED_VIRTUAL_NMIS |
6192                 (enable_apicv ? PIN_BASED_POSTED_INTR : 0);
6193         msrs->pinbased_ctls_high |=
6194                 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
6195                 PIN_BASED_VMX_PREEMPTION_TIMER;
6196
6197         /* exit controls */
6198         rdmsr(MSR_IA32_VMX_EXIT_CTLS,
6199                 msrs->exit_ctls_low,
6200                 msrs->exit_ctls_high);
6201         msrs->exit_ctls_low =
6202                 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
6203
6204         msrs->exit_ctls_high &=
6205 #ifdef CONFIG_X86_64
6206                 VM_EXIT_HOST_ADDR_SPACE_SIZE |
6207 #endif
6208                 VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
6209         msrs->exit_ctls_high |=
6210                 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
6211                 VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
6212                 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
6213
6214         /* We support free control of debug control saving. */
6215         msrs->exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
6216
6217         /* entry controls */
6218         rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
6219                 msrs->entry_ctls_low,
6220                 msrs->entry_ctls_high);
6221         msrs->entry_ctls_low =
6222                 VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
6223         msrs->entry_ctls_high &=
6224 #ifdef CONFIG_X86_64
6225                 VM_ENTRY_IA32E_MODE |
6226 #endif
6227                 VM_ENTRY_LOAD_IA32_PAT;
6228         msrs->entry_ctls_high |=
6229                 (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
6230
6231         /* We support free control of debug control loading. */
6232         msrs->entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
6233
6234         /* cpu-based controls */
6235         rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
6236                 msrs->procbased_ctls_low,
6237                 msrs->procbased_ctls_high);
6238         msrs->procbased_ctls_low =
6239                 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
6240         msrs->procbased_ctls_high &=
6241                 CPU_BASED_INTR_WINDOW_EXITING |
6242                 CPU_BASED_NMI_WINDOW_EXITING | CPU_BASED_USE_TSC_OFFSETTING |
6243                 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
6244                 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
6245                 CPU_BASED_CR3_STORE_EXITING |
6246 #ifdef CONFIG_X86_64
6247                 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
6248 #endif
6249                 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
6250                 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
6251                 CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
6252                 CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
6253                 CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
6254         /*
6255          * We can allow some features even when not supported by the
6256          * hardware. For example, L1 can specify an MSR bitmap - and we
6257          * can use it to avoid exits to L1 - even when L0 runs L2
6258          * without MSR bitmaps.
6259          */
6260         msrs->procbased_ctls_high |=
6261                 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
6262                 CPU_BASED_USE_MSR_BITMAPS;
6263
6264         /* We support free control of CR3 access interception. */
6265         msrs->procbased_ctls_low &=
6266                 ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
6267
6268         /*
6269          * secondary cpu-based controls.  Do not include those that
6270          * depend on CPUID bits, they are added later by vmx_cpuid_update.
6271          */
6272         if (msrs->procbased_ctls_high & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)
6273                 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
6274                       msrs->secondary_ctls_low,
6275                       msrs->secondary_ctls_high);
6276
6277         msrs->secondary_ctls_low = 0;
6278         msrs->secondary_ctls_high &=
6279                 SECONDARY_EXEC_DESC |
6280                 SECONDARY_EXEC_RDTSCP |
6281                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
6282                 SECONDARY_EXEC_WBINVD_EXITING |
6283                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
6284                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
6285                 SECONDARY_EXEC_RDRAND_EXITING |
6286                 SECONDARY_EXEC_ENABLE_INVPCID |
6287                 SECONDARY_EXEC_RDSEED_EXITING |
6288                 SECONDARY_EXEC_XSAVES;
6289
6290         /*
6291          * We can emulate "VMCS shadowing," even if the hardware
6292          * doesn't support it.
6293          */
6294         msrs->secondary_ctls_high |=
6295                 SECONDARY_EXEC_SHADOW_VMCS;
6296
6297         if (enable_ept) {
6298                 /* nested EPT: emulate EPT also to L1 */
6299                 msrs->secondary_ctls_high |=
6300                         SECONDARY_EXEC_ENABLE_EPT;
6301                 msrs->ept_caps =
6302                         VMX_EPT_PAGE_WALK_4_BIT |
6303                         VMX_EPT_PAGE_WALK_5_BIT |
6304                         VMX_EPTP_WB_BIT |
6305                         VMX_EPT_INVEPT_BIT |
6306                         VMX_EPT_EXECUTE_ONLY_BIT;
6307
6308                 msrs->ept_caps &= ept_caps;
6309                 msrs->ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
6310                         VMX_EPT_EXTENT_CONTEXT_BIT | VMX_EPT_2MB_PAGE_BIT |
6311                         VMX_EPT_1GB_PAGE_BIT;
6312                 if (enable_ept_ad_bits) {
6313                         msrs->secondary_ctls_high |=
6314                                 SECONDARY_EXEC_ENABLE_PML;
6315                         msrs->ept_caps |= VMX_EPT_AD_BIT;
6316                 }
6317         }
6318
6319         if (cpu_has_vmx_vmfunc()) {
6320                 msrs->secondary_ctls_high |=
6321                         SECONDARY_EXEC_ENABLE_VMFUNC;
6322                 /*
6323                  * Advertise EPTP switching unconditionally
6324                  * since we emulate it
6325                  */
6326                 if (enable_ept)
6327                         msrs->vmfunc_controls =
6328                                 VMX_VMFUNC_EPTP_SWITCHING;
6329         }
6330
6331         /*
6332          * Old versions of KVM use the single-context version without
6333          * checking for support, so declare that it is supported even
6334          * though it is treated as global context.  The alternative is
6335          * not failing the single-context invvpid, and it is worse.
6336          */
6337         if (enable_vpid) {
6338                 msrs->secondary_ctls_high |=
6339                         SECONDARY_EXEC_ENABLE_VPID;
6340                 msrs->vpid_caps = VMX_VPID_INVVPID_BIT |
6341                         VMX_VPID_EXTENT_SUPPORTED_MASK;
6342         }
6343
6344         if (enable_unrestricted_guest)
6345                 msrs->secondary_ctls_high |=
6346                         SECONDARY_EXEC_UNRESTRICTED_GUEST;
6347
6348         if (flexpriority_enabled)
6349                 msrs->secondary_ctls_high |=
6350                         SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6351
6352         /* miscellaneous data */
6353         rdmsr(MSR_IA32_VMX_MISC,
6354                 msrs->misc_low,
6355                 msrs->misc_high);
6356         msrs->misc_low &= VMX_MISC_SAVE_EFER_LMA;
6357         msrs->misc_low |=
6358                 MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS |
6359                 VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
6360                 VMX_MISC_ACTIVITY_HLT;
6361         msrs->misc_high = 0;
6362
6363         /*
6364          * This MSR reports some information about VMX support. We
6365          * should return information about the VMX we emulate for the
6366          * guest, and the VMCS structure we give it - not about the
6367          * VMX support of the underlying hardware.
6368          */
6369         msrs->basic =
6370                 VMCS12_REVISION |
6371                 VMX_BASIC_TRUE_CTLS |
6372                 ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
6373                 (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
6374
6375         if (cpu_has_vmx_basic_inout())
6376                 msrs->basic |= VMX_BASIC_INOUT;
6377
6378         /*
6379          * These MSRs specify bits which the guest must keep fixed on
6380          * while L1 is in VMXON mode (in L1's root mode, or running an L2).
6381          * We picked the standard core2 setting.
6382          */
6383 #define VMXON_CR0_ALWAYSON     (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
6384 #define VMXON_CR4_ALWAYSON     X86_CR4_VMXE
6385         msrs->cr0_fixed0 = VMXON_CR0_ALWAYSON;
6386         msrs->cr4_fixed0 = VMXON_CR4_ALWAYSON;
6387
6388         /* These MSRs specify bits which the guest must keep fixed off. */
6389         rdmsrl(MSR_IA32_VMX_CR0_FIXED1, msrs->cr0_fixed1);
6390         rdmsrl(MSR_IA32_VMX_CR4_FIXED1, msrs->cr4_fixed1);
6391
6392         /* highest index: VMX_PREEMPTION_TIMER_VALUE */
6393         msrs->vmcs_enum = VMCS12_MAX_FIELD_INDEX << 1;
6394 }
6395
6396 void nested_vmx_hardware_unsetup(void)
6397 {
6398         int i;
6399
6400         if (enable_shadow_vmcs) {
6401                 for (i = 0; i < VMX_BITMAP_NR; i++)
6402                         free_page((unsigned long)vmx_bitmap[i]);
6403         }
6404 }
6405
6406 __init int nested_vmx_hardware_setup(struct kvm_x86_ops *ops,
6407                                      int (*exit_handlers[])(struct kvm_vcpu *))
6408 {
6409         int i;
6410
6411         if (!cpu_has_vmx_shadow_vmcs())
6412                 enable_shadow_vmcs = 0;
6413         if (enable_shadow_vmcs) {
6414                 for (i = 0; i < VMX_BITMAP_NR; i++) {
6415                         /*
6416                          * The vmx_bitmap is not tied to a VM and so should
6417                          * not be charged to a memcg.
6418                          */
6419                         vmx_bitmap[i] = (unsigned long *)
6420                                 __get_free_page(GFP_KERNEL);
6421                         if (!vmx_bitmap[i]) {
6422                                 nested_vmx_hardware_unsetup();
6423                                 return -ENOMEM;
6424                         }
6425                 }
6426
6427                 init_vmcs_shadow_fields();
6428         }
6429
6430         exit_handlers[EXIT_REASON_VMCLEAR]      = handle_vmclear;
6431         exit_handlers[EXIT_REASON_VMLAUNCH]     = handle_vmlaunch;
6432         exit_handlers[EXIT_REASON_VMPTRLD]      = handle_vmptrld;
6433         exit_handlers[EXIT_REASON_VMPTRST]      = handle_vmptrst;
6434         exit_handlers[EXIT_REASON_VMREAD]       = handle_vmread;
6435         exit_handlers[EXIT_REASON_VMRESUME]     = handle_vmresume;
6436         exit_handlers[EXIT_REASON_VMWRITE]      = handle_vmwrite;
6437         exit_handlers[EXIT_REASON_VMOFF]        = handle_vmoff;
6438         exit_handlers[EXIT_REASON_VMON]         = handle_vmon;
6439         exit_handlers[EXIT_REASON_INVEPT]       = handle_invept;
6440         exit_handlers[EXIT_REASON_INVVPID]      = handle_invvpid;
6441         exit_handlers[EXIT_REASON_VMFUNC]       = handle_vmfunc;
6442
6443         return 0;
6444 }
6445
6446 struct kvm_x86_nested_ops vmx_nested_ops = {
6447         .check_events = vmx_check_nested_events,
6448         .get_state = vmx_get_nested_state,
6449         .set_state = vmx_set_nested_state,
6450         .get_vmcs12_pages = nested_get_vmcs12_pages,
6451         .enable_evmcs = nested_enable_evmcs,
6452         .get_evmcs_version = nested_get_evmcs_version,
6453 };