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