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