GNU Linux-libre 5.15.137-gnu
[releases.git] / arch / x86 / kvm / svm / nested.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine driver for Linux
4  *
5  * AMD SVM support
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
9  *
10  * Authors:
11  *   Yaniv Kamay  <yaniv@qumranet.com>
12  *   Avi Kivity   <avi@qumranet.com>
13  */
14
15 #define pr_fmt(fmt) "SVM: " fmt
16
17 #include <linux/kvm_types.h>
18 #include <linux/kvm_host.h>
19 #include <linux/kernel.h>
20
21 #include <asm/msr-index.h>
22 #include <asm/debugreg.h>
23
24 #include "kvm_emulate.h"
25 #include "trace.h"
26 #include "mmu.h"
27 #include "x86.h"
28 #include "cpuid.h"
29 #include "lapic.h"
30 #include "svm.h"
31
32 #define CC KVM_NESTED_VMENTER_CONSISTENCY_CHECK
33
34 static void nested_svm_inject_npf_exit(struct kvm_vcpu *vcpu,
35                                        struct x86_exception *fault)
36 {
37         struct vcpu_svm *svm = to_svm(vcpu);
38
39         if (svm->vmcb->control.exit_code != SVM_EXIT_NPF) {
40                 /*
41                  * TODO: track the cause of the nested page fault, and
42                  * correctly fill in the high bits of exit_info_1.
43                  */
44                 svm->vmcb->control.exit_code = SVM_EXIT_NPF;
45                 svm->vmcb->control.exit_code_hi = 0;
46                 svm->vmcb->control.exit_info_1 = (1ULL << 32);
47                 svm->vmcb->control.exit_info_2 = fault->address;
48         }
49
50         svm->vmcb->control.exit_info_1 &= ~0xffffffffULL;
51         svm->vmcb->control.exit_info_1 |= fault->error_code;
52
53         nested_svm_vmexit(svm);
54 }
55
56 static void svm_inject_page_fault_nested(struct kvm_vcpu *vcpu, struct x86_exception *fault)
57 {
58        struct vcpu_svm *svm = to_svm(vcpu);
59        WARN_ON(!is_guest_mode(vcpu));
60
61        if (vmcb_is_intercept(&svm->nested.ctl, INTERCEPT_EXCEPTION_OFFSET + PF_VECTOR) &&
62            !svm->nested.nested_run_pending) {
63                svm->vmcb->control.exit_code = SVM_EXIT_EXCP_BASE + PF_VECTOR;
64                svm->vmcb->control.exit_code_hi = 0;
65                svm->vmcb->control.exit_info_1 = fault->error_code;
66                svm->vmcb->control.exit_info_2 = fault->address;
67                nested_svm_vmexit(svm);
68        } else {
69                kvm_inject_page_fault(vcpu, fault);
70        }
71 }
72
73 static u64 nested_svm_get_tdp_pdptr(struct kvm_vcpu *vcpu, int index)
74 {
75         struct vcpu_svm *svm = to_svm(vcpu);
76         u64 cr3 = svm->nested.ctl.nested_cr3;
77         u64 pdpte;
78         int ret;
79
80         ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(cr3), &pdpte,
81                                        offset_in_page(cr3) + index * 8, 8);
82         if (ret)
83                 return 0;
84         return pdpte;
85 }
86
87 static unsigned long nested_svm_get_tdp_cr3(struct kvm_vcpu *vcpu)
88 {
89         struct vcpu_svm *svm = to_svm(vcpu);
90
91         return svm->nested.ctl.nested_cr3;
92 }
93
94 static void nested_svm_init_mmu_context(struct kvm_vcpu *vcpu)
95 {
96         struct vcpu_svm *svm = to_svm(vcpu);
97
98         WARN_ON(mmu_is_nested(vcpu));
99
100         vcpu->arch.mmu = &vcpu->arch.guest_mmu;
101
102         /*
103          * The NPT format depends on L1's CR4 and EFER, which is in vmcb01.  Note,
104          * when called via KVM_SET_NESTED_STATE, that state may _not_ match current
105          * vCPU state.  CR0.WP is explicitly ignored, while CR0.PG is required.
106          */
107         kvm_init_shadow_npt_mmu(vcpu, X86_CR0_PG, svm->vmcb01.ptr->save.cr4,
108                                 svm->vmcb01.ptr->save.efer,
109                                 svm->nested.ctl.nested_cr3);
110         vcpu->arch.mmu->get_guest_pgd     = nested_svm_get_tdp_cr3;
111         vcpu->arch.mmu->get_pdptr         = nested_svm_get_tdp_pdptr;
112         vcpu->arch.mmu->inject_page_fault = nested_svm_inject_npf_exit;
113         vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
114 }
115
116 static void nested_svm_uninit_mmu_context(struct kvm_vcpu *vcpu)
117 {
118         vcpu->arch.mmu = &vcpu->arch.root_mmu;
119         vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
120 }
121
122 void recalc_intercepts(struct vcpu_svm *svm)
123 {
124         struct vmcb_control_area *c, *h, *g;
125         unsigned int i;
126
127         vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
128
129         if (!is_guest_mode(&svm->vcpu))
130                 return;
131
132         c = &svm->vmcb->control;
133         h = &svm->vmcb01.ptr->control;
134         g = &svm->nested.ctl;
135
136         for (i = 0; i < MAX_INTERCEPT; i++)
137                 c->intercepts[i] = h->intercepts[i];
138
139         if (g->int_ctl & V_INTR_MASKING_MASK) {
140                 /* We only want the cr8 intercept bits of L1 */
141                 vmcb_clr_intercept(c, INTERCEPT_CR8_READ);
142                 vmcb_clr_intercept(c, INTERCEPT_CR8_WRITE);
143
144                 /*
145                  * Once running L2 with HF_VINTR_MASK, EFLAGS.IF does not
146                  * affect any interrupt we may want to inject; therefore,
147                  * interrupt window vmexits are irrelevant to L0.
148                  */
149                 vmcb_clr_intercept(c, INTERCEPT_VINTR);
150         }
151
152         /* We don't want to see VMMCALLs from a nested guest */
153         vmcb_clr_intercept(c, INTERCEPT_VMMCALL);
154
155         for (i = 0; i < MAX_INTERCEPT; i++)
156                 c->intercepts[i] |= g->intercepts[i];
157
158         /* If SMI is not intercepted, ignore guest SMI intercept as well  */
159         if (!intercept_smi)
160                 vmcb_clr_intercept(c, INTERCEPT_SMI);
161
162         vmcb_set_intercept(c, INTERCEPT_VMLOAD);
163         vmcb_set_intercept(c, INTERCEPT_VMSAVE);
164 }
165
166 static void copy_vmcb_control_area(struct vmcb_control_area *dst,
167                                    struct vmcb_control_area *from)
168 {
169         unsigned int i;
170
171         for (i = 0; i < MAX_INTERCEPT; i++)
172                 dst->intercepts[i] = from->intercepts[i];
173
174         dst->iopm_base_pa         = from->iopm_base_pa;
175         dst->msrpm_base_pa        = from->msrpm_base_pa;
176         dst->tsc_offset           = from->tsc_offset;
177         /* asid not copied, it is handled manually for svm->vmcb.  */
178         dst->tlb_ctl              = from->tlb_ctl;
179         dst->int_ctl              = from->int_ctl;
180         dst->int_vector           = from->int_vector;
181         dst->int_state            = from->int_state;
182         dst->exit_code            = from->exit_code;
183         dst->exit_code_hi         = from->exit_code_hi;
184         dst->exit_info_1          = from->exit_info_1;
185         dst->exit_info_2          = from->exit_info_2;
186         dst->exit_int_info        = from->exit_int_info;
187         dst->exit_int_info_err    = from->exit_int_info_err;
188         dst->nested_ctl           = from->nested_ctl;
189         dst->event_inj            = from->event_inj;
190         dst->event_inj_err        = from->event_inj_err;
191         dst->nested_cr3           = from->nested_cr3;
192         dst->virt_ext              = from->virt_ext;
193         dst->pause_filter_count   = from->pause_filter_count;
194         dst->pause_filter_thresh  = from->pause_filter_thresh;
195 }
196
197 static bool nested_svm_vmrun_msrpm(struct vcpu_svm *svm)
198 {
199         /*
200          * This function merges the msr permission bitmaps of kvm and the
201          * nested vmcb. It is optimized in that it only merges the parts where
202          * the kvm msr permission bitmap may contain zero bits
203          */
204         int i;
205
206         if (!(vmcb_is_intercept(&svm->nested.ctl, INTERCEPT_MSR_PROT)))
207                 return true;
208
209         for (i = 0; i < MSRPM_OFFSETS; i++) {
210                 u32 value, p;
211                 u64 offset;
212
213                 if (msrpm_offsets[i] == 0xffffffff)
214                         break;
215
216                 p      = msrpm_offsets[i];
217                 offset = svm->nested.ctl.msrpm_base_pa + (p * 4);
218
219                 if (kvm_vcpu_read_guest(&svm->vcpu, offset, &value, 4))
220                         return false;
221
222                 svm->nested.msrpm[p] = svm->msrpm[p] | value;
223         }
224
225         svm->vmcb->control.msrpm_base_pa = __sme_set(__pa(svm->nested.msrpm));
226
227         return true;
228 }
229
230 /*
231  * Bits 11:0 of bitmap address are ignored by hardware
232  */
233 static bool nested_svm_check_bitmap_pa(struct kvm_vcpu *vcpu, u64 pa, u32 size)
234 {
235         u64 addr = PAGE_ALIGN(pa);
236
237         return kvm_vcpu_is_legal_gpa(vcpu, addr) &&
238             kvm_vcpu_is_legal_gpa(vcpu, addr + size - 1);
239 }
240
241 static bool nested_vmcb_check_controls(struct kvm_vcpu *vcpu,
242                                        struct vmcb_control_area *control)
243 {
244         if (CC(!vmcb_is_intercept(control, INTERCEPT_VMRUN)))
245                 return false;
246
247         if (CC(control->asid == 0))
248                 return false;
249
250         if (CC((control->nested_ctl & SVM_NESTED_CTL_NP_ENABLE) && !npt_enabled))
251                 return false;
252
253         if (CC(!nested_svm_check_bitmap_pa(vcpu, control->msrpm_base_pa,
254                                            MSRPM_SIZE)))
255                 return false;
256         if (CC(!nested_svm_check_bitmap_pa(vcpu, control->iopm_base_pa,
257                                            IOPM_SIZE)))
258                 return false;
259
260         return true;
261 }
262
263 static bool nested_vmcb_check_cr3_cr4(struct kvm_vcpu *vcpu,
264                                       struct vmcb_save_area *save)
265 {
266         /*
267          * These checks are also performed by KVM_SET_SREGS,
268          * except that EFER.LMA is not checked by SVM against
269          * CR0.PG && EFER.LME.
270          */
271         if ((save->efer & EFER_LME) && (save->cr0 & X86_CR0_PG)) {
272                 if (CC(!(save->cr4 & X86_CR4_PAE)) ||
273                     CC(!(save->cr0 & X86_CR0_PE)) ||
274                     CC(kvm_vcpu_is_illegal_gpa(vcpu, save->cr3)))
275                         return false;
276         }
277
278         /* Note, SVM doesn't have any additional restrictions on CR4. */
279         if (CC(!__kvm_is_valid_cr4(vcpu, save->cr4)))
280                 return false;
281
282         return true;
283 }
284
285 /* Common checks that apply to both L1 and L2 state.  */
286 static bool nested_vmcb_valid_sregs(struct kvm_vcpu *vcpu,
287                                     struct vmcb_save_area *save)
288 {
289         /*
290          * FIXME: these should be done after copying the fields,
291          * to avoid TOC/TOU races.  For these save area checks
292          * the possible damage is limited since kvm_set_cr0 and
293          * kvm_set_cr4 handle failure; EFER_SVME is an exception
294          * so it is force-set later in nested_prepare_vmcb_save.
295          */
296         if (CC(!(save->efer & EFER_SVME)))
297                 return false;
298
299         if (CC((save->cr0 & X86_CR0_CD) == 0 && (save->cr0 & X86_CR0_NW)) ||
300             CC(save->cr0 & ~0xffffffffULL))
301                 return false;
302
303         if (CC(!kvm_dr6_valid(save->dr6)) || CC(!kvm_dr7_valid(save->dr7)))
304                 return false;
305
306         if (!nested_vmcb_check_cr3_cr4(vcpu, save))
307                 return false;
308
309         if (CC(!kvm_valid_efer(vcpu, save->efer)))
310                 return false;
311
312         return true;
313 }
314
315 void nested_load_control_from_vmcb12(struct vcpu_svm *svm,
316                                      struct vmcb_control_area *control)
317 {
318         copy_vmcb_control_area(&svm->nested.ctl, control);
319
320         /* Copy it here because nested_svm_check_controls will check it.  */
321         svm->nested.ctl.asid           = control->asid;
322         svm->nested.ctl.msrpm_base_pa &= ~0x0fffULL;
323         svm->nested.ctl.iopm_base_pa  &= ~0x0fffULL;
324 }
325
326 /*
327  * Synchronize fields that are written by the processor, so that
328  * they can be copied back into the vmcb12.
329  */
330 void nested_sync_control_from_vmcb02(struct vcpu_svm *svm)
331 {
332         u32 mask;
333         svm->nested.ctl.event_inj      = svm->vmcb->control.event_inj;
334         svm->nested.ctl.event_inj_err  = svm->vmcb->control.event_inj_err;
335
336         /* Only a few fields of int_ctl are written by the processor.  */
337         mask = V_IRQ_MASK | V_TPR_MASK;
338         if (!(svm->nested.ctl.int_ctl & V_INTR_MASKING_MASK) &&
339             svm_is_intercept(svm, INTERCEPT_VINTR)) {
340                 /*
341                  * In order to request an interrupt window, L0 is usurping
342                  * svm->vmcb->control.int_ctl and possibly setting V_IRQ
343                  * even if it was clear in L1's VMCB.  Restoring it would be
344                  * wrong.  However, in this case V_IRQ will remain true until
345                  * interrupt_window_interception calls svm_clear_vintr and
346                  * restores int_ctl.  We can just leave it aside.
347                  */
348                 mask &= ~V_IRQ_MASK;
349         }
350         svm->nested.ctl.int_ctl        &= ~mask;
351         svm->nested.ctl.int_ctl        |= svm->vmcb->control.int_ctl & mask;
352 }
353
354 /*
355  * Transfer any event that L0 or L1 wanted to inject into L2 to
356  * EXIT_INT_INFO.
357  */
358 static void nested_save_pending_event_to_vmcb12(struct vcpu_svm *svm,
359                                                 struct vmcb *vmcb12)
360 {
361         struct kvm_vcpu *vcpu = &svm->vcpu;
362         u32 exit_int_info = 0;
363         unsigned int nr;
364
365         if (vcpu->arch.exception.injected) {
366                 nr = vcpu->arch.exception.nr;
367                 exit_int_info = nr | SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_EXEPT;
368
369                 if (vcpu->arch.exception.has_error_code) {
370                         exit_int_info |= SVM_EVTINJ_VALID_ERR;
371                         vmcb12->control.exit_int_info_err =
372                                 vcpu->arch.exception.error_code;
373                 }
374
375         } else if (vcpu->arch.nmi_injected) {
376                 exit_int_info = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
377
378         } else if (vcpu->arch.interrupt.injected) {
379                 nr = vcpu->arch.interrupt.nr;
380                 exit_int_info = nr | SVM_EVTINJ_VALID;
381
382                 if (vcpu->arch.interrupt.soft)
383                         exit_int_info |= SVM_EVTINJ_TYPE_SOFT;
384                 else
385                         exit_int_info |= SVM_EVTINJ_TYPE_INTR;
386         }
387
388         vmcb12->control.exit_int_info = exit_int_info;
389 }
390
391 static inline bool nested_npt_enabled(struct vcpu_svm *svm)
392 {
393         return svm->nested.ctl.nested_ctl & SVM_NESTED_CTL_NP_ENABLE;
394 }
395
396 static void nested_svm_transition_tlb_flush(struct kvm_vcpu *vcpu)
397 {
398         /*
399          * TODO: optimize unconditional TLB flush/MMU sync.  A partial list of
400          * things to fix before this can be conditional:
401          *
402          *  - Flush TLBs for both L1 and L2 remote TLB flush
403          *  - Honor L1's request to flush an ASID on nested VMRUN
404          *  - Sync nested NPT MMU on VMRUN that flushes L2's ASID[*]
405          *  - Don't crush a pending TLB flush in vmcb02 on nested VMRUN
406          *  - Flush L1's ASID on KVM_REQ_TLB_FLUSH_GUEST
407          *
408          * [*] Unlike nested EPT, SVM's ASID management can invalidate nested
409          *     NPT guest-physical mappings on VMRUN.
410          */
411         kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
412         kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
413 }
414
415 /*
416  * Load guest's/host's cr3 on nested vmentry or vmexit. @nested_npt is true
417  * if we are emulating VM-Entry into a guest with NPT enabled.
418  */
419 static int nested_svm_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3,
420                                bool nested_npt, bool reload_pdptrs)
421 {
422         if (CC(kvm_vcpu_is_illegal_gpa(vcpu, cr3)))
423                 return -EINVAL;
424
425         if (reload_pdptrs && !nested_npt && is_pae_paging(vcpu) &&
426             CC(!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)))
427                 return -EINVAL;
428
429         if (!nested_npt)
430                 kvm_mmu_new_pgd(vcpu, cr3);
431
432         vcpu->arch.cr3 = cr3;
433         kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
434
435         /* Re-initialize the MMU, e.g. to pick up CR4 MMU role changes. */
436         kvm_init_mmu(vcpu);
437
438         return 0;
439 }
440
441 void nested_vmcb02_compute_g_pat(struct vcpu_svm *svm)
442 {
443         if (!svm->nested.vmcb02.ptr)
444                 return;
445
446         /* FIXME: merge g_pat from vmcb01 and vmcb12.  */
447         svm->nested.vmcb02.ptr->save.g_pat = svm->vmcb01.ptr->save.g_pat;
448 }
449
450 static void nested_vmcb02_prepare_save(struct vcpu_svm *svm, struct vmcb *vmcb12)
451 {
452         bool new_vmcb12 = false;
453
454         nested_vmcb02_compute_g_pat(svm);
455
456         /* Load the nested guest state */
457         if (svm->nested.vmcb12_gpa != svm->nested.last_vmcb12_gpa) {
458                 new_vmcb12 = true;
459                 svm->nested.last_vmcb12_gpa = svm->nested.vmcb12_gpa;
460         }
461
462         if (unlikely(new_vmcb12 || vmcb_is_dirty(vmcb12, VMCB_SEG))) {
463                 svm->vmcb->save.es = vmcb12->save.es;
464                 svm->vmcb->save.cs = vmcb12->save.cs;
465                 svm->vmcb->save.ss = vmcb12->save.ss;
466                 svm->vmcb->save.ds = vmcb12->save.ds;
467                 svm->vmcb->save.cpl = vmcb12->save.cpl;
468                 vmcb_mark_dirty(svm->vmcb, VMCB_SEG);
469         }
470
471         if (unlikely(new_vmcb12 || vmcb_is_dirty(vmcb12, VMCB_DT))) {
472                 svm->vmcb->save.gdtr = vmcb12->save.gdtr;
473                 svm->vmcb->save.idtr = vmcb12->save.idtr;
474                 vmcb_mark_dirty(svm->vmcb, VMCB_DT);
475         }
476
477         kvm_set_rflags(&svm->vcpu, vmcb12->save.rflags | X86_EFLAGS_FIXED);
478
479         /*
480          * Force-set EFER_SVME even though it is checked earlier on the
481          * VMCB12, because the guest can flip the bit between the check
482          * and now.  Clearing EFER_SVME would call svm_free_nested.
483          */
484         svm_set_efer(&svm->vcpu, vmcb12->save.efer | EFER_SVME);
485
486         svm_set_cr0(&svm->vcpu, vmcb12->save.cr0);
487         svm_set_cr4(&svm->vcpu, vmcb12->save.cr4);
488
489         svm->vcpu.arch.cr2 = vmcb12->save.cr2;
490
491         kvm_rax_write(&svm->vcpu, vmcb12->save.rax);
492         kvm_rsp_write(&svm->vcpu, vmcb12->save.rsp);
493         kvm_rip_write(&svm->vcpu, vmcb12->save.rip);
494
495         /* In case we don't even reach vcpu_run, the fields are not updated */
496         svm->vmcb->save.rax = vmcb12->save.rax;
497         svm->vmcb->save.rsp = vmcb12->save.rsp;
498         svm->vmcb->save.rip = vmcb12->save.rip;
499
500         /* These bits will be set properly on the first execution when new_vmc12 is true */
501         if (unlikely(new_vmcb12 || vmcb_is_dirty(vmcb12, VMCB_DR))) {
502                 svm->vmcb->save.dr7 = vmcb12->save.dr7 | DR7_FIXED_1;
503                 svm->vcpu.arch.dr6  = vmcb12->save.dr6 | DR6_ACTIVE_LOW;
504                 vmcb_mark_dirty(svm->vmcb, VMCB_DR);
505         }
506 }
507
508 static void nested_vmcb02_prepare_control(struct vcpu_svm *svm)
509 {
510         const u32 int_ctl_vmcb01_bits =
511                 V_INTR_MASKING_MASK | V_GIF_MASK | V_GIF_ENABLE_MASK;
512
513         const u32 int_ctl_vmcb12_bits = V_TPR_MASK | V_IRQ_INJECTION_BITS_MASK;
514
515         struct kvm_vcpu *vcpu = &svm->vcpu;
516
517         /*
518          * Filled at exit: exit_code, exit_code_hi, exit_info_1, exit_info_2,
519          * exit_int_info, exit_int_info_err, next_rip, insn_len, insn_bytes.
520          */
521
522         /*
523          * Also covers avic_vapic_bar, avic_backing_page, avic_logical_id,
524          * avic_physical_id.
525          */
526         WARN_ON(kvm_apicv_activated(svm->vcpu.kvm));
527
528         /* Copied from vmcb01.  msrpm_base can be overwritten later.  */
529         svm->vmcb->control.nested_ctl = svm->vmcb01.ptr->control.nested_ctl;
530         svm->vmcb->control.iopm_base_pa = svm->vmcb01.ptr->control.iopm_base_pa;
531         svm->vmcb->control.msrpm_base_pa = svm->vmcb01.ptr->control.msrpm_base_pa;
532
533         /* Done at vmrun: asid.  */
534
535         /* Also overwritten later if necessary.  */
536         svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
537
538         /* nested_cr3.  */
539         if (nested_npt_enabled(svm))
540                 nested_svm_init_mmu_context(vcpu);
541
542         svm->vmcb->control.tsc_offset = vcpu->arch.tsc_offset =
543                 vcpu->arch.l1_tsc_offset + svm->nested.ctl.tsc_offset;
544
545         svm->vmcb->control.int_ctl             =
546                 (svm->nested.ctl.int_ctl & int_ctl_vmcb12_bits) |
547                 (svm->vmcb01.ptr->control.int_ctl & int_ctl_vmcb01_bits);
548
549         svm->vmcb->control.int_vector          = svm->nested.ctl.int_vector;
550         svm->vmcb->control.int_state           = svm->nested.ctl.int_state;
551         svm->vmcb->control.event_inj           = svm->nested.ctl.event_inj;
552         svm->vmcb->control.event_inj_err       = svm->nested.ctl.event_inj_err;
553
554         svm->vmcb->control.pause_filter_count  = svm->nested.ctl.pause_filter_count;
555         svm->vmcb->control.pause_filter_thresh = svm->nested.ctl.pause_filter_thresh;
556
557         nested_svm_transition_tlb_flush(vcpu);
558
559         /* Enter Guest-Mode */
560         enter_guest_mode(vcpu);
561
562         /*
563          * Merge guest and host intercepts - must be called with vcpu in
564          * guest-mode to take effect.
565          */
566         recalc_intercepts(svm);
567 }
568
569 static void nested_svm_copy_common_state(struct vmcb *from_vmcb, struct vmcb *to_vmcb)
570 {
571         /*
572          * Some VMCB state is shared between L1 and L2 and thus has to be
573          * moved at the time of nested vmrun and vmexit.
574          *
575          * VMLOAD/VMSAVE state would also belong in this category, but KVM
576          * always performs VMLOAD and VMSAVE from the VMCB01.
577          */
578         to_vmcb->save.spec_ctrl = from_vmcb->save.spec_ctrl;
579 }
580
581 int enter_svm_guest_mode(struct kvm_vcpu *vcpu, u64 vmcb12_gpa,
582                          struct vmcb *vmcb12, bool from_vmrun)
583 {
584         struct vcpu_svm *svm = to_svm(vcpu);
585         int ret;
586
587         trace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb12_gpa,
588                                vmcb12->save.rip,
589                                vmcb12->control.int_ctl,
590                                vmcb12->control.event_inj,
591                                vmcb12->control.nested_ctl);
592
593         trace_kvm_nested_intercepts(vmcb12->control.intercepts[INTERCEPT_CR] & 0xffff,
594                                     vmcb12->control.intercepts[INTERCEPT_CR] >> 16,
595                                     vmcb12->control.intercepts[INTERCEPT_EXCEPTION],
596                                     vmcb12->control.intercepts[INTERCEPT_WORD3],
597                                     vmcb12->control.intercepts[INTERCEPT_WORD4],
598                                     vmcb12->control.intercepts[INTERCEPT_WORD5]);
599
600
601         svm->nested.vmcb12_gpa = vmcb12_gpa;
602
603         WARN_ON(svm->vmcb == svm->nested.vmcb02.ptr);
604
605         nested_svm_copy_common_state(svm->vmcb01.ptr, svm->nested.vmcb02.ptr);
606
607         svm_switch_vmcb(svm, &svm->nested.vmcb02);
608         nested_vmcb02_prepare_control(svm);
609         nested_vmcb02_prepare_save(svm, vmcb12);
610
611         ret = nested_svm_load_cr3(&svm->vcpu, vmcb12->save.cr3,
612                                   nested_npt_enabled(svm), from_vmrun);
613         if (ret)
614                 return ret;
615
616         if (!npt_enabled)
617                 vcpu->arch.mmu->inject_page_fault = svm_inject_page_fault_nested;
618
619         if (!from_vmrun)
620                 kvm_make_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu);
621
622         svm_set_gif(svm, true);
623
624         return 0;
625 }
626
627 int nested_svm_vmrun(struct kvm_vcpu *vcpu)
628 {
629         struct vcpu_svm *svm = to_svm(vcpu);
630         int ret;
631         struct vmcb *vmcb12;
632         struct kvm_host_map map;
633         u64 vmcb12_gpa;
634
635         if (!svm->nested.hsave_msr) {
636                 kvm_inject_gp(vcpu, 0);
637                 return 1;
638         }
639
640         if (is_smm(vcpu)) {
641                 kvm_queue_exception(vcpu, UD_VECTOR);
642                 return 1;
643         }
644
645         vmcb12_gpa = svm->vmcb->save.rax;
646         ret = kvm_vcpu_map(vcpu, gpa_to_gfn(vmcb12_gpa), &map);
647         if (ret == -EINVAL) {
648                 kvm_inject_gp(vcpu, 0);
649                 return 1;
650         } else if (ret) {
651                 return kvm_skip_emulated_instruction(vcpu);
652         }
653
654         ret = kvm_skip_emulated_instruction(vcpu);
655
656         vmcb12 = map.hva;
657
658         if (WARN_ON_ONCE(!svm->nested.initialized))
659                 return -EINVAL;
660
661         nested_load_control_from_vmcb12(svm, &vmcb12->control);
662
663         if (!nested_vmcb_valid_sregs(vcpu, &vmcb12->save) ||
664             !nested_vmcb_check_controls(vcpu, &svm->nested.ctl)) {
665                 vmcb12->control.exit_code    = SVM_EXIT_ERR;
666                 vmcb12->control.exit_code_hi = 0;
667                 vmcb12->control.exit_info_1  = 0;
668                 vmcb12->control.exit_info_2  = 0;
669                 goto out;
670         }
671
672         /*
673          * Since vmcb01 is not in use, we can use it to store some of the L1
674          * state.
675          */
676         svm->vmcb01.ptr->save.efer   = vcpu->arch.efer;
677         svm->vmcb01.ptr->save.cr0    = kvm_read_cr0(vcpu);
678         svm->vmcb01.ptr->save.cr4    = vcpu->arch.cr4;
679         svm->vmcb01.ptr->save.rflags = kvm_get_rflags(vcpu);
680         svm->vmcb01.ptr->save.rip    = kvm_rip_read(vcpu);
681
682         if (!npt_enabled)
683                 svm->vmcb01.ptr->save.cr3 = kvm_read_cr3(vcpu);
684
685         svm->nested.nested_run_pending = 1;
686
687         if (enter_svm_guest_mode(vcpu, vmcb12_gpa, vmcb12, true))
688                 goto out_exit_err;
689
690         if (nested_svm_vmrun_msrpm(svm))
691                 goto out;
692
693 out_exit_err:
694         svm->nested.nested_run_pending = 0;
695
696         svm->vmcb->control.exit_code    = SVM_EXIT_ERR;
697         svm->vmcb->control.exit_code_hi = 0;
698         svm->vmcb->control.exit_info_1  = 0;
699         svm->vmcb->control.exit_info_2  = 0;
700
701         nested_svm_vmexit(svm);
702
703 out:
704         kvm_vcpu_unmap(vcpu, &map, true);
705
706         return ret;
707 }
708
709 /* Copy state save area fields which are handled by VMRUN */
710 void svm_copy_vmrun_state(struct vmcb_save_area *to_save,
711                           struct vmcb_save_area *from_save)
712 {
713         to_save->es = from_save->es;
714         to_save->cs = from_save->cs;
715         to_save->ss = from_save->ss;
716         to_save->ds = from_save->ds;
717         to_save->gdtr = from_save->gdtr;
718         to_save->idtr = from_save->idtr;
719         to_save->rflags = from_save->rflags | X86_EFLAGS_FIXED;
720         to_save->efer = from_save->efer;
721         to_save->cr0 = from_save->cr0;
722         to_save->cr3 = from_save->cr3;
723         to_save->cr4 = from_save->cr4;
724         to_save->rax = from_save->rax;
725         to_save->rsp = from_save->rsp;
726         to_save->rip = from_save->rip;
727         to_save->cpl = 0;
728 }
729
730 void svm_copy_vmloadsave_state(struct vmcb *to_vmcb, struct vmcb *from_vmcb)
731 {
732         to_vmcb->save.fs = from_vmcb->save.fs;
733         to_vmcb->save.gs = from_vmcb->save.gs;
734         to_vmcb->save.tr = from_vmcb->save.tr;
735         to_vmcb->save.ldtr = from_vmcb->save.ldtr;
736         to_vmcb->save.kernel_gs_base = from_vmcb->save.kernel_gs_base;
737         to_vmcb->save.star = from_vmcb->save.star;
738         to_vmcb->save.lstar = from_vmcb->save.lstar;
739         to_vmcb->save.cstar = from_vmcb->save.cstar;
740         to_vmcb->save.sfmask = from_vmcb->save.sfmask;
741         to_vmcb->save.sysenter_cs = from_vmcb->save.sysenter_cs;
742         to_vmcb->save.sysenter_esp = from_vmcb->save.sysenter_esp;
743         to_vmcb->save.sysenter_eip = from_vmcb->save.sysenter_eip;
744 }
745
746 int nested_svm_vmexit(struct vcpu_svm *svm)
747 {
748         struct kvm_vcpu *vcpu = &svm->vcpu;
749         struct vmcb *vmcb12;
750         struct vmcb *vmcb = svm->vmcb;
751         struct kvm_host_map map;
752         int rc;
753
754         rc = kvm_vcpu_map(vcpu, gpa_to_gfn(svm->nested.vmcb12_gpa), &map);
755         if (rc) {
756                 if (rc == -EINVAL)
757                         kvm_inject_gp(vcpu, 0);
758                 return 1;
759         }
760
761         vmcb12 = map.hva;
762
763         /* Exit Guest-Mode */
764         leave_guest_mode(vcpu);
765         svm->nested.vmcb12_gpa = 0;
766         WARN_ON_ONCE(svm->nested.nested_run_pending);
767
768         kvm_clear_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu);
769
770         /* in case we halted in L2 */
771         svm->vcpu.arch.mp_state = KVM_MP_STATE_RUNNABLE;
772
773         /* Give the current vmcb to the guest */
774
775         vmcb12->save.es     = vmcb->save.es;
776         vmcb12->save.cs     = vmcb->save.cs;
777         vmcb12->save.ss     = vmcb->save.ss;
778         vmcb12->save.ds     = vmcb->save.ds;
779         vmcb12->save.gdtr   = vmcb->save.gdtr;
780         vmcb12->save.idtr   = vmcb->save.idtr;
781         vmcb12->save.efer   = svm->vcpu.arch.efer;
782         vmcb12->save.cr0    = kvm_read_cr0(vcpu);
783         vmcb12->save.cr3    = kvm_read_cr3(vcpu);
784         vmcb12->save.cr2    = vmcb->save.cr2;
785         vmcb12->save.cr4    = svm->vcpu.arch.cr4;
786         vmcb12->save.rflags = kvm_get_rflags(vcpu);
787         vmcb12->save.rip    = kvm_rip_read(vcpu);
788         vmcb12->save.rsp    = kvm_rsp_read(vcpu);
789         vmcb12->save.rax    = kvm_rax_read(vcpu);
790         vmcb12->save.dr7    = vmcb->save.dr7;
791         vmcb12->save.dr6    = svm->vcpu.arch.dr6;
792         vmcb12->save.cpl    = vmcb->save.cpl;
793
794         vmcb12->control.int_state         = vmcb->control.int_state;
795         vmcb12->control.exit_code         = vmcb->control.exit_code;
796         vmcb12->control.exit_code_hi      = vmcb->control.exit_code_hi;
797         vmcb12->control.exit_info_1       = vmcb->control.exit_info_1;
798         vmcb12->control.exit_info_2       = vmcb->control.exit_info_2;
799
800         if (vmcb12->control.exit_code != SVM_EXIT_ERR)
801                 nested_save_pending_event_to_vmcb12(svm, vmcb12);
802
803         if (svm->nrips_enabled)
804                 vmcb12->control.next_rip  = vmcb->control.next_rip;
805
806         vmcb12->control.int_ctl           = svm->nested.ctl.int_ctl;
807         vmcb12->control.tlb_ctl           = svm->nested.ctl.tlb_ctl;
808         vmcb12->control.event_inj         = svm->nested.ctl.event_inj;
809         vmcb12->control.event_inj_err     = svm->nested.ctl.event_inj_err;
810
811         vmcb12->control.pause_filter_count =
812                 svm->vmcb->control.pause_filter_count;
813         vmcb12->control.pause_filter_thresh =
814                 svm->vmcb->control.pause_filter_thresh;
815
816         nested_svm_copy_common_state(svm->nested.vmcb02.ptr, svm->vmcb01.ptr);
817
818         svm_switch_vmcb(svm, &svm->vmcb01);
819
820         /*
821          * On vmexit the  GIF is set to false and
822          * no event can be injected in L1.
823          */
824         svm_set_gif(svm, false);
825         svm->vmcb->control.exit_int_info = 0;
826
827         svm->vcpu.arch.tsc_offset = svm->vcpu.arch.l1_tsc_offset;
828         if (svm->vmcb->control.tsc_offset != svm->vcpu.arch.tsc_offset) {
829                 svm->vmcb->control.tsc_offset = svm->vcpu.arch.tsc_offset;
830                 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
831         }
832
833         svm->nested.ctl.nested_cr3 = 0;
834
835         /*
836          * Restore processor state that had been saved in vmcb01
837          */
838         kvm_set_rflags(vcpu, svm->vmcb->save.rflags);
839         svm_set_efer(vcpu, svm->vmcb->save.efer);
840         svm_set_cr0(vcpu, svm->vmcb->save.cr0 | X86_CR0_PE);
841         svm_set_cr4(vcpu, svm->vmcb->save.cr4);
842         kvm_rax_write(vcpu, svm->vmcb->save.rax);
843         kvm_rsp_write(vcpu, svm->vmcb->save.rsp);
844         kvm_rip_write(vcpu, svm->vmcb->save.rip);
845
846         svm->vcpu.arch.dr7 = DR7_FIXED_1;
847         kvm_update_dr7(&svm->vcpu);
848
849         trace_kvm_nested_vmexit_inject(vmcb12->control.exit_code,
850                                        vmcb12->control.exit_info_1,
851                                        vmcb12->control.exit_info_2,
852                                        vmcb12->control.exit_int_info,
853                                        vmcb12->control.exit_int_info_err,
854                                        KVM_ISA_SVM);
855
856         kvm_vcpu_unmap(vcpu, &map, true);
857
858         nested_svm_transition_tlb_flush(vcpu);
859
860         nested_svm_uninit_mmu_context(vcpu);
861
862         rc = nested_svm_load_cr3(vcpu, svm->vmcb->save.cr3, false, true);
863         if (rc)
864                 return 1;
865
866         /*
867          * Drop what we picked up for L2 via svm_complete_interrupts() so it
868          * doesn't end up in L1.
869          */
870         svm->vcpu.arch.nmi_injected = false;
871         kvm_clear_exception_queue(vcpu);
872         kvm_clear_interrupt_queue(vcpu);
873
874         /*
875          * If we are here following the completion of a VMRUN that
876          * is being single-stepped, queue the pending #DB intercept
877          * right now so that it an be accounted for before we execute
878          * L1's next instruction.
879          */
880         if (unlikely(svm->vmcb->save.rflags & X86_EFLAGS_TF))
881                 kvm_queue_exception(&(svm->vcpu), DB_VECTOR);
882
883         return 0;
884 }
885
886 static void nested_svm_triple_fault(struct kvm_vcpu *vcpu)
887 {
888         nested_svm_simple_vmexit(to_svm(vcpu), SVM_EXIT_SHUTDOWN);
889 }
890
891 int svm_allocate_nested(struct vcpu_svm *svm)
892 {
893         struct page *vmcb02_page;
894
895         if (svm->nested.initialized)
896                 return 0;
897
898         vmcb02_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
899         if (!vmcb02_page)
900                 return -ENOMEM;
901         svm->nested.vmcb02.ptr = page_address(vmcb02_page);
902         svm->nested.vmcb02.pa = __sme_set(page_to_pfn(vmcb02_page) << PAGE_SHIFT);
903
904         svm->nested.msrpm = svm_vcpu_alloc_msrpm();
905         if (!svm->nested.msrpm)
906                 goto err_free_vmcb02;
907         svm_vcpu_init_msrpm(&svm->vcpu, svm->nested.msrpm);
908
909         svm->nested.initialized = true;
910         return 0;
911
912 err_free_vmcb02:
913         __free_page(vmcb02_page);
914         return -ENOMEM;
915 }
916
917 void svm_free_nested(struct vcpu_svm *svm)
918 {
919         if (!svm->nested.initialized)
920                 return;
921
922         if (WARN_ON_ONCE(svm->vmcb != svm->vmcb01.ptr))
923                 svm_switch_vmcb(svm, &svm->vmcb01);
924
925         svm_vcpu_free_msrpm(svm->nested.msrpm);
926         svm->nested.msrpm = NULL;
927
928         __free_page(virt_to_page(svm->nested.vmcb02.ptr));
929         svm->nested.vmcb02.ptr = NULL;
930
931         /*
932          * When last_vmcb12_gpa matches the current vmcb12 gpa,
933          * some vmcb12 fields are not loaded if they are marked clean
934          * in the vmcb12, since in this case they are up to date already.
935          *
936          * When the vmcb02 is freed, this optimization becomes invalid.
937          */
938         svm->nested.last_vmcb12_gpa = INVALID_GPA;
939
940         svm->nested.initialized = false;
941 }
942
943 void svm_leave_nested(struct kvm_vcpu *vcpu)
944 {
945         struct vcpu_svm *svm = to_svm(vcpu);
946
947         if (is_guest_mode(vcpu)) {
948                 svm->nested.nested_run_pending = 0;
949                 svm->nested.vmcb12_gpa = INVALID_GPA;
950
951                 leave_guest_mode(vcpu);
952
953                 svm_switch_vmcb(svm, &svm->vmcb01);
954
955                 nested_svm_uninit_mmu_context(vcpu);
956                 vmcb_mark_all_dirty(svm->vmcb);
957         }
958
959         kvm_clear_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu);
960 }
961
962 static int nested_svm_exit_handled_msr(struct vcpu_svm *svm)
963 {
964         u32 offset, msr, value;
965         int write, mask;
966
967         if (!(vmcb_is_intercept(&svm->nested.ctl, INTERCEPT_MSR_PROT)))
968                 return NESTED_EXIT_HOST;
969
970         msr    = svm->vcpu.arch.regs[VCPU_REGS_RCX];
971         offset = svm_msrpm_offset(msr);
972         write  = svm->vmcb->control.exit_info_1 & 1;
973         mask   = 1 << ((2 * (msr & 0xf)) + write);
974
975         if (offset == MSR_INVALID)
976                 return NESTED_EXIT_DONE;
977
978         /* Offset is in 32 bit units but need in 8 bit units */
979         offset *= 4;
980
981         if (kvm_vcpu_read_guest(&svm->vcpu, svm->nested.ctl.msrpm_base_pa + offset, &value, 4))
982                 return NESTED_EXIT_DONE;
983
984         return (value & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
985 }
986
987 static int nested_svm_intercept_ioio(struct vcpu_svm *svm)
988 {
989         unsigned port, size, iopm_len;
990         u16 val, mask;
991         u8 start_bit;
992         u64 gpa;
993
994         if (!(vmcb_is_intercept(&svm->nested.ctl, INTERCEPT_IOIO_PROT)))
995                 return NESTED_EXIT_HOST;
996
997         port = svm->vmcb->control.exit_info_1 >> 16;
998         size = (svm->vmcb->control.exit_info_1 & SVM_IOIO_SIZE_MASK) >>
999                 SVM_IOIO_SIZE_SHIFT;
1000         gpa  = svm->nested.ctl.iopm_base_pa + (port / 8);
1001         start_bit = port % 8;
1002         iopm_len = (start_bit + size > 8) ? 2 : 1;
1003         mask = (0xf >> (4 - size)) << start_bit;
1004         val = 0;
1005
1006         if (kvm_vcpu_read_guest(&svm->vcpu, gpa, &val, iopm_len))
1007                 return NESTED_EXIT_DONE;
1008
1009         return (val & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
1010 }
1011
1012 static int nested_svm_intercept(struct vcpu_svm *svm)
1013 {
1014         u32 exit_code = svm->vmcb->control.exit_code;
1015         int vmexit = NESTED_EXIT_HOST;
1016
1017         switch (exit_code) {
1018         case SVM_EXIT_MSR:
1019                 vmexit = nested_svm_exit_handled_msr(svm);
1020                 break;
1021         case SVM_EXIT_IOIO:
1022                 vmexit = nested_svm_intercept_ioio(svm);
1023                 break;
1024         case SVM_EXIT_READ_CR0 ... SVM_EXIT_WRITE_CR8: {
1025                 if (vmcb_is_intercept(&svm->nested.ctl, exit_code))
1026                         vmexit = NESTED_EXIT_DONE;
1027                 break;
1028         }
1029         case SVM_EXIT_READ_DR0 ... SVM_EXIT_WRITE_DR7: {
1030                 if (vmcb_is_intercept(&svm->nested.ctl, exit_code))
1031                         vmexit = NESTED_EXIT_DONE;
1032                 break;
1033         }
1034         case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
1035                 /*
1036                  * Host-intercepted exceptions have been checked already in
1037                  * nested_svm_exit_special.  There is nothing to do here,
1038                  * the vmexit is injected by svm_check_nested_events.
1039                  */
1040                 vmexit = NESTED_EXIT_DONE;
1041                 break;
1042         }
1043         case SVM_EXIT_ERR: {
1044                 vmexit = NESTED_EXIT_DONE;
1045                 break;
1046         }
1047         default: {
1048                 if (vmcb_is_intercept(&svm->nested.ctl, exit_code))
1049                         vmexit = NESTED_EXIT_DONE;
1050         }
1051         }
1052
1053         return vmexit;
1054 }
1055
1056 int nested_svm_exit_handled(struct vcpu_svm *svm)
1057 {
1058         int vmexit;
1059
1060         vmexit = nested_svm_intercept(svm);
1061
1062         if (vmexit == NESTED_EXIT_DONE)
1063                 nested_svm_vmexit(svm);
1064
1065         return vmexit;
1066 }
1067
1068 int nested_svm_check_permissions(struct kvm_vcpu *vcpu)
1069 {
1070         if (!(vcpu->arch.efer & EFER_SVME) || !is_paging(vcpu)) {
1071                 kvm_queue_exception(vcpu, UD_VECTOR);
1072                 return 1;
1073         }
1074
1075         if (to_svm(vcpu)->vmcb->save.cpl) {
1076                 kvm_inject_gp(vcpu, 0);
1077                 return 1;
1078         }
1079
1080         return 0;
1081 }
1082
1083 static bool nested_exit_on_exception(struct vcpu_svm *svm)
1084 {
1085         unsigned int nr = svm->vcpu.arch.exception.nr;
1086
1087         return (svm->nested.ctl.intercepts[INTERCEPT_EXCEPTION] & BIT(nr));
1088 }
1089
1090 static void nested_svm_inject_exception_vmexit(struct vcpu_svm *svm)
1091 {
1092         unsigned int nr = svm->vcpu.arch.exception.nr;
1093
1094         svm->vmcb->control.exit_code = SVM_EXIT_EXCP_BASE + nr;
1095         svm->vmcb->control.exit_code_hi = 0;
1096
1097         if (svm->vcpu.arch.exception.has_error_code)
1098                 svm->vmcb->control.exit_info_1 = svm->vcpu.arch.exception.error_code;
1099
1100         /*
1101          * EXITINFO2 is undefined for all exception intercepts other
1102          * than #PF.
1103          */
1104         if (nr == PF_VECTOR) {
1105                 if (svm->vcpu.arch.exception.nested_apf)
1106                         svm->vmcb->control.exit_info_2 = svm->vcpu.arch.apf.nested_apf_token;
1107                 else if (svm->vcpu.arch.exception.has_payload)
1108                         svm->vmcb->control.exit_info_2 = svm->vcpu.arch.exception.payload;
1109                 else
1110                         svm->vmcb->control.exit_info_2 = svm->vcpu.arch.cr2;
1111         } else if (nr == DB_VECTOR) {
1112                 /* See inject_pending_event.  */
1113                 kvm_deliver_exception_payload(&svm->vcpu);
1114                 if (svm->vcpu.arch.dr7 & DR7_GD) {
1115                         svm->vcpu.arch.dr7 &= ~DR7_GD;
1116                         kvm_update_dr7(&svm->vcpu);
1117                 }
1118         } else
1119                 WARN_ON(svm->vcpu.arch.exception.has_payload);
1120
1121         nested_svm_vmexit(svm);
1122 }
1123
1124 static inline bool nested_exit_on_init(struct vcpu_svm *svm)
1125 {
1126         return vmcb_is_intercept(&svm->nested.ctl, INTERCEPT_INIT);
1127 }
1128
1129 static int svm_check_nested_events(struct kvm_vcpu *vcpu)
1130 {
1131         struct vcpu_svm *svm = to_svm(vcpu);
1132         bool block_nested_events =
1133                 kvm_event_needs_reinjection(vcpu) || svm->nested.nested_run_pending;
1134         struct kvm_lapic *apic = vcpu->arch.apic;
1135
1136         if (lapic_in_kernel(vcpu) &&
1137             test_bit(KVM_APIC_INIT, &apic->pending_events)) {
1138                 if (block_nested_events)
1139                         return -EBUSY;
1140                 if (!nested_exit_on_init(svm))
1141                         return 0;
1142                 nested_svm_simple_vmexit(svm, SVM_EXIT_INIT);
1143                 return 0;
1144         }
1145
1146         if (vcpu->arch.exception.pending) {
1147                 /*
1148                  * Only a pending nested run can block a pending exception.
1149                  * Otherwise an injected NMI/interrupt should either be
1150                  * lost or delivered to the nested hypervisor in the EXITINTINFO
1151                  * vmcb field, while delivering the pending exception.
1152                  */
1153                 if (svm->nested.nested_run_pending)
1154                         return -EBUSY;
1155                 if (!nested_exit_on_exception(svm))
1156                         return 0;
1157                 nested_svm_inject_exception_vmexit(svm);
1158                 return 0;
1159         }
1160
1161         if (vcpu->arch.smi_pending && !svm_smi_blocked(vcpu)) {
1162                 if (block_nested_events)
1163                         return -EBUSY;
1164                 if (!nested_exit_on_smi(svm))
1165                         return 0;
1166                 nested_svm_simple_vmexit(svm, SVM_EXIT_SMI);
1167                 return 0;
1168         }
1169
1170         if (vcpu->arch.nmi_pending && !svm_nmi_blocked(vcpu)) {
1171                 if (block_nested_events)
1172                         return -EBUSY;
1173                 if (!nested_exit_on_nmi(svm))
1174                         return 0;
1175                 nested_svm_simple_vmexit(svm, SVM_EXIT_NMI);
1176                 return 0;
1177         }
1178
1179         if (kvm_cpu_has_interrupt(vcpu) && !svm_interrupt_blocked(vcpu)) {
1180                 if (block_nested_events)
1181                         return -EBUSY;
1182                 if (!nested_exit_on_intr(svm))
1183                         return 0;
1184                 trace_kvm_nested_intr_vmexit(svm->vmcb->save.rip);
1185                 nested_svm_simple_vmexit(svm, SVM_EXIT_INTR);
1186                 return 0;
1187         }
1188
1189         return 0;
1190 }
1191
1192 int nested_svm_exit_special(struct vcpu_svm *svm)
1193 {
1194         u32 exit_code = svm->vmcb->control.exit_code;
1195
1196         switch (exit_code) {
1197         case SVM_EXIT_INTR:
1198         case SVM_EXIT_NMI:
1199         case SVM_EXIT_NPF:
1200                 return NESTED_EXIT_HOST;
1201         case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
1202                 u32 excp_bits = 1 << (exit_code - SVM_EXIT_EXCP_BASE);
1203
1204                 if (svm->vmcb01.ptr->control.intercepts[INTERCEPT_EXCEPTION] &
1205                     excp_bits)
1206                         return NESTED_EXIT_HOST;
1207                 else if (exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR &&
1208                          svm->vcpu.arch.apf.host_apf_flags)
1209                         /* Trap async PF even if not shadowing */
1210                         return NESTED_EXIT_HOST;
1211                 break;
1212         }
1213         default:
1214                 break;
1215         }
1216
1217         return NESTED_EXIT_CONTINUE;
1218 }
1219
1220 static int svm_get_nested_state(struct kvm_vcpu *vcpu,
1221                                 struct kvm_nested_state __user *user_kvm_nested_state,
1222                                 u32 user_data_size)
1223 {
1224         struct vcpu_svm *svm;
1225         struct kvm_nested_state kvm_state = {
1226                 .flags = 0,
1227                 .format = KVM_STATE_NESTED_FORMAT_SVM,
1228                 .size = sizeof(kvm_state),
1229         };
1230         struct vmcb __user *user_vmcb = (struct vmcb __user *)
1231                 &user_kvm_nested_state->data.svm[0];
1232
1233         if (!vcpu)
1234                 return kvm_state.size + KVM_STATE_NESTED_SVM_VMCB_SIZE;
1235
1236         svm = to_svm(vcpu);
1237
1238         if (user_data_size < kvm_state.size)
1239                 goto out;
1240
1241         /* First fill in the header and copy it out.  */
1242         if (is_guest_mode(vcpu)) {
1243                 kvm_state.hdr.svm.vmcb_pa = svm->nested.vmcb12_gpa;
1244                 kvm_state.size += KVM_STATE_NESTED_SVM_VMCB_SIZE;
1245                 kvm_state.flags |= KVM_STATE_NESTED_GUEST_MODE;
1246
1247                 if (svm->nested.nested_run_pending)
1248                         kvm_state.flags |= KVM_STATE_NESTED_RUN_PENDING;
1249         }
1250
1251         if (gif_set(svm))
1252                 kvm_state.flags |= KVM_STATE_NESTED_GIF_SET;
1253
1254         if (copy_to_user(user_kvm_nested_state, &kvm_state, sizeof(kvm_state)))
1255                 return -EFAULT;
1256
1257         if (!is_guest_mode(vcpu))
1258                 goto out;
1259
1260         /*
1261          * Copy over the full size of the VMCB rather than just the size
1262          * of the structs.
1263          */
1264         if (clear_user(user_vmcb, KVM_STATE_NESTED_SVM_VMCB_SIZE))
1265                 return -EFAULT;
1266         if (copy_to_user(&user_vmcb->control, &svm->nested.ctl,
1267                          sizeof(user_vmcb->control)))
1268                 return -EFAULT;
1269         if (copy_to_user(&user_vmcb->save, &svm->vmcb01.ptr->save,
1270                          sizeof(user_vmcb->save)))
1271                 return -EFAULT;
1272 out:
1273         return kvm_state.size;
1274 }
1275
1276 static int svm_set_nested_state(struct kvm_vcpu *vcpu,
1277                                 struct kvm_nested_state __user *user_kvm_nested_state,
1278                                 struct kvm_nested_state *kvm_state)
1279 {
1280         struct vcpu_svm *svm = to_svm(vcpu);
1281         struct vmcb __user *user_vmcb = (struct vmcb __user *)
1282                 &user_kvm_nested_state->data.svm[0];
1283         struct vmcb_control_area *ctl;
1284         struct vmcb_save_area *save;
1285         unsigned long cr0;
1286         int ret;
1287
1288         BUILD_BUG_ON(sizeof(struct vmcb_control_area) + sizeof(struct vmcb_save_area) >
1289                      KVM_STATE_NESTED_SVM_VMCB_SIZE);
1290
1291         if (kvm_state->format != KVM_STATE_NESTED_FORMAT_SVM)
1292                 return -EINVAL;
1293
1294         if (kvm_state->flags & ~(KVM_STATE_NESTED_GUEST_MODE |
1295                                  KVM_STATE_NESTED_RUN_PENDING |
1296                                  KVM_STATE_NESTED_GIF_SET))
1297                 return -EINVAL;
1298
1299         /*
1300          * If in guest mode, vcpu->arch.efer actually refers to the L2 guest's
1301          * EFER.SVME, but EFER.SVME still has to be 1 for VMRUN to succeed.
1302          */
1303         if (!(vcpu->arch.efer & EFER_SVME)) {
1304                 /* GIF=1 and no guest mode are required if SVME=0.  */
1305                 if (kvm_state->flags != KVM_STATE_NESTED_GIF_SET)
1306                         return -EINVAL;
1307         }
1308
1309         /* SMM temporarily disables SVM, so we cannot be in guest mode.  */
1310         if (is_smm(vcpu) && (kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
1311                 return -EINVAL;
1312
1313         if (!(kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE)) {
1314                 svm_leave_nested(vcpu);
1315                 svm_set_gif(svm, !!(kvm_state->flags & KVM_STATE_NESTED_GIF_SET));
1316                 return 0;
1317         }
1318
1319         if (!page_address_valid(vcpu, kvm_state->hdr.svm.vmcb_pa))
1320                 return -EINVAL;
1321         if (kvm_state->size < sizeof(*kvm_state) + KVM_STATE_NESTED_SVM_VMCB_SIZE)
1322                 return -EINVAL;
1323
1324         ret  = -ENOMEM;
1325         ctl  = kzalloc(sizeof(*ctl),  GFP_KERNEL_ACCOUNT);
1326         save = kzalloc(sizeof(*save), GFP_KERNEL_ACCOUNT);
1327         if (!ctl || !save)
1328                 goto out_free;
1329
1330         ret = -EFAULT;
1331         if (copy_from_user(ctl, &user_vmcb->control, sizeof(*ctl)))
1332                 goto out_free;
1333         if (copy_from_user(save, &user_vmcb->save, sizeof(*save)))
1334                 goto out_free;
1335
1336         ret = -EINVAL;
1337         if (!nested_vmcb_check_controls(vcpu, ctl))
1338                 goto out_free;
1339
1340         /*
1341          * Processor state contains L2 state.  Check that it is
1342          * valid for guest mode (see nested_vmcb_check_save).
1343          */
1344         cr0 = kvm_read_cr0(vcpu);
1345         if (((cr0 & X86_CR0_CD) == 0) && (cr0 & X86_CR0_NW))
1346                 goto out_free;
1347
1348         /*
1349          * Validate host state saved from before VMRUN (see
1350          * nested_svm_check_permissions).
1351          */
1352         if (!(save->cr0 & X86_CR0_PG) ||
1353             !(save->cr0 & X86_CR0_PE) ||
1354             (save->rflags & X86_EFLAGS_VM) ||
1355             !nested_vmcb_valid_sregs(vcpu, save))
1356                 goto out_free;
1357
1358
1359         /*
1360          * All checks done, we can enter guest mode. Userspace provides
1361          * vmcb12.control, which will be combined with L1 and stored into
1362          * vmcb02, and the L1 save state which we store in vmcb01.
1363          * L2 registers if needed are moved from the current VMCB to VMCB02.
1364          */
1365
1366         if (is_guest_mode(vcpu))
1367                 svm_leave_nested(vcpu);
1368         else
1369                 svm->nested.vmcb02.ptr->save = svm->vmcb01.ptr->save;
1370
1371         svm_set_gif(svm, !!(kvm_state->flags & KVM_STATE_NESTED_GIF_SET));
1372
1373         svm->nested.nested_run_pending =
1374                 !!(kvm_state->flags & KVM_STATE_NESTED_RUN_PENDING);
1375
1376         svm->nested.vmcb12_gpa = kvm_state->hdr.svm.vmcb_pa;
1377
1378         svm_copy_vmrun_state(&svm->vmcb01.ptr->save, save);
1379         nested_load_control_from_vmcb12(svm, ctl);
1380
1381         svm_switch_vmcb(svm, &svm->nested.vmcb02);
1382         nested_vmcb02_prepare_control(svm);
1383
1384         /*
1385          * While the nested guest CR3 is already checked and set by
1386          * KVM_SET_SREGS, it was set when nested state was yet loaded,
1387          * thus MMU might not be initialized correctly.
1388          * Set it again to fix this.
1389          */
1390
1391         ret = nested_svm_load_cr3(&svm->vcpu, vcpu->arch.cr3,
1392                                   nested_npt_enabled(svm), false);
1393         if (WARN_ON_ONCE(ret))
1394                 goto out_free;
1395
1396
1397         kvm_make_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu);
1398         ret = 0;
1399 out_free:
1400         kfree(save);
1401         kfree(ctl);
1402
1403         return ret;
1404 }
1405
1406 static bool svm_get_nested_state_pages(struct kvm_vcpu *vcpu)
1407 {
1408         struct vcpu_svm *svm = to_svm(vcpu);
1409
1410         if (WARN_ON(!is_guest_mode(vcpu)))
1411                 return true;
1412
1413         if (!vcpu->arch.pdptrs_from_userspace &&
1414             !nested_npt_enabled(svm) && is_pae_paging(vcpu))
1415                 /*
1416                  * Reload the guest's PDPTRs since after a migration
1417                  * the guest CR3 might be restored prior to setting the nested
1418                  * state which can lead to a load of wrong PDPTRs.
1419                  */
1420                 if (CC(!load_pdptrs(vcpu, vcpu->arch.walk_mmu, vcpu->arch.cr3)))
1421                         return false;
1422
1423         if (!nested_svm_vmrun_msrpm(svm)) {
1424                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
1425                 vcpu->run->internal.suberror =
1426                         KVM_INTERNAL_ERROR_EMULATION;
1427                 vcpu->run->internal.ndata = 0;
1428                 return false;
1429         }
1430
1431         return true;
1432 }
1433
1434 struct kvm_x86_nested_ops svm_nested_ops = {
1435         .leave_nested = svm_leave_nested,
1436         .check_events = svm_check_nested_events,
1437         .triple_fault = nested_svm_triple_fault,
1438         .get_nested_state_pages = svm_get_nested_state_pages,
1439         .get_state = svm_get_nested_state,
1440         .set_state = svm_set_nested_state,
1441 };