Merge tag 'for-linus' of git://git.armlinux.org.uk/~rmk/linux-arm
[platform/kernel/linux-rpi.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         if (CC(!kvm_is_valid_cr4(vcpu, save->cr4)))
279                 return false;
280
281         return true;
282 }
283
284 /* Common checks that apply to both L1 and L2 state.  */
285 static bool nested_vmcb_valid_sregs(struct kvm_vcpu *vcpu,
286                                     struct vmcb_save_area *save)
287 {
288         /*
289          * FIXME: these should be done after copying the fields,
290          * to avoid TOC/TOU races.  For these save area checks
291          * the possible damage is limited since kvm_set_cr0 and
292          * kvm_set_cr4 handle failure; EFER_SVME is an exception
293          * so it is force-set later in nested_prepare_vmcb_save.
294          */
295         if (CC(!(save->efer & EFER_SVME)))
296                 return false;
297
298         if (CC((save->cr0 & X86_CR0_CD) == 0 && (save->cr0 & X86_CR0_NW)) ||
299             CC(save->cr0 & ~0xffffffffULL))
300                 return false;
301
302         if (CC(!kvm_dr6_valid(save->dr6)) || CC(!kvm_dr7_valid(save->dr7)))
303                 return false;
304
305         if (!nested_vmcb_check_cr3_cr4(vcpu, save))
306                 return false;
307
308         if (CC(!kvm_valid_efer(vcpu, save->efer)))
309                 return false;
310
311         return true;
312 }
313
314 void nested_load_control_from_vmcb12(struct vcpu_svm *svm,
315                                      struct vmcb_control_area *control)
316 {
317         copy_vmcb_control_area(&svm->nested.ctl, control);
318
319         /* Copy it here because nested_svm_check_controls will check it.  */
320         svm->nested.ctl.asid           = control->asid;
321         svm->nested.ctl.msrpm_base_pa &= ~0x0fffULL;
322         svm->nested.ctl.iopm_base_pa  &= ~0x0fffULL;
323 }
324
325 /*
326  * Synchronize fields that are written by the processor, so that
327  * they can be copied back into the vmcb12.
328  */
329 void nested_sync_control_from_vmcb02(struct vcpu_svm *svm)
330 {
331         u32 mask;
332         svm->nested.ctl.event_inj      = svm->vmcb->control.event_inj;
333         svm->nested.ctl.event_inj_err  = svm->vmcb->control.event_inj_err;
334
335         /* Only a few fields of int_ctl are written by the processor.  */
336         mask = V_IRQ_MASK | V_TPR_MASK;
337         if (!(svm->nested.ctl.int_ctl & V_INTR_MASKING_MASK) &&
338             svm_is_intercept(svm, INTERCEPT_VINTR)) {
339                 /*
340                  * In order to request an interrupt window, L0 is usurping
341                  * svm->vmcb->control.int_ctl and possibly setting V_IRQ
342                  * even if it was clear in L1's VMCB.  Restoring it would be
343                  * wrong.  However, in this case V_IRQ will remain true until
344                  * interrupt_window_interception calls svm_clear_vintr and
345                  * restores int_ctl.  We can just leave it aside.
346                  */
347                 mask &= ~V_IRQ_MASK;
348         }
349         svm->nested.ctl.int_ctl        &= ~mask;
350         svm->nested.ctl.int_ctl        |= svm->vmcb->control.int_ctl & mask;
351 }
352
353 /*
354  * Transfer any event that L0 or L1 wanted to inject into L2 to
355  * EXIT_INT_INFO.
356  */
357 static void nested_save_pending_event_to_vmcb12(struct vcpu_svm *svm,
358                                                 struct vmcb *vmcb12)
359 {
360         struct kvm_vcpu *vcpu = &svm->vcpu;
361         u32 exit_int_info = 0;
362         unsigned int nr;
363
364         if (vcpu->arch.exception.injected) {
365                 nr = vcpu->arch.exception.nr;
366                 exit_int_info = nr | SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_EXEPT;
367
368                 if (vcpu->arch.exception.has_error_code) {
369                         exit_int_info |= SVM_EVTINJ_VALID_ERR;
370                         vmcb12->control.exit_int_info_err =
371                                 vcpu->arch.exception.error_code;
372                 }
373
374         } else if (vcpu->arch.nmi_injected) {
375                 exit_int_info = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
376
377         } else if (vcpu->arch.interrupt.injected) {
378                 nr = vcpu->arch.interrupt.nr;
379                 exit_int_info = nr | SVM_EVTINJ_VALID;
380
381                 if (vcpu->arch.interrupt.soft)
382                         exit_int_info |= SVM_EVTINJ_TYPE_SOFT;
383                 else
384                         exit_int_info |= SVM_EVTINJ_TYPE_INTR;
385         }
386
387         vmcb12->control.exit_int_info = exit_int_info;
388 }
389
390 static inline bool nested_npt_enabled(struct vcpu_svm *svm)
391 {
392         return svm->nested.ctl.nested_ctl & SVM_NESTED_CTL_NP_ENABLE;
393 }
394
395 static void nested_svm_transition_tlb_flush(struct kvm_vcpu *vcpu)
396 {
397         /*
398          * TODO: optimize unconditional TLB flush/MMU sync.  A partial list of
399          * things to fix before this can be conditional:
400          *
401          *  - Flush TLBs for both L1 and L2 remote TLB flush
402          *  - Honor L1's request to flush an ASID on nested VMRUN
403          *  - Sync nested NPT MMU on VMRUN that flushes L2's ASID[*]
404          *  - Don't crush a pending TLB flush in vmcb02 on nested VMRUN
405          *  - Flush L1's ASID on KVM_REQ_TLB_FLUSH_GUEST
406          *
407          * [*] Unlike nested EPT, SVM's ASID management can invalidate nested
408          *     NPT guest-physical mappings on VMRUN.
409          */
410         kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
411         kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
412 }
413
414 /*
415  * Load guest's/host's cr3 on nested vmentry or vmexit. @nested_npt is true
416  * if we are emulating VM-Entry into a guest with NPT enabled.
417  */
418 static int nested_svm_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3,
419                                bool nested_npt, bool reload_pdptrs)
420 {
421         if (CC(kvm_vcpu_is_illegal_gpa(vcpu, cr3)))
422                 return -EINVAL;
423
424         if (reload_pdptrs && !nested_npt && is_pae_paging(vcpu) &&
425             CC(!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)))
426                 return -EINVAL;
427
428         if (!nested_npt)
429                 kvm_mmu_new_pgd(vcpu, cr3);
430
431         vcpu->arch.cr3 = cr3;
432         kvm_register_mark_available(vcpu, VCPU_EXREG_CR3);
433
434         /* Re-initialize the MMU, e.g. to pick up CR4 MMU role changes. */
435         kvm_init_mmu(vcpu);
436
437         return 0;
438 }
439
440 void nested_vmcb02_compute_g_pat(struct vcpu_svm *svm)
441 {
442         if (!svm->nested.vmcb02.ptr)
443                 return;
444
445         /* FIXME: merge g_pat from vmcb01 and vmcb12.  */
446         svm->nested.vmcb02.ptr->save.g_pat = svm->vmcb01.ptr->save.g_pat;
447 }
448
449 static void nested_vmcb02_prepare_save(struct vcpu_svm *svm, struct vmcb *vmcb12)
450 {
451         bool new_vmcb12 = false;
452
453         nested_vmcb02_compute_g_pat(svm);
454
455         /* Load the nested guest state */
456         if (svm->nested.vmcb12_gpa != svm->nested.last_vmcb12_gpa) {
457                 new_vmcb12 = true;
458                 svm->nested.last_vmcb12_gpa = svm->nested.vmcb12_gpa;
459         }
460
461         if (unlikely(new_vmcb12 || vmcb_is_dirty(vmcb12, VMCB_SEG))) {
462                 svm->vmcb->save.es = vmcb12->save.es;
463                 svm->vmcb->save.cs = vmcb12->save.cs;
464                 svm->vmcb->save.ss = vmcb12->save.ss;
465                 svm->vmcb->save.ds = vmcb12->save.ds;
466                 svm->vmcb->save.cpl = vmcb12->save.cpl;
467                 vmcb_mark_dirty(svm->vmcb, VMCB_SEG);
468         }
469
470         if (unlikely(new_vmcb12 || vmcb_is_dirty(vmcb12, VMCB_DT))) {
471                 svm->vmcb->save.gdtr = vmcb12->save.gdtr;
472                 svm->vmcb->save.idtr = vmcb12->save.idtr;
473                 vmcb_mark_dirty(svm->vmcb, VMCB_DT);
474         }
475
476         kvm_set_rflags(&svm->vcpu, vmcb12->save.rflags | X86_EFLAGS_FIXED);
477
478         /*
479          * Force-set EFER_SVME even though it is checked earlier on the
480          * VMCB12, because the guest can flip the bit between the check
481          * and now.  Clearing EFER_SVME would call svm_free_nested.
482          */
483         svm_set_efer(&svm->vcpu, vmcb12->save.efer | EFER_SVME);
484
485         svm_set_cr0(&svm->vcpu, vmcb12->save.cr0);
486         svm_set_cr4(&svm->vcpu, vmcb12->save.cr4);
487
488         svm->vcpu.arch.cr2 = vmcb12->save.cr2;
489
490         kvm_rax_write(&svm->vcpu, vmcb12->save.rax);
491         kvm_rsp_write(&svm->vcpu, vmcb12->save.rsp);
492         kvm_rip_write(&svm->vcpu, vmcb12->save.rip);
493
494         /* In case we don't even reach vcpu_run, the fields are not updated */
495         svm->vmcb->save.rax = vmcb12->save.rax;
496         svm->vmcb->save.rsp = vmcb12->save.rsp;
497         svm->vmcb->save.rip = vmcb12->save.rip;
498
499         /* These bits will be set properly on the first execution when new_vmc12 is true */
500         if (unlikely(new_vmcb12 || vmcb_is_dirty(vmcb12, VMCB_DR))) {
501                 svm->vmcb->save.dr7 = vmcb12->save.dr7 | DR7_FIXED_1;
502                 svm->vcpu.arch.dr6  = vmcb12->save.dr6 | DR6_ACTIVE_LOW;
503                 vmcb_mark_dirty(svm->vmcb, VMCB_DR);
504         }
505 }
506
507 static void nested_vmcb02_prepare_control(struct vcpu_svm *svm)
508 {
509         const u32 int_ctl_vmcb01_bits =
510                 V_INTR_MASKING_MASK | V_GIF_MASK | V_GIF_ENABLE_MASK;
511
512         const u32 int_ctl_vmcb12_bits = V_TPR_MASK | V_IRQ_INJECTION_BITS_MASK;
513
514         struct kvm_vcpu *vcpu = &svm->vcpu;
515
516         /*
517          * Filled at exit: exit_code, exit_code_hi, exit_info_1, exit_info_2,
518          * exit_int_info, exit_int_info_err, next_rip, insn_len, insn_bytes.
519          */
520
521         /*
522          * Also covers avic_vapic_bar, avic_backing_page, avic_logical_id,
523          * avic_physical_id.
524          */
525         WARN_ON(kvm_apicv_activated(svm->vcpu.kvm));
526
527         /* Copied from vmcb01.  msrpm_base can be overwritten later.  */
528         svm->vmcb->control.nested_ctl = svm->vmcb01.ptr->control.nested_ctl;
529         svm->vmcb->control.iopm_base_pa = svm->vmcb01.ptr->control.iopm_base_pa;
530         svm->vmcb->control.msrpm_base_pa = svm->vmcb01.ptr->control.msrpm_base_pa;
531
532         /* Done at vmrun: asid.  */
533
534         /* Also overwritten later if necessary.  */
535         svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
536
537         /* nested_cr3.  */
538         if (nested_npt_enabled(svm))
539                 nested_svm_init_mmu_context(vcpu);
540
541         svm->vmcb->control.tsc_offset = vcpu->arch.tsc_offset =
542                 vcpu->arch.l1_tsc_offset + svm->nested.ctl.tsc_offset;
543
544         svm->vmcb->control.int_ctl             =
545                 (svm->nested.ctl.int_ctl & int_ctl_vmcb12_bits) |
546                 (svm->vmcb01.ptr->control.int_ctl & int_ctl_vmcb01_bits);
547
548         svm->vmcb->control.int_vector          = svm->nested.ctl.int_vector;
549         svm->vmcb->control.int_state           = svm->nested.ctl.int_state;
550         svm->vmcb->control.event_inj           = svm->nested.ctl.event_inj;
551         svm->vmcb->control.event_inj_err       = svm->nested.ctl.event_inj_err;
552
553         svm->vmcb->control.pause_filter_count  = svm->nested.ctl.pause_filter_count;
554         svm->vmcb->control.pause_filter_thresh = svm->nested.ctl.pause_filter_thresh;
555
556         nested_svm_transition_tlb_flush(vcpu);
557
558         /* Enter Guest-Mode */
559         enter_guest_mode(vcpu);
560
561         /*
562          * Merge guest and host intercepts - must be called with vcpu in
563          * guest-mode to take effect.
564          */
565         recalc_intercepts(svm);
566 }
567
568 static void nested_svm_copy_common_state(struct vmcb *from_vmcb, struct vmcb *to_vmcb)
569 {
570         /*
571          * Some VMCB state is shared between L1 and L2 and thus has to be
572          * moved at the time of nested vmrun and vmexit.
573          *
574          * VMLOAD/VMSAVE state would also belong in this category, but KVM
575          * always performs VMLOAD and VMSAVE from the VMCB01.
576          */
577         to_vmcb->save.spec_ctrl = from_vmcb->save.spec_ctrl;
578 }
579
580 int enter_svm_guest_mode(struct kvm_vcpu *vcpu, u64 vmcb12_gpa,
581                          struct vmcb *vmcb12, bool from_vmrun)
582 {
583         struct vcpu_svm *svm = to_svm(vcpu);
584         int ret;
585
586         trace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb12_gpa,
587                                vmcb12->save.rip,
588                                vmcb12->control.int_ctl,
589                                vmcb12->control.event_inj,
590                                vmcb12->control.nested_ctl);
591
592         trace_kvm_nested_intercepts(vmcb12->control.intercepts[INTERCEPT_CR] & 0xffff,
593                                     vmcb12->control.intercepts[INTERCEPT_CR] >> 16,
594                                     vmcb12->control.intercepts[INTERCEPT_EXCEPTION],
595                                     vmcb12->control.intercepts[INTERCEPT_WORD3],
596                                     vmcb12->control.intercepts[INTERCEPT_WORD4],
597                                     vmcb12->control.intercepts[INTERCEPT_WORD5]);
598
599
600         svm->nested.vmcb12_gpa = vmcb12_gpa;
601
602         WARN_ON(svm->vmcb == svm->nested.vmcb02.ptr);
603
604         nested_svm_copy_common_state(svm->vmcb01.ptr, svm->nested.vmcb02.ptr);
605
606         svm_switch_vmcb(svm, &svm->nested.vmcb02);
607         nested_vmcb02_prepare_control(svm);
608         nested_vmcb02_prepare_save(svm, vmcb12);
609
610         ret = nested_svm_load_cr3(&svm->vcpu, vmcb12->save.cr3,
611                                   nested_npt_enabled(svm), from_vmrun);
612         if (ret)
613                 return ret;
614
615         if (!npt_enabled)
616                 vcpu->arch.mmu->inject_page_fault = svm_inject_page_fault_nested;
617
618         if (!from_vmrun)
619                 kvm_make_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu);
620
621         svm_set_gif(svm, true);
622
623         return 0;
624 }
625
626 int nested_svm_vmrun(struct kvm_vcpu *vcpu)
627 {
628         struct vcpu_svm *svm = to_svm(vcpu);
629         int ret;
630         struct vmcb *vmcb12;
631         struct kvm_host_map map;
632         u64 vmcb12_gpa;
633
634         if (!svm->nested.hsave_msr) {
635                 kvm_inject_gp(vcpu, 0);
636                 return 1;
637         }
638
639         if (is_smm(vcpu)) {
640                 kvm_queue_exception(vcpu, UD_VECTOR);
641                 return 1;
642         }
643
644         vmcb12_gpa = svm->vmcb->save.rax;
645         ret = kvm_vcpu_map(vcpu, gpa_to_gfn(vmcb12_gpa), &map);
646         if (ret == -EINVAL) {
647                 kvm_inject_gp(vcpu, 0);
648                 return 1;
649         } else if (ret) {
650                 return kvm_skip_emulated_instruction(vcpu);
651         }
652
653         ret = kvm_skip_emulated_instruction(vcpu);
654
655         vmcb12 = map.hva;
656
657         if (WARN_ON_ONCE(!svm->nested.initialized))
658                 return -EINVAL;
659
660         nested_load_control_from_vmcb12(svm, &vmcb12->control);
661
662         if (!nested_vmcb_valid_sregs(vcpu, &vmcb12->save) ||
663             !nested_vmcb_check_controls(vcpu, &svm->nested.ctl)) {
664                 vmcb12->control.exit_code    = SVM_EXIT_ERR;
665                 vmcb12->control.exit_code_hi = 0;
666                 vmcb12->control.exit_info_1  = 0;
667                 vmcb12->control.exit_info_2  = 0;
668                 goto out;
669         }
670
671         /*
672          * Since vmcb01 is not in use, we can use it to store some of the L1
673          * state.
674          */
675         svm->vmcb01.ptr->save.efer   = vcpu->arch.efer;
676         svm->vmcb01.ptr->save.cr0    = kvm_read_cr0(vcpu);
677         svm->vmcb01.ptr->save.cr4    = vcpu->arch.cr4;
678         svm->vmcb01.ptr->save.rflags = kvm_get_rflags(vcpu);
679         svm->vmcb01.ptr->save.rip    = kvm_rip_read(vcpu);
680
681         if (!npt_enabled)
682                 svm->vmcb01.ptr->save.cr3 = kvm_read_cr3(vcpu);
683
684         svm->nested.nested_run_pending = 1;
685
686         if (enter_svm_guest_mode(vcpu, vmcb12_gpa, vmcb12, true))
687                 goto out_exit_err;
688
689         if (nested_svm_vmrun_msrpm(svm))
690                 goto out;
691
692 out_exit_err:
693         svm->nested.nested_run_pending = 0;
694
695         svm->vmcb->control.exit_code    = SVM_EXIT_ERR;
696         svm->vmcb->control.exit_code_hi = 0;
697         svm->vmcb->control.exit_info_1  = 0;
698         svm->vmcb->control.exit_info_2  = 0;
699
700         nested_svm_vmexit(svm);
701
702 out:
703         kvm_vcpu_unmap(vcpu, &map, true);
704
705         return ret;
706 }
707
708 /* Copy state save area fields which are handled by VMRUN */
709 void svm_copy_vmrun_state(struct vmcb_save_area *to_save,
710                           struct vmcb_save_area *from_save)
711 {
712         to_save->es = from_save->es;
713         to_save->cs = from_save->cs;
714         to_save->ss = from_save->ss;
715         to_save->ds = from_save->ds;
716         to_save->gdtr = from_save->gdtr;
717         to_save->idtr = from_save->idtr;
718         to_save->rflags = from_save->rflags | X86_EFLAGS_FIXED;
719         to_save->efer = from_save->efer;
720         to_save->cr0 = from_save->cr0;
721         to_save->cr3 = from_save->cr3;
722         to_save->cr4 = from_save->cr4;
723         to_save->rax = from_save->rax;
724         to_save->rsp = from_save->rsp;
725         to_save->rip = from_save->rip;
726         to_save->cpl = 0;
727 }
728
729 void svm_copy_vmloadsave_state(struct vmcb *to_vmcb, struct vmcb *from_vmcb)
730 {
731         to_vmcb->save.fs = from_vmcb->save.fs;
732         to_vmcb->save.gs = from_vmcb->save.gs;
733         to_vmcb->save.tr = from_vmcb->save.tr;
734         to_vmcb->save.ldtr = from_vmcb->save.ldtr;
735         to_vmcb->save.kernel_gs_base = from_vmcb->save.kernel_gs_base;
736         to_vmcb->save.star = from_vmcb->save.star;
737         to_vmcb->save.lstar = from_vmcb->save.lstar;
738         to_vmcb->save.cstar = from_vmcb->save.cstar;
739         to_vmcb->save.sfmask = from_vmcb->save.sfmask;
740         to_vmcb->save.sysenter_cs = from_vmcb->save.sysenter_cs;
741         to_vmcb->save.sysenter_esp = from_vmcb->save.sysenter_esp;
742         to_vmcb->save.sysenter_eip = from_vmcb->save.sysenter_eip;
743 }
744
745 int nested_svm_vmexit(struct vcpu_svm *svm)
746 {
747         struct kvm_vcpu *vcpu = &svm->vcpu;
748         struct vmcb *vmcb12;
749         struct vmcb *vmcb = svm->vmcb;
750         struct kvm_host_map map;
751         int rc;
752
753         /* Triple faults in L2 should never escape. */
754         WARN_ON_ONCE(kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu));
755
756         rc = kvm_vcpu_map(vcpu, gpa_to_gfn(svm->nested.vmcb12_gpa), &map);
757         if (rc) {
758                 if (rc == -EINVAL)
759                         kvm_inject_gp(vcpu, 0);
760                 return 1;
761         }
762
763         vmcb12 = map.hva;
764
765         /* Exit Guest-Mode */
766         leave_guest_mode(vcpu);
767         svm->nested.vmcb12_gpa = 0;
768         WARN_ON_ONCE(svm->nested.nested_run_pending);
769
770         kvm_clear_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu);
771
772         /* in case we halted in L2 */
773         svm->vcpu.arch.mp_state = KVM_MP_STATE_RUNNABLE;
774
775         /* Give the current vmcb to the guest */
776
777         vmcb12->save.es     = vmcb->save.es;
778         vmcb12->save.cs     = vmcb->save.cs;
779         vmcb12->save.ss     = vmcb->save.ss;
780         vmcb12->save.ds     = vmcb->save.ds;
781         vmcb12->save.gdtr   = vmcb->save.gdtr;
782         vmcb12->save.idtr   = vmcb->save.idtr;
783         vmcb12->save.efer   = svm->vcpu.arch.efer;
784         vmcb12->save.cr0    = kvm_read_cr0(vcpu);
785         vmcb12->save.cr3    = kvm_read_cr3(vcpu);
786         vmcb12->save.cr2    = vmcb->save.cr2;
787         vmcb12->save.cr4    = svm->vcpu.arch.cr4;
788         vmcb12->save.rflags = kvm_get_rflags(vcpu);
789         vmcb12->save.rip    = kvm_rip_read(vcpu);
790         vmcb12->save.rsp    = kvm_rsp_read(vcpu);
791         vmcb12->save.rax    = kvm_rax_read(vcpu);
792         vmcb12->save.dr7    = vmcb->save.dr7;
793         vmcb12->save.dr6    = svm->vcpu.arch.dr6;
794         vmcb12->save.cpl    = vmcb->save.cpl;
795
796         vmcb12->control.int_state         = vmcb->control.int_state;
797         vmcb12->control.exit_code         = vmcb->control.exit_code;
798         vmcb12->control.exit_code_hi      = vmcb->control.exit_code_hi;
799         vmcb12->control.exit_info_1       = vmcb->control.exit_info_1;
800         vmcb12->control.exit_info_2       = vmcb->control.exit_info_2;
801
802         if (vmcb12->control.exit_code != SVM_EXIT_ERR)
803                 nested_save_pending_event_to_vmcb12(svm, vmcb12);
804
805         if (svm->nrips_enabled)
806                 vmcb12->control.next_rip  = vmcb->control.next_rip;
807
808         vmcb12->control.int_ctl           = svm->nested.ctl.int_ctl;
809         vmcb12->control.tlb_ctl           = svm->nested.ctl.tlb_ctl;
810         vmcb12->control.event_inj         = svm->nested.ctl.event_inj;
811         vmcb12->control.event_inj_err     = svm->nested.ctl.event_inj_err;
812
813         vmcb12->control.pause_filter_count =
814                 svm->vmcb->control.pause_filter_count;
815         vmcb12->control.pause_filter_thresh =
816                 svm->vmcb->control.pause_filter_thresh;
817
818         nested_svm_copy_common_state(svm->nested.vmcb02.ptr, svm->vmcb01.ptr);
819
820         svm_switch_vmcb(svm, &svm->vmcb01);
821
822         /*
823          * On vmexit the  GIF is set to false and
824          * no event can be injected in L1.
825          */
826         svm_set_gif(svm, false);
827         svm->vmcb->control.exit_int_info = 0;
828
829         svm->vcpu.arch.tsc_offset = svm->vcpu.arch.l1_tsc_offset;
830         if (svm->vmcb->control.tsc_offset != svm->vcpu.arch.tsc_offset) {
831                 svm->vmcb->control.tsc_offset = svm->vcpu.arch.tsc_offset;
832                 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
833         }
834
835         svm->nested.ctl.nested_cr3 = 0;
836
837         /*
838          * Restore processor state that had been saved in vmcb01
839          */
840         kvm_set_rflags(vcpu, svm->vmcb->save.rflags);
841         svm_set_efer(vcpu, svm->vmcb->save.efer);
842         svm_set_cr0(vcpu, svm->vmcb->save.cr0 | X86_CR0_PE);
843         svm_set_cr4(vcpu, svm->vmcb->save.cr4);
844         kvm_rax_write(vcpu, svm->vmcb->save.rax);
845         kvm_rsp_write(vcpu, svm->vmcb->save.rsp);
846         kvm_rip_write(vcpu, svm->vmcb->save.rip);
847
848         svm->vcpu.arch.dr7 = DR7_FIXED_1;
849         kvm_update_dr7(&svm->vcpu);
850
851         trace_kvm_nested_vmexit_inject(vmcb12->control.exit_code,
852                                        vmcb12->control.exit_info_1,
853                                        vmcb12->control.exit_info_2,
854                                        vmcb12->control.exit_int_info,
855                                        vmcb12->control.exit_int_info_err,
856                                        KVM_ISA_SVM);
857
858         kvm_vcpu_unmap(vcpu, &map, true);
859
860         nested_svm_transition_tlb_flush(vcpu);
861
862         nested_svm_uninit_mmu_context(vcpu);
863
864         rc = nested_svm_load_cr3(vcpu, svm->vmcb->save.cr3, false, true);
865         if (rc)
866                 return 1;
867
868         /*
869          * Drop what we picked up for L2 via svm_complete_interrupts() so it
870          * doesn't end up in L1.
871          */
872         svm->vcpu.arch.nmi_injected = false;
873         kvm_clear_exception_queue(vcpu);
874         kvm_clear_interrupt_queue(vcpu);
875
876         /*
877          * If we are here following the completion of a VMRUN that
878          * is being single-stepped, queue the pending #DB intercept
879          * right now so that it an be accounted for before we execute
880          * L1's next instruction.
881          */
882         if (unlikely(svm->vmcb->save.rflags & X86_EFLAGS_TF))
883                 kvm_queue_exception(&(svm->vcpu), DB_VECTOR);
884
885         return 0;
886 }
887
888 static void nested_svm_triple_fault(struct kvm_vcpu *vcpu)
889 {
890         nested_svm_simple_vmexit(to_svm(vcpu), SVM_EXIT_SHUTDOWN);
891 }
892
893 int svm_allocate_nested(struct vcpu_svm *svm)
894 {
895         struct page *vmcb02_page;
896
897         if (svm->nested.initialized)
898                 return 0;
899
900         vmcb02_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
901         if (!vmcb02_page)
902                 return -ENOMEM;
903         svm->nested.vmcb02.ptr = page_address(vmcb02_page);
904         svm->nested.vmcb02.pa = __sme_set(page_to_pfn(vmcb02_page) << PAGE_SHIFT);
905
906         svm->nested.msrpm = svm_vcpu_alloc_msrpm();
907         if (!svm->nested.msrpm)
908                 goto err_free_vmcb02;
909         svm_vcpu_init_msrpm(&svm->vcpu, svm->nested.msrpm);
910
911         svm->nested.initialized = true;
912         return 0;
913
914 err_free_vmcb02:
915         __free_page(vmcb02_page);
916         return -ENOMEM;
917 }
918
919 void svm_free_nested(struct vcpu_svm *svm)
920 {
921         if (!svm->nested.initialized)
922                 return;
923
924         svm_vcpu_free_msrpm(svm->nested.msrpm);
925         svm->nested.msrpm = NULL;
926
927         __free_page(virt_to_page(svm->nested.vmcb02.ptr));
928         svm->nested.vmcb02.ptr = NULL;
929
930         /*
931          * When last_vmcb12_gpa matches the current vmcb12 gpa,
932          * some vmcb12 fields are not loaded if they are marked clean
933          * in the vmcb12, since in this case they are up to date already.
934          *
935          * When the vmcb02 is freed, this optimization becomes invalid.
936          */
937         svm->nested.last_vmcb12_gpa = INVALID_GPA;
938
939         svm->nested.initialized = false;
940 }
941
942 /*
943  * Forcibly leave nested mode in order to be able to reset the VCPU later on.
944  */
945 void svm_leave_nested(struct vcpu_svm *svm)
946 {
947         struct kvm_vcpu *vcpu = &svm->vcpu;
948
949         if (is_guest_mode(vcpu)) {
950                 svm->nested.nested_run_pending = 0;
951                 svm->nested.vmcb12_gpa = INVALID_GPA;
952
953                 leave_guest_mode(vcpu);
954
955                 svm_switch_vmcb(svm, &svm->vmcb01);
956
957                 nested_svm_uninit_mmu_context(vcpu);
958                 vmcb_mark_all_dirty(svm->vmcb);
959         }
960
961         kvm_clear_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu);
962 }
963
964 static int nested_svm_exit_handled_msr(struct vcpu_svm *svm)
965 {
966         u32 offset, msr, value;
967         int write, mask;
968
969         if (!(vmcb_is_intercept(&svm->nested.ctl, INTERCEPT_MSR_PROT)))
970                 return NESTED_EXIT_HOST;
971
972         msr    = svm->vcpu.arch.regs[VCPU_REGS_RCX];
973         offset = svm_msrpm_offset(msr);
974         write  = svm->vmcb->control.exit_info_1 & 1;
975         mask   = 1 << ((2 * (msr & 0xf)) + write);
976
977         if (offset == MSR_INVALID)
978                 return NESTED_EXIT_DONE;
979
980         /* Offset is in 32 bit units but need in 8 bit units */
981         offset *= 4;
982
983         if (kvm_vcpu_read_guest(&svm->vcpu, svm->nested.ctl.msrpm_base_pa + offset, &value, 4))
984                 return NESTED_EXIT_DONE;
985
986         return (value & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
987 }
988
989 static int nested_svm_intercept_ioio(struct vcpu_svm *svm)
990 {
991         unsigned port, size, iopm_len;
992         u16 val, mask;
993         u8 start_bit;
994         u64 gpa;
995
996         if (!(vmcb_is_intercept(&svm->nested.ctl, INTERCEPT_IOIO_PROT)))
997                 return NESTED_EXIT_HOST;
998
999         port = svm->vmcb->control.exit_info_1 >> 16;
1000         size = (svm->vmcb->control.exit_info_1 & SVM_IOIO_SIZE_MASK) >>
1001                 SVM_IOIO_SIZE_SHIFT;
1002         gpa  = svm->nested.ctl.iopm_base_pa + (port / 8);
1003         start_bit = port % 8;
1004         iopm_len = (start_bit + size > 8) ? 2 : 1;
1005         mask = (0xf >> (4 - size)) << start_bit;
1006         val = 0;
1007
1008         if (kvm_vcpu_read_guest(&svm->vcpu, gpa, &val, iopm_len))
1009                 return NESTED_EXIT_DONE;
1010
1011         return (val & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
1012 }
1013
1014 static int nested_svm_intercept(struct vcpu_svm *svm)
1015 {
1016         u32 exit_code = svm->vmcb->control.exit_code;
1017         int vmexit = NESTED_EXIT_HOST;
1018
1019         switch (exit_code) {
1020         case SVM_EXIT_MSR:
1021                 vmexit = nested_svm_exit_handled_msr(svm);
1022                 break;
1023         case SVM_EXIT_IOIO:
1024                 vmexit = nested_svm_intercept_ioio(svm);
1025                 break;
1026         case SVM_EXIT_READ_CR0 ... SVM_EXIT_WRITE_CR8: {
1027                 if (vmcb_is_intercept(&svm->nested.ctl, exit_code))
1028                         vmexit = NESTED_EXIT_DONE;
1029                 break;
1030         }
1031         case SVM_EXIT_READ_DR0 ... SVM_EXIT_WRITE_DR7: {
1032                 if (vmcb_is_intercept(&svm->nested.ctl, exit_code))
1033                         vmexit = NESTED_EXIT_DONE;
1034                 break;
1035         }
1036         case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
1037                 /*
1038                  * Host-intercepted exceptions have been checked already in
1039                  * nested_svm_exit_special.  There is nothing to do here,
1040                  * the vmexit is injected by svm_check_nested_events.
1041                  */
1042                 vmexit = NESTED_EXIT_DONE;
1043                 break;
1044         }
1045         case SVM_EXIT_ERR: {
1046                 vmexit = NESTED_EXIT_DONE;
1047                 break;
1048         }
1049         default: {
1050                 if (vmcb_is_intercept(&svm->nested.ctl, exit_code))
1051                         vmexit = NESTED_EXIT_DONE;
1052         }
1053         }
1054
1055         return vmexit;
1056 }
1057
1058 int nested_svm_exit_handled(struct vcpu_svm *svm)
1059 {
1060         int vmexit;
1061
1062         vmexit = nested_svm_intercept(svm);
1063
1064         if (vmexit == NESTED_EXIT_DONE)
1065                 nested_svm_vmexit(svm);
1066
1067         return vmexit;
1068 }
1069
1070 int nested_svm_check_permissions(struct kvm_vcpu *vcpu)
1071 {
1072         if (!(vcpu->arch.efer & EFER_SVME) || !is_paging(vcpu)) {
1073                 kvm_queue_exception(vcpu, UD_VECTOR);
1074                 return 1;
1075         }
1076
1077         if (to_svm(vcpu)->vmcb->save.cpl) {
1078                 kvm_inject_gp(vcpu, 0);
1079                 return 1;
1080         }
1081
1082         return 0;
1083 }
1084
1085 static bool nested_exit_on_exception(struct vcpu_svm *svm)
1086 {
1087         unsigned int nr = svm->vcpu.arch.exception.nr;
1088
1089         return (svm->nested.ctl.intercepts[INTERCEPT_EXCEPTION] & BIT(nr));
1090 }
1091
1092 static void nested_svm_inject_exception_vmexit(struct vcpu_svm *svm)
1093 {
1094         unsigned int nr = svm->vcpu.arch.exception.nr;
1095
1096         svm->vmcb->control.exit_code = SVM_EXIT_EXCP_BASE + nr;
1097         svm->vmcb->control.exit_code_hi = 0;
1098
1099         if (svm->vcpu.arch.exception.has_error_code)
1100                 svm->vmcb->control.exit_info_1 = svm->vcpu.arch.exception.error_code;
1101
1102         /*
1103          * EXITINFO2 is undefined for all exception intercepts other
1104          * than #PF.
1105          */
1106         if (nr == PF_VECTOR) {
1107                 if (svm->vcpu.arch.exception.nested_apf)
1108                         svm->vmcb->control.exit_info_2 = svm->vcpu.arch.apf.nested_apf_token;
1109                 else if (svm->vcpu.arch.exception.has_payload)
1110                         svm->vmcb->control.exit_info_2 = svm->vcpu.arch.exception.payload;
1111                 else
1112                         svm->vmcb->control.exit_info_2 = svm->vcpu.arch.cr2;
1113         } else if (nr == DB_VECTOR) {
1114                 /* See inject_pending_event.  */
1115                 kvm_deliver_exception_payload(&svm->vcpu);
1116                 if (svm->vcpu.arch.dr7 & DR7_GD) {
1117                         svm->vcpu.arch.dr7 &= ~DR7_GD;
1118                         kvm_update_dr7(&svm->vcpu);
1119                 }
1120         } else
1121                 WARN_ON(svm->vcpu.arch.exception.has_payload);
1122
1123         nested_svm_vmexit(svm);
1124 }
1125
1126 static inline bool nested_exit_on_init(struct vcpu_svm *svm)
1127 {
1128         return vmcb_is_intercept(&svm->nested.ctl, INTERCEPT_INIT);
1129 }
1130
1131 static int svm_check_nested_events(struct kvm_vcpu *vcpu)
1132 {
1133         struct vcpu_svm *svm = to_svm(vcpu);
1134         bool block_nested_events =
1135                 kvm_event_needs_reinjection(vcpu) || svm->nested.nested_run_pending;
1136         struct kvm_lapic *apic = vcpu->arch.apic;
1137
1138         if (lapic_in_kernel(vcpu) &&
1139             test_bit(KVM_APIC_INIT, &apic->pending_events)) {
1140                 if (block_nested_events)
1141                         return -EBUSY;
1142                 if (!nested_exit_on_init(svm))
1143                         return 0;
1144                 nested_svm_simple_vmexit(svm, SVM_EXIT_INIT);
1145                 return 0;
1146         }
1147
1148         if (vcpu->arch.exception.pending) {
1149                 /*
1150                  * Only a pending nested run can block a pending exception.
1151                  * Otherwise an injected NMI/interrupt should either be
1152                  * lost or delivered to the nested hypervisor in the EXITINTINFO
1153                  * vmcb field, while delivering the pending exception.
1154                  */
1155                 if (svm->nested.nested_run_pending)
1156                         return -EBUSY;
1157                 if (!nested_exit_on_exception(svm))
1158                         return 0;
1159                 nested_svm_inject_exception_vmexit(svm);
1160                 return 0;
1161         }
1162
1163         if (vcpu->arch.smi_pending && !svm_smi_blocked(vcpu)) {
1164                 if (block_nested_events)
1165                         return -EBUSY;
1166                 if (!nested_exit_on_smi(svm))
1167                         return 0;
1168                 nested_svm_simple_vmexit(svm, SVM_EXIT_SMI);
1169                 return 0;
1170         }
1171
1172         if (vcpu->arch.nmi_pending && !svm_nmi_blocked(vcpu)) {
1173                 if (block_nested_events)
1174                         return -EBUSY;
1175                 if (!nested_exit_on_nmi(svm))
1176                         return 0;
1177                 nested_svm_simple_vmexit(svm, SVM_EXIT_NMI);
1178                 return 0;
1179         }
1180
1181         if (kvm_cpu_has_interrupt(vcpu) && !svm_interrupt_blocked(vcpu)) {
1182                 if (block_nested_events)
1183                         return -EBUSY;
1184                 if (!nested_exit_on_intr(svm))
1185                         return 0;
1186                 trace_kvm_nested_intr_vmexit(svm->vmcb->save.rip);
1187                 nested_svm_simple_vmexit(svm, SVM_EXIT_INTR);
1188                 return 0;
1189         }
1190
1191         return 0;
1192 }
1193
1194 int nested_svm_exit_special(struct vcpu_svm *svm)
1195 {
1196         u32 exit_code = svm->vmcb->control.exit_code;
1197
1198         switch (exit_code) {
1199         case SVM_EXIT_INTR:
1200         case SVM_EXIT_NMI:
1201         case SVM_EXIT_NPF:
1202                 return NESTED_EXIT_HOST;
1203         case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
1204                 u32 excp_bits = 1 << (exit_code - SVM_EXIT_EXCP_BASE);
1205
1206                 if (svm->vmcb01.ptr->control.intercepts[INTERCEPT_EXCEPTION] &
1207                     excp_bits)
1208                         return NESTED_EXIT_HOST;
1209                 else if (exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR &&
1210                          svm->vcpu.arch.apf.host_apf_flags)
1211                         /* Trap async PF even if not shadowing */
1212                         return NESTED_EXIT_HOST;
1213                 break;
1214         }
1215         default:
1216                 break;
1217         }
1218
1219         return NESTED_EXIT_CONTINUE;
1220 }
1221
1222 static int svm_get_nested_state(struct kvm_vcpu *vcpu,
1223                                 struct kvm_nested_state __user *user_kvm_nested_state,
1224                                 u32 user_data_size)
1225 {
1226         struct vcpu_svm *svm;
1227         struct kvm_nested_state kvm_state = {
1228                 .flags = 0,
1229                 .format = KVM_STATE_NESTED_FORMAT_SVM,
1230                 .size = sizeof(kvm_state),
1231         };
1232         struct vmcb __user *user_vmcb = (struct vmcb __user *)
1233                 &user_kvm_nested_state->data.svm[0];
1234
1235         if (!vcpu)
1236                 return kvm_state.size + KVM_STATE_NESTED_SVM_VMCB_SIZE;
1237
1238         svm = to_svm(vcpu);
1239
1240         if (user_data_size < kvm_state.size)
1241                 goto out;
1242
1243         /* First fill in the header and copy it out.  */
1244         if (is_guest_mode(vcpu)) {
1245                 kvm_state.hdr.svm.vmcb_pa = svm->nested.vmcb12_gpa;
1246                 kvm_state.size += KVM_STATE_NESTED_SVM_VMCB_SIZE;
1247                 kvm_state.flags |= KVM_STATE_NESTED_GUEST_MODE;
1248
1249                 if (svm->nested.nested_run_pending)
1250                         kvm_state.flags |= KVM_STATE_NESTED_RUN_PENDING;
1251         }
1252
1253         if (gif_set(svm))
1254                 kvm_state.flags |= KVM_STATE_NESTED_GIF_SET;
1255
1256         if (copy_to_user(user_kvm_nested_state, &kvm_state, sizeof(kvm_state)))
1257                 return -EFAULT;
1258
1259         if (!is_guest_mode(vcpu))
1260                 goto out;
1261
1262         /*
1263          * Copy over the full size of the VMCB rather than just the size
1264          * of the structs.
1265          */
1266         if (clear_user(user_vmcb, KVM_STATE_NESTED_SVM_VMCB_SIZE))
1267                 return -EFAULT;
1268         if (copy_to_user(&user_vmcb->control, &svm->nested.ctl,
1269                          sizeof(user_vmcb->control)))
1270                 return -EFAULT;
1271         if (copy_to_user(&user_vmcb->save, &svm->vmcb01.ptr->save,
1272                          sizeof(user_vmcb->save)))
1273                 return -EFAULT;
1274 out:
1275         return kvm_state.size;
1276 }
1277
1278 static int svm_set_nested_state(struct kvm_vcpu *vcpu,
1279                                 struct kvm_nested_state __user *user_kvm_nested_state,
1280                                 struct kvm_nested_state *kvm_state)
1281 {
1282         struct vcpu_svm *svm = to_svm(vcpu);
1283         struct vmcb __user *user_vmcb = (struct vmcb __user *)
1284                 &user_kvm_nested_state->data.svm[0];
1285         struct vmcb_control_area *ctl;
1286         struct vmcb_save_area *save;
1287         unsigned long cr0;
1288         int ret;
1289
1290         BUILD_BUG_ON(sizeof(struct vmcb_control_area) + sizeof(struct vmcb_save_area) >
1291                      KVM_STATE_NESTED_SVM_VMCB_SIZE);
1292
1293         if (kvm_state->format != KVM_STATE_NESTED_FORMAT_SVM)
1294                 return -EINVAL;
1295
1296         if (kvm_state->flags & ~(KVM_STATE_NESTED_GUEST_MODE |
1297                                  KVM_STATE_NESTED_RUN_PENDING |
1298                                  KVM_STATE_NESTED_GIF_SET))
1299                 return -EINVAL;
1300
1301         /*
1302          * If in guest mode, vcpu->arch.efer actually refers to the L2 guest's
1303          * EFER.SVME, but EFER.SVME still has to be 1 for VMRUN to succeed.
1304          */
1305         if (!(vcpu->arch.efer & EFER_SVME)) {
1306                 /* GIF=1 and no guest mode are required if SVME=0.  */
1307                 if (kvm_state->flags != KVM_STATE_NESTED_GIF_SET)
1308                         return -EINVAL;
1309         }
1310
1311         /* SMM temporarily disables SVM, so we cannot be in guest mode.  */
1312         if (is_smm(vcpu) && (kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
1313                 return -EINVAL;
1314
1315         if (!(kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE)) {
1316                 svm_leave_nested(svm);
1317                 svm_set_gif(svm, !!(kvm_state->flags & KVM_STATE_NESTED_GIF_SET));
1318                 return 0;
1319         }
1320
1321         if (!page_address_valid(vcpu, kvm_state->hdr.svm.vmcb_pa))
1322                 return -EINVAL;
1323         if (kvm_state->size < sizeof(*kvm_state) + KVM_STATE_NESTED_SVM_VMCB_SIZE)
1324                 return -EINVAL;
1325
1326         ret  = -ENOMEM;
1327         ctl  = kzalloc(sizeof(*ctl),  GFP_KERNEL_ACCOUNT);
1328         save = kzalloc(sizeof(*save), GFP_KERNEL_ACCOUNT);
1329         if (!ctl || !save)
1330                 goto out_free;
1331
1332         ret = -EFAULT;
1333         if (copy_from_user(ctl, &user_vmcb->control, sizeof(*ctl)))
1334                 goto out_free;
1335         if (copy_from_user(save, &user_vmcb->save, sizeof(*save)))
1336                 goto out_free;
1337
1338         ret = -EINVAL;
1339         if (!nested_vmcb_check_controls(vcpu, ctl))
1340                 goto out_free;
1341
1342         /*
1343          * Processor state contains L2 state.  Check that it is
1344          * valid for guest mode (see nested_vmcb_check_save).
1345          */
1346         cr0 = kvm_read_cr0(vcpu);
1347         if (((cr0 & X86_CR0_CD) == 0) && (cr0 & X86_CR0_NW))
1348                 goto out_free;
1349
1350         /*
1351          * Validate host state saved from before VMRUN (see
1352          * nested_svm_check_permissions).
1353          */
1354         if (!(save->cr0 & X86_CR0_PG) ||
1355             !(save->cr0 & X86_CR0_PE) ||
1356             (save->rflags & X86_EFLAGS_VM) ||
1357             !nested_vmcb_valid_sregs(vcpu, save))
1358                 goto out_free;
1359
1360         /*
1361          * While the nested guest CR3 is already checked and set by
1362          * KVM_SET_SREGS, it was set when nested state was yet loaded,
1363          * thus MMU might not be initialized correctly.
1364          * Set it again to fix this.
1365          */
1366
1367         ret = nested_svm_load_cr3(&svm->vcpu, vcpu->arch.cr3,
1368                                   nested_npt_enabled(svm), false);
1369         if (WARN_ON_ONCE(ret))
1370                 goto out_free;
1371
1372
1373         /*
1374          * All checks done, we can enter guest mode. Userspace provides
1375          * vmcb12.control, which will be combined with L1 and stored into
1376          * vmcb02, and the L1 save state which we store in vmcb01.
1377          * L2 registers if needed are moved from the current VMCB to VMCB02.
1378          */
1379
1380         if (is_guest_mode(vcpu))
1381                 svm_leave_nested(svm);
1382         else
1383                 svm->nested.vmcb02.ptr->save = svm->vmcb01.ptr->save;
1384
1385         svm_set_gif(svm, !!(kvm_state->flags & KVM_STATE_NESTED_GIF_SET));
1386
1387         svm->nested.nested_run_pending =
1388                 !!(kvm_state->flags & KVM_STATE_NESTED_RUN_PENDING);
1389
1390         svm->nested.vmcb12_gpa = kvm_state->hdr.svm.vmcb_pa;
1391
1392         svm_copy_vmrun_state(&svm->vmcb01.ptr->save, save);
1393         nested_load_control_from_vmcb12(svm, ctl);
1394
1395         svm_switch_vmcb(svm, &svm->nested.vmcb02);
1396         nested_vmcb02_prepare_control(svm);
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         .check_events = svm_check_nested_events,
1436         .triple_fault = nested_svm_triple_fault,
1437         .get_nested_state_pages = svm_get_nested_state_pages,
1438         .get_state = svm_get_nested_state,
1439         .set_state = svm_set_nested_state,
1440 };