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