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