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