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