VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR0/HMSVMR0.cpp@ 72786

Last change on this file since 72786 was 72786, checked in by vboxsync, 6 years ago

HM: doxygen fixes

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 318.2 KB
Line 
1/* $Id: HMSVMR0.cpp 72786 2018-07-02 08:54:12Z vboxsync $ */
2/** @file
3 * HM SVM (AMD-V) - Host Context Ring-0.
4 */
5
6/*
7 * Copyright (C) 2013-2017 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_HM
23#define VMCPU_INCL_CPUM_GST_CTX
24#include <iprt/asm-amd64-x86.h>
25#include <iprt/thread.h>
26
27#include <VBox/vmm/pdmapi.h>
28#include <VBox/vmm/dbgf.h>
29#include <VBox/vmm/iem.h>
30#include <VBox/vmm/iom.h>
31#include <VBox/vmm/tm.h>
32#include <VBox/vmm/gim.h>
33#include <VBox/vmm/apic.h>
34#include "HMInternal.h"
35#include <VBox/vmm/vm.h>
36#include "HMSVMR0.h"
37#include "dtrace/VBoxVMM.h"
38
39#ifdef DEBUG_ramshankar
40# define HMSVM_SYNC_FULL_GUEST_STATE
41# define HMSVM_SYNC_FULL_NESTED_GUEST_STATE
42# define HMSVM_ALWAYS_TRAP_ALL_XCPTS
43# define HMSVM_ALWAYS_TRAP_PF
44# define HMSVM_ALWAYS_TRAP_TASK_SWITCH
45#endif
46
47
48/*********************************************************************************************************************************
49* Defined Constants And Macros *
50*********************************************************************************************************************************/
51#ifdef VBOX_WITH_STATISTICS
52# define HMSVM_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { \
53 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll); \
54 if ((u64ExitCode) == SVM_EXIT_NPF) \
55 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitReasonNpf); \
56 else \
57 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[(u64ExitCode) & MASK_EXITREASON_STAT]); \
58 } while (0)
59
60# ifdef VBOX_WITH_NESTED_HWVIRT_SVM
61# define HMSVM_NESTED_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { \
62 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll); \
63 if ((u64ExitCode) == SVM_EXIT_NPF) \
64 STAM_COUNTER_INC(&pVCpu->hm.s.StatNestedExitReasonNpf); \
65 else \
66 STAM_COUNTER_INC(&pVCpu->hm.s.paStatNestedExitReasonR0[(u64ExitCode) & MASK_EXITREASON_STAT]); \
67 } while (0)
68# endif
69#else
70# define HMSVM_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { } while (0)
71# ifdef VBOX_WITH_NESTED_HWVIRT_SVM
72# define HMSVM_NESTED_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { } while (0)
73# endif
74#endif /* !VBOX_WITH_STATISTICS */
75
76
77/** If we decide to use a function table approach this can be useful to
78 * switch to a "static DECLCALLBACK(int)". */
79#define HMSVM_EXIT_DECL static int
80
81/**
82 * Subset of the guest-CPU state that is kept by SVM R0 code while executing the
83 * guest using hardware-assisted SVM.
84 *
85 * This excludes state like TSC AUX, GPRs (other than RSP, RAX) which are always
86 * are swapped and restored across the world-switch and also registers like
87 * EFER, PAT MSR etc. which cannot be modified by the guest without causing a
88 * \#VMEXIT.
89 */
90#define HMSVM_CPUMCTX_EXTRN_ALL ( CPUMCTX_EXTRN_RIP \
91 | CPUMCTX_EXTRN_RFLAGS \
92 | CPUMCTX_EXTRN_RAX \
93 | CPUMCTX_EXTRN_RSP \
94 | CPUMCTX_EXTRN_SREG_MASK \
95 | CPUMCTX_EXTRN_CR0 \
96 | CPUMCTX_EXTRN_CR2 \
97 | CPUMCTX_EXTRN_CR3 \
98 | CPUMCTX_EXTRN_TABLE_MASK \
99 | CPUMCTX_EXTRN_DR6 \
100 | CPUMCTX_EXTRN_DR7 \
101 | CPUMCTX_EXTRN_KERNEL_GS_BASE \
102 | CPUMCTX_EXTRN_SYSCALL_MSRS \
103 | CPUMCTX_EXTRN_SYSENTER_MSRS \
104 | CPUMCTX_EXTRN_HWVIRT \
105 | CPUMCTX_EXTRN_HM_SVM_MASK)
106
107/**
108 * Subset of the guest-CPU state that is shared between the guest and host.
109 */
110#define HMSVM_CPUMCTX_SHARED_STATE CPUMCTX_EXTRN_DR_MASK
111
112/** Macro for importing guest state from the VMCB back into CPUMCTX. */
113#define HMSVM_CPUMCTX_IMPORT_STATE(a_pVCpu, a_fWhat) \
114 do { \
115 if ((a_pVCpu)->cpum.GstCtx.fExtrn & (a_fWhat)) \
116 hmR0SvmImportGuestState((a_pVCpu), (a_fWhat)); \
117 } while (0)
118
119/** Assert that the required state bits are fetched. */
120#define HMSVM_CPUMCTX_ASSERT(a_pVCpu, a_fExtrnMbz) AssertMsg(!((a_pVCpu)->cpum.GstCtx.fExtrn & (a_fExtrnMbz)), \
121 ("fExtrn=%#RX64 fExtrnMbz=%#RX64\n", \
122 (a_pVCpu)->cpum.GstCtx.fExtrn, (a_fExtrnMbz)))
123
124/** Macro for checking and returning from the using function for
125 * \#VMEXIT intercepts that maybe caused during delivering of another
126 * event in the guest. */
127#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
128# define HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY() \
129 do \
130 { \
131 int rc = hmR0SvmCheckExitDueToEventDelivery(pVCpu, pCtx, pSvmTransient); \
132 if (RT_LIKELY(rc == VINF_SUCCESS)) { /* continue #VMEXIT handling */ } \
133 else if ( rc == VINF_HM_DOUBLE_FAULT) { return VINF_SUCCESS; } \
134 else if ( rc == VINF_EM_RESET \
135 && CPUMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_SHUTDOWN)) \
136 { \
137 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, IEM_CPUMCTX_EXTRN_SVM_VMEXIT_MASK); \
138 return VBOXSTRICTRC_TODO(IEMExecSvmVmexit(pVCpu, SVM_EXIT_SHUTDOWN, 0, 0)); \
139 } \
140 else \
141 return rc; \
142 } while (0)
143#else
144# define HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY() \
145 do \
146 { \
147 int rc = hmR0SvmCheckExitDueToEventDelivery(pVCpu, pCtx, pSvmTransient); \
148 if (RT_LIKELY(rc == VINF_SUCCESS)) { /* continue #VMEXIT handling */ } \
149 else if ( rc == VINF_HM_DOUBLE_FAULT) { return VINF_SUCCESS; } \
150 else \
151 return rc; \
152 } while (0)
153#endif
154
155/** Macro which updates interrupt shadow for the current RIP. */
156#define HMSVM_UPDATE_INTR_SHADOW(pVCpu, pCtx) \
157 do { \
158 /* Update interrupt shadow. */ \
159 if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS) \
160 && pCtx->rip != EMGetInhibitInterruptsPC(pVCpu)) \
161 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS); \
162 } while (0)
163
164/** Macro for upgrading a @a a_rc to VINF_EM_DBG_STEPPED after emulating an
165 * instruction that exited. */
166#define HMSVM_CHECK_SINGLE_STEP(a_pVCpu, a_rc) \
167 do { \
168 if ((a_pVCpu)->hm.s.fSingleInstruction && (a_rc) == VINF_SUCCESS) \
169 (a_rc) = VINF_EM_DBG_STEPPED; \
170 } while (0)
171
172/** Assert that preemption is disabled or covered by thread-context hooks. */
173#define HMSVM_ASSERT_PREEMPT_SAFE() Assert( VMMR0ThreadCtxHookIsEnabled(pVCpu) \
174 || !RTThreadPreemptIsEnabled(NIL_RTTHREAD));
175
176/** Assert that we haven't migrated CPUs when thread-context hooks are not
177 * used. */
178#define HMSVM_ASSERT_CPU_SAFE() AssertMsg( VMMR0ThreadCtxHookIsEnabled(pVCpu) \
179 || pVCpu->hm.s.idEnteredCpu == RTMpCpuId(), \
180 ("Illegal migration! Entered on CPU %u Current %u\n", \
181 pVCpu->hm.s.idEnteredCpu, RTMpCpuId()));
182
183/** Assert that we're not executing a nested-guest. */
184#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
185# define HMSVM_ASSERT_NOT_IN_NESTED_GUEST(a_pCtx) Assert(!CPUMIsGuestInSvmNestedHwVirtMode((a_pCtx)))
186#else
187# define HMSVM_ASSERT_NOT_IN_NESTED_GUEST(a_pCtx) do { NOREF((a_pCtx)); } while (0)
188#endif
189
190/** Assert that we're executing a nested-guest. */
191#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
192# define HMSVM_ASSERT_IN_NESTED_GUEST(a_pCtx) Assert(CPUMIsGuestInSvmNestedHwVirtMode((a_pCtx)))
193#else
194# define HMSVM_ASSERT_IN_NESTED_GUEST(a_pCtx) do { NOREF((a_pCtx)); } while (0)
195#endif
196
197/** Validate segment descriptor granularity bit. */
198#ifdef VBOX_STRICT
199# define HMSVM_ASSERT_SEG_GRANULARITY(a_pCtx, reg) \
200 AssertMsg( !(a_pCtx)->reg.Attr.n.u1Present \
201 || ( (a_pCtx)->reg.Attr.n.u1Granularity \
202 ? ((a_pCtx)->reg.u32Limit & 0xfff) == 0xfff \
203 : (a_pCtx)->reg.u32Limit <= UINT32_C(0xfffff)), \
204 ("Invalid Segment Attributes Limit=%#RX32 Attr=%#RX32 Base=%#RX64\n", (a_pCtx)->reg.u32Limit, \
205 (a_pCtx)->reg.Attr.u, (a_pCtx)->reg.u64Base))
206#else
207# define HMSVM_ASSERT_SEG_GRANULARITY(a_pCtx, reg) do { } while (0)
208#endif
209
210/**
211 * Exception bitmap mask for all contributory exceptions.
212 *
213 * Page fault is deliberately excluded here as it's conditional as to whether
214 * it's contributory or benign. Page faults are handled separately.
215 */
216#define HMSVM_CONTRIBUTORY_XCPT_MASK ( RT_BIT(X86_XCPT_GP) | RT_BIT(X86_XCPT_NP) | RT_BIT(X86_XCPT_SS) | RT_BIT(X86_XCPT_TS) \
217 | RT_BIT(X86_XCPT_DE))
218
219/**
220 * Mandatory/unconditional guest control intercepts.
221 *
222 * SMIs can and do happen in normal operation. We need not intercept them
223 * while executing the guest (or nested-guest).
224 */
225#define HMSVM_MANDATORY_GUEST_CTRL_INTERCEPTS ( SVM_CTRL_INTERCEPT_INTR \
226 | SVM_CTRL_INTERCEPT_NMI \
227 | SVM_CTRL_INTERCEPT_INIT \
228 | SVM_CTRL_INTERCEPT_RDPMC \
229 | SVM_CTRL_INTERCEPT_CPUID \
230 | SVM_CTRL_INTERCEPT_RSM \
231 | SVM_CTRL_INTERCEPT_HLT \
232 | SVM_CTRL_INTERCEPT_IOIO_PROT \
233 | SVM_CTRL_INTERCEPT_MSR_PROT \
234 | SVM_CTRL_INTERCEPT_INVLPGA \
235 | SVM_CTRL_INTERCEPT_SHUTDOWN \
236 | SVM_CTRL_INTERCEPT_FERR_FREEZE \
237 | SVM_CTRL_INTERCEPT_VMRUN \
238 | SVM_CTRL_INTERCEPT_SKINIT \
239 | SVM_CTRL_INTERCEPT_WBINVD \
240 | SVM_CTRL_INTERCEPT_MONITOR \
241 | SVM_CTRL_INTERCEPT_MWAIT \
242 | SVM_CTRL_INTERCEPT_CR0_SEL_WRITE \
243 | SVM_CTRL_INTERCEPT_XSETBV)
244
245/** @name VMCB Clean Bits.
246 *
247 * These flags are used for VMCB-state caching. A set VMCB Clean bit indicates
248 * AMD-V doesn't need to reload the corresponding value(s) from the VMCB in
249 * memory.
250 *
251 * @{ */
252/** All intercepts vectors, TSC offset, PAUSE filter counter. */
253#define HMSVM_VMCB_CLEAN_INTERCEPTS RT_BIT(0)
254/** I/O permission bitmap, MSR permission bitmap. */
255#define HMSVM_VMCB_CLEAN_IOPM_MSRPM RT_BIT(1)
256/** ASID. */
257#define HMSVM_VMCB_CLEAN_ASID RT_BIT(2)
258/** TRP: V_TPR, V_IRQ, V_INTR_PRIO, V_IGN_TPR, V_INTR_MASKING,
259V_INTR_VECTOR. */
260#define HMSVM_VMCB_CLEAN_INT_CTRL RT_BIT(3)
261/** Nested Paging: Nested CR3 (nCR3), PAT. */
262#define HMSVM_VMCB_CLEAN_NP RT_BIT(4)
263/** Control registers (CR0, CR3, CR4, EFER). */
264#define HMSVM_VMCB_CLEAN_CRX_EFER RT_BIT(5)
265/** Debug registers (DR6, DR7). */
266#define HMSVM_VMCB_CLEAN_DRX RT_BIT(6)
267/** GDT, IDT limit and base. */
268#define HMSVM_VMCB_CLEAN_DT RT_BIT(7)
269/** Segment register: CS, SS, DS, ES limit and base. */
270#define HMSVM_VMCB_CLEAN_SEG RT_BIT(8)
271/** CR2.*/
272#define HMSVM_VMCB_CLEAN_CR2 RT_BIT(9)
273/** Last-branch record (DbgCtlMsr, br_from, br_to, lastint_from, lastint_to) */
274#define HMSVM_VMCB_CLEAN_LBR RT_BIT(10)
275/** AVIC (AVIC APIC_BAR; AVIC APIC_BACKING_PAGE, AVIC
276PHYSICAL_TABLE and AVIC LOGICAL_TABLE Pointers). */
277#define HMSVM_VMCB_CLEAN_AVIC RT_BIT(11)
278/** Mask of all valid VMCB Clean bits. */
279#define HMSVM_VMCB_CLEAN_ALL ( HMSVM_VMCB_CLEAN_INTERCEPTS \
280 | HMSVM_VMCB_CLEAN_IOPM_MSRPM \
281 | HMSVM_VMCB_CLEAN_ASID \
282 | HMSVM_VMCB_CLEAN_INT_CTRL \
283 | HMSVM_VMCB_CLEAN_NP \
284 | HMSVM_VMCB_CLEAN_CRX_EFER \
285 | HMSVM_VMCB_CLEAN_DRX \
286 | HMSVM_VMCB_CLEAN_DT \
287 | HMSVM_VMCB_CLEAN_SEG \
288 | HMSVM_VMCB_CLEAN_CR2 \
289 | HMSVM_VMCB_CLEAN_LBR \
290 | HMSVM_VMCB_CLEAN_AVIC)
291/** @} */
292
293/** @name SVM transient.
294 *
295 * A state structure for holding miscellaneous information across AMD-V
296 * VMRUN/\#VMEXIT operation, restored after the transition.
297 *
298 * @{ */
299typedef struct SVMTRANSIENT
300{
301 /** The host's rflags/eflags. */
302 RTCCUINTREG fEFlags;
303#if HC_ARCH_BITS == 32
304 uint32_t u32Alignment0;
305#endif
306
307 /** The \#VMEXIT exit code (the EXITCODE field in the VMCB). */
308 uint64_t u64ExitCode;
309 /** The guest's TPR value used for TPR shadowing. */
310 uint8_t u8GuestTpr;
311 /** Alignment. */
312 uint8_t abAlignment0[7];
313
314 /** Pointer to the currently executing VMCB. */
315 PSVMVMCB pVmcb;
316 /** Whether we are currently executing a nested-guest. */
317 bool fIsNestedGuest;
318
319 /** Whether the guest debug state was active at the time of \#VMEXIT. */
320 bool fWasGuestDebugStateActive;
321 /** Whether the hyper debug state was active at the time of \#VMEXIT. */
322 bool fWasHyperDebugStateActive;
323 /** Whether the TSC offset mode needs to be updated. */
324 bool fUpdateTscOffsetting;
325 /** Whether the TSC_AUX MSR needs restoring on \#VMEXIT. */
326 bool fRestoreTscAuxMsr;
327 /** Whether the \#VMEXIT was caused by a page-fault during delivery of a
328 * contributary exception or a page-fault. */
329 bool fVectoringDoublePF;
330 /** Whether the \#VMEXIT was caused by a page-fault during delivery of an
331 * external interrupt or NMI. */
332 bool fVectoringPF;
333} SVMTRANSIENT, *PSVMTRANSIENT;
334AssertCompileMemberAlignment(SVMTRANSIENT, u64ExitCode, sizeof(uint64_t));
335AssertCompileMemberAlignment(SVMTRANSIENT, pVmcb, sizeof(uint64_t));
336/** @} */
337
338/**
339 * MSRPM (MSR permission bitmap) read permissions (for guest RDMSR).
340 */
341typedef enum SVMMSREXITREAD
342{
343 /** Reading this MSR causes a \#VMEXIT. */
344 SVMMSREXIT_INTERCEPT_READ = 0xb,
345 /** Reading this MSR does not cause a \#VMEXIT. */
346 SVMMSREXIT_PASSTHRU_READ
347} SVMMSREXITREAD;
348
349/**
350 * MSRPM (MSR permission bitmap) write permissions (for guest WRMSR).
351 */
352typedef enum SVMMSREXITWRITE
353{
354 /** Writing to this MSR causes a \#VMEXIT. */
355 SVMMSREXIT_INTERCEPT_WRITE = 0xd,
356 /** Writing to this MSR does not cause a \#VMEXIT. */
357 SVMMSREXIT_PASSTHRU_WRITE
358} SVMMSREXITWRITE;
359
360/**
361 * SVM \#VMEXIT handler.
362 *
363 * @returns VBox status code.
364 * @param pVCpu The cross context virtual CPU structure.
365 * @param pCtx Pointer to the guest-CPU context.
366 * @param pSvmTransient Pointer to the SVM-transient structure.
367 */
368typedef int FNSVMEXITHANDLER(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient);
369
370
371/*********************************************************************************************************************************
372* Internal Functions *
373*********************************************************************************************************************************/
374static void hmR0SvmPendingEventToTrpmTrap(PVMCPU pVCpu);
375static void hmR0SvmLeave(PVMCPU pVCpu, bool fImportState);
376
377
378/** @name \#VMEXIT handlers.
379 * @{
380 */
381static FNSVMEXITHANDLER hmR0SvmExitIntr;
382static FNSVMEXITHANDLER hmR0SvmExitWbinvd;
383static FNSVMEXITHANDLER hmR0SvmExitInvd;
384static FNSVMEXITHANDLER hmR0SvmExitCpuid;
385static FNSVMEXITHANDLER hmR0SvmExitRdtsc;
386static FNSVMEXITHANDLER hmR0SvmExitRdtscp;
387static FNSVMEXITHANDLER hmR0SvmExitRdpmc;
388static FNSVMEXITHANDLER hmR0SvmExitInvlpg;
389static FNSVMEXITHANDLER hmR0SvmExitHlt;
390static FNSVMEXITHANDLER hmR0SvmExitMonitor;
391static FNSVMEXITHANDLER hmR0SvmExitMwait;
392static FNSVMEXITHANDLER hmR0SvmExitShutdown;
393static FNSVMEXITHANDLER hmR0SvmExitUnexpected;
394static FNSVMEXITHANDLER hmR0SvmExitReadCRx;
395static FNSVMEXITHANDLER hmR0SvmExitWriteCRx;
396static FNSVMEXITHANDLER hmR0SvmExitMsr;
397static FNSVMEXITHANDLER hmR0SvmExitReadDRx;
398static FNSVMEXITHANDLER hmR0SvmExitWriteDRx;
399static FNSVMEXITHANDLER hmR0SvmExitXsetbv;
400static FNSVMEXITHANDLER hmR0SvmExitIOInstr;
401static FNSVMEXITHANDLER hmR0SvmExitNestedPF;
402static FNSVMEXITHANDLER hmR0SvmExitVIntr;
403static FNSVMEXITHANDLER hmR0SvmExitTaskSwitch;
404static FNSVMEXITHANDLER hmR0SvmExitVmmCall;
405static FNSVMEXITHANDLER hmR0SvmExitPause;
406static FNSVMEXITHANDLER hmR0SvmExitFerrFreeze;
407static FNSVMEXITHANDLER hmR0SvmExitIret;
408static FNSVMEXITHANDLER hmR0SvmExitXcptPF;
409static FNSVMEXITHANDLER hmR0SvmExitXcptUD;
410static FNSVMEXITHANDLER hmR0SvmExitXcptMF;
411static FNSVMEXITHANDLER hmR0SvmExitXcptDB;
412static FNSVMEXITHANDLER hmR0SvmExitXcptAC;
413static FNSVMEXITHANDLER hmR0SvmExitXcptBP;
414#if defined(HMSVM_ALWAYS_TRAP_ALL_XCPTS) || defined(VBOX_WITH_NESTED_HWVIRT_SVM)
415static FNSVMEXITHANDLER hmR0SvmExitXcptGeneric;
416#endif
417#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
418static FNSVMEXITHANDLER hmR0SvmExitClgi;
419static FNSVMEXITHANDLER hmR0SvmExitStgi;
420static FNSVMEXITHANDLER hmR0SvmExitVmload;
421static FNSVMEXITHANDLER hmR0SvmExitVmsave;
422static FNSVMEXITHANDLER hmR0SvmExitInvlpga;
423static FNSVMEXITHANDLER hmR0SvmExitVmrun;
424static FNSVMEXITHANDLER hmR0SvmNestedExitXcptDB;
425static FNSVMEXITHANDLER hmR0SvmNestedExitXcptBP;
426#endif
427/** @} */
428
429static int hmR0SvmHandleExit(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient);
430#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
431static int hmR0SvmHandleExitNested(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient);
432#endif
433
434
435/*********************************************************************************************************************************
436* Global Variables *
437*********************************************************************************************************************************/
438/** Ring-0 memory object for the IO bitmap. */
439static RTR0MEMOBJ g_hMemObjIOBitmap = NIL_RTR0MEMOBJ;
440/** Physical address of the IO bitmap. */
441static RTHCPHYS g_HCPhysIOBitmap;
442/** Pointer to the IO bitmap. */
443static R0PTRTYPE(void *) g_pvIOBitmap;
444
445#ifdef VBOX_STRICT
446# define HMSVM_LOG_RBP_RSP RT_BIT_32(0)
447# define HMSVM_LOG_CR_REGS RT_BIT_32(1)
448# define HMSVM_LOG_CS RT_BIT_32(2)
449# define HMSVM_LOG_SS RT_BIT_32(3)
450# define HMSVM_LOG_FS RT_BIT_32(4)
451# define HMSVM_LOG_GS RT_BIT_32(5)
452# define HMSVM_LOG_LBR RT_BIT_32(6)
453# define HMSVM_LOG_ALL ( HMSVM_LOG_RBP_RSP \
454 | HMSVM_LOG_CR_REGS \
455 | HMSVM_LOG_CS \
456 | HMSVM_LOG_SS \
457 | HMSVM_LOG_FS \
458 | HMSVM_LOG_GS \
459 | HMSVM_LOG_LBR)
460
461/**
462 * Dumps virtual CPU state and additional info. to the logger for diagnostics.
463 *
464 * @param pVCpu The cross context virtual CPU structure.
465 * @param pVmcb Pointer to the VM control block.
466 * @param pszPrefix Log prefix.
467 * @param fFlags Log flags, see HMSVM_LOG_XXX.
468 * @param uVerbose The verbosity level, currently unused.
469 */
470static void hmR0SvmLogState(PVMCPU pVCpu, PCSVMVMCB pVmcb, const char *pszPrefix, uint32_t fFlags, uint8_t uVerbose)
471{
472 RT_NOREF2(pVCpu, uVerbose);
473 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
474
475 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS);
476 Log4(("%s: cs:rip=%04x:%RX64 efl=%#RX64\n", pszPrefix, pCtx->cs.Sel, pCtx->rip, pCtx->rflags.u));
477
478 if (fFlags & HMSVM_LOG_RBP_RSP)
479 {
480 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_RBP);
481 Log4(("%s: rsp=%#RX64 rbp=%#RX64\n", pszPrefix, pCtx->rsp, pCtx->rbp));
482 }
483
484 if (fFlags & HMSVM_LOG_CR_REGS)
485 {
486 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_CR3 | CPUMCTX_EXTRN_CR4);
487 Log4(("%s: cr0=%#RX64 cr3=%#RX64 cr4=%#RX64\n", pszPrefix, pCtx->cr0, pCtx->cr3, pCtx->cr4));
488 }
489
490 if (fFlags & HMSVM_LOG_CS)
491 {
492 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CS);
493 Log4(("%s: cs={%04x base=%016RX64 limit=%08x flags=%08x}\n", pszPrefix, pCtx->cs.Sel, pCtx->cs.u64Base,
494 pCtx->cs.u32Limit, pCtx->cs.Attr.u));
495 }
496 if (fFlags & HMSVM_LOG_SS)
497 {
498 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_SS);
499 Log4(("%s: ss={%04x base=%016RX64 limit=%08x flags=%08x}\n", pszPrefix, pCtx->ss.Sel, pCtx->ss.u64Base,
500 pCtx->ss.u32Limit, pCtx->ss.Attr.u));
501 }
502 if (fFlags & HMSVM_LOG_FS)
503 {
504 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_FS);
505 Log4(("%s: fs={%04x base=%016RX64 limit=%08x flags=%08x}\n", pszPrefix, pCtx->fs.Sel, pCtx->fs.u64Base,
506 pCtx->fs.u32Limit, pCtx->fs.Attr.u));
507 }
508 if (fFlags & HMSVM_LOG_GS)
509 {
510 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_GS);
511 Log4(("%s: gs={%04x base=%016RX64 limit=%08x flags=%08x}\n", pszPrefix, pCtx->gs.Sel, pCtx->gs.u64Base,
512 pCtx->gs.u32Limit, pCtx->gs.Attr.u));
513 }
514
515 PCSVMVMCBSTATESAVE pVmcbGuest = &pVmcb->guest;
516 if (fFlags & HMSVM_LOG_LBR)
517 {
518 Log4(("%s: br_from=%#RX64 br_to=%#RX64 lastxcpt_from=%#RX64 lastxcpt_to=%#RX64\n", pszPrefix, pVmcbGuest->u64BR_FROM,
519 pVmcbGuest->u64BR_TO, pVmcbGuest->u64LASTEXCPFROM, pVmcbGuest->u64LASTEXCPTO));
520 }
521 NOREF(pVmcbGuest); NOREF(pCtx);
522}
523#endif /* VBOX_STRICT */
524
525
526/**
527 * Sets up and activates AMD-V on the current CPU.
528 *
529 * @returns VBox status code.
530 * @param pCpu Pointer to the CPU info struct.
531 * @param pVM The cross context VM structure. Can be
532 * NULL after a resume!
533 * @param pvCpuPage Pointer to the global CPU page.
534 * @param HCPhysCpuPage Physical address of the global CPU page.
535 * @param fEnabledByHost Whether the host OS has already initialized AMD-V.
536 * @param pvArg Unused on AMD-V.
537 */
538VMMR0DECL(int) SVMR0EnableCpu(PHMGLOBALCPUINFO pCpu, PVM pVM, void *pvCpuPage, RTHCPHYS HCPhysCpuPage, bool fEnabledByHost,
539 void *pvArg)
540{
541 Assert(!fEnabledByHost);
542 Assert(HCPhysCpuPage && HCPhysCpuPage != NIL_RTHCPHYS);
543 Assert(RT_ALIGN_T(HCPhysCpuPage, _4K, RTHCPHYS) == HCPhysCpuPage);
544 Assert(pvCpuPage); NOREF(pvCpuPage);
545 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
546
547 NOREF(pvArg);
548 NOREF(fEnabledByHost);
549
550 /* Paranoid: Disable interrupt as, in theory, interrupt handlers might mess with EFER. */
551 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
552
553 /*
554 * We must turn on AMD-V and setup the host state physical address, as those MSRs are per CPU.
555 */
556 uint64_t u64HostEfer = ASMRdMsr(MSR_K6_EFER);
557 if (u64HostEfer & MSR_K6_EFER_SVME)
558 {
559 /* If the VBOX_HWVIRTEX_IGNORE_SVM_IN_USE is active, then we blindly use AMD-V. */
560 if ( pVM
561 && pVM->hm.s.svm.fIgnoreInUseError)
562 pCpu->fIgnoreAMDVInUseError = true;
563
564 if (!pCpu->fIgnoreAMDVInUseError)
565 {
566 ASMSetFlags(fEFlags);
567 return VERR_SVM_IN_USE;
568 }
569 }
570
571 /* Turn on AMD-V in the EFER MSR. */
572 ASMWrMsr(MSR_K6_EFER, u64HostEfer | MSR_K6_EFER_SVME);
573
574 /* Write the physical page address where the CPU will store the host state while executing the VM. */
575 ASMWrMsr(MSR_K8_VM_HSAVE_PA, HCPhysCpuPage);
576
577 /* Restore interrupts. */
578 ASMSetFlags(fEFlags);
579
580 /*
581 * Theoretically, other hypervisors may have used ASIDs, ideally we should flush all
582 * non-zero ASIDs when enabling SVM. AMD doesn't have an SVM instruction to flush all
583 * ASIDs (flushing is done upon VMRUN). Therefore, flag that we need to flush the TLB
584 * entirely with before executing any guest code.
585 */
586 pCpu->fFlushAsidBeforeUse = true;
587
588 /*
589 * Ensure each VCPU scheduled on this CPU gets a new ASID on resume. See @bugref{6255}.
590 */
591 ++pCpu->cTlbFlushes;
592
593 return VINF_SUCCESS;
594}
595
596
597/**
598 * Deactivates AMD-V on the current CPU.
599 *
600 * @returns VBox status code.
601 * @param pCpu Pointer to the CPU info struct.
602 * @param pvCpuPage Pointer to the global CPU page.
603 * @param HCPhysCpuPage Physical address of the global CPU page.
604 */
605VMMR0DECL(int) SVMR0DisableCpu(PHMGLOBALCPUINFO pCpu, void *pvCpuPage, RTHCPHYS HCPhysCpuPage)
606{
607 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
608 AssertReturn( HCPhysCpuPage
609 && HCPhysCpuPage != NIL_RTHCPHYS, VERR_INVALID_PARAMETER);
610 AssertReturn(pvCpuPage, VERR_INVALID_PARAMETER);
611 NOREF(pCpu);
612
613 /* Paranoid: Disable interrupts as, in theory, interrupt handlers might mess with EFER. */
614 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
615
616 /* Turn off AMD-V in the EFER MSR. */
617 uint64_t u64HostEfer = ASMRdMsr(MSR_K6_EFER);
618 ASMWrMsr(MSR_K6_EFER, u64HostEfer & ~MSR_K6_EFER_SVME);
619
620 /* Invalidate host state physical address. */
621 ASMWrMsr(MSR_K8_VM_HSAVE_PA, 0);
622
623 /* Restore interrupts. */
624 ASMSetFlags(fEFlags);
625
626 return VINF_SUCCESS;
627}
628
629
630/**
631 * Does global AMD-V initialization (called during module initialization).
632 *
633 * @returns VBox status code.
634 */
635VMMR0DECL(int) SVMR0GlobalInit(void)
636{
637 /*
638 * Allocate 12 KB (3 pages) for the IO bitmap. Since this is non-optional and we always
639 * intercept all IO accesses, it's done once globally here instead of per-VM.
640 */
641 Assert(g_hMemObjIOBitmap == NIL_RTR0MEMOBJ);
642 int rc = RTR0MemObjAllocCont(&g_hMemObjIOBitmap, SVM_IOPM_PAGES << X86_PAGE_4K_SHIFT, false /* fExecutable */);
643 if (RT_FAILURE(rc))
644 return rc;
645
646 g_pvIOBitmap = RTR0MemObjAddress(g_hMemObjIOBitmap);
647 g_HCPhysIOBitmap = RTR0MemObjGetPagePhysAddr(g_hMemObjIOBitmap, 0 /* iPage */);
648
649 /* Set all bits to intercept all IO accesses. */
650 ASMMemFill32(g_pvIOBitmap, SVM_IOPM_PAGES << X86_PAGE_4K_SHIFT, UINT32_C(0xffffffff));
651
652 return VINF_SUCCESS;
653}
654
655
656/**
657 * Does global AMD-V termination (called during module termination).
658 */
659VMMR0DECL(void) SVMR0GlobalTerm(void)
660{
661 if (g_hMemObjIOBitmap != NIL_RTR0MEMOBJ)
662 {
663 RTR0MemObjFree(g_hMemObjIOBitmap, true /* fFreeMappings */);
664 g_pvIOBitmap = NULL;
665 g_HCPhysIOBitmap = 0;
666 g_hMemObjIOBitmap = NIL_RTR0MEMOBJ;
667 }
668}
669
670
671/**
672 * Frees any allocated per-VCPU structures for a VM.
673 *
674 * @param pVM The cross context VM structure.
675 */
676DECLINLINE(void) hmR0SvmFreeStructs(PVM pVM)
677{
678 for (uint32_t i = 0; i < pVM->cCpus; i++)
679 {
680 PVMCPU pVCpu = &pVM->aCpus[i];
681 AssertPtr(pVCpu);
682
683 if (pVCpu->hm.s.svm.hMemObjVmcbHost != NIL_RTR0MEMOBJ)
684 {
685 RTR0MemObjFree(pVCpu->hm.s.svm.hMemObjVmcbHost, false);
686 pVCpu->hm.s.svm.HCPhysVmcbHost = 0;
687 pVCpu->hm.s.svm.hMemObjVmcbHost = NIL_RTR0MEMOBJ;
688 }
689
690 if (pVCpu->hm.s.svm.hMemObjVmcb != NIL_RTR0MEMOBJ)
691 {
692 RTR0MemObjFree(pVCpu->hm.s.svm.hMemObjVmcb, false);
693 pVCpu->hm.s.svm.pVmcb = NULL;
694 pVCpu->hm.s.svm.HCPhysVmcb = 0;
695 pVCpu->hm.s.svm.hMemObjVmcb = NIL_RTR0MEMOBJ;
696 }
697
698 if (pVCpu->hm.s.svm.hMemObjMsrBitmap != NIL_RTR0MEMOBJ)
699 {
700 RTR0MemObjFree(pVCpu->hm.s.svm.hMemObjMsrBitmap, false);
701 pVCpu->hm.s.svm.pvMsrBitmap = NULL;
702 pVCpu->hm.s.svm.HCPhysMsrBitmap = 0;
703 pVCpu->hm.s.svm.hMemObjMsrBitmap = NIL_RTR0MEMOBJ;
704 }
705 }
706}
707
708
709/**
710 * Does per-VM AMD-V initialization.
711 *
712 * @returns VBox status code.
713 * @param pVM The cross context VM structure.
714 */
715VMMR0DECL(int) SVMR0InitVM(PVM pVM)
716{
717 int rc = VERR_INTERNAL_ERROR_5;
718
719 /*
720 * Check for an AMD CPU erratum which requires us to flush the TLB before every world-switch.
721 */
722 uint32_t u32Family;
723 uint32_t u32Model;
724 uint32_t u32Stepping;
725 if (HMAmdIsSubjectToErratum170(&u32Family, &u32Model, &u32Stepping))
726 {
727 Log4Func(("AMD cpu with erratum 170 family %#x model %#x stepping %#x\n", u32Family, u32Model, u32Stepping));
728 pVM->hm.s.svm.fAlwaysFlushTLB = true;
729 }
730
731 /*
732 * Initialize the R0 memory objects up-front so we can properly cleanup on allocation failures.
733 */
734 for (VMCPUID i = 0; i < pVM->cCpus; i++)
735 {
736 PVMCPU pVCpu = &pVM->aCpus[i];
737 pVCpu->hm.s.svm.hMemObjVmcbHost = NIL_RTR0MEMOBJ;
738 pVCpu->hm.s.svm.hMemObjVmcb = NIL_RTR0MEMOBJ;
739 pVCpu->hm.s.svm.hMemObjMsrBitmap = NIL_RTR0MEMOBJ;
740 }
741
742 for (VMCPUID i = 0; i < pVM->cCpus; i++)
743 {
744 PVMCPU pVCpu = &pVM->aCpus[i];
745
746 /*
747 * Allocate one page for the host-context VM control block (VMCB). This is used for additional host-state (such as
748 * FS, GS, Kernel GS Base, etc.) apart from the host-state save area specified in MSR_K8_VM_HSAVE_PA.
749 */
750 rc = RTR0MemObjAllocCont(&pVCpu->hm.s.svm.hMemObjVmcbHost, SVM_VMCB_PAGES << PAGE_SHIFT, false /* fExecutable */);
751 if (RT_FAILURE(rc))
752 goto failure_cleanup;
753
754 void *pvVmcbHost = RTR0MemObjAddress(pVCpu->hm.s.svm.hMemObjVmcbHost);
755 pVCpu->hm.s.svm.HCPhysVmcbHost = RTR0MemObjGetPagePhysAddr(pVCpu->hm.s.svm.hMemObjVmcbHost, 0 /* iPage */);
756 Assert(pVCpu->hm.s.svm.HCPhysVmcbHost < _4G);
757 ASMMemZeroPage(pvVmcbHost);
758
759 /*
760 * Allocate one page for the guest-state VMCB.
761 */
762 rc = RTR0MemObjAllocCont(&pVCpu->hm.s.svm.hMemObjVmcb, SVM_VMCB_PAGES << PAGE_SHIFT, false /* fExecutable */);
763 if (RT_FAILURE(rc))
764 goto failure_cleanup;
765
766 pVCpu->hm.s.svm.pVmcb = (PSVMVMCB)RTR0MemObjAddress(pVCpu->hm.s.svm.hMemObjVmcb);
767 pVCpu->hm.s.svm.HCPhysVmcb = RTR0MemObjGetPagePhysAddr(pVCpu->hm.s.svm.hMemObjVmcb, 0 /* iPage */);
768 Assert(pVCpu->hm.s.svm.HCPhysVmcb < _4G);
769 ASMMemZeroPage(pVCpu->hm.s.svm.pVmcb);
770
771 /*
772 * Allocate two pages (8 KB) for the MSR permission bitmap. There doesn't seem to be a way to convince
773 * SVM to not require one.
774 */
775 rc = RTR0MemObjAllocCont(&pVCpu->hm.s.svm.hMemObjMsrBitmap, SVM_MSRPM_PAGES << X86_PAGE_4K_SHIFT,
776 false /* fExecutable */);
777 if (RT_FAILURE(rc))
778 goto failure_cleanup;
779
780 pVCpu->hm.s.svm.pvMsrBitmap = RTR0MemObjAddress(pVCpu->hm.s.svm.hMemObjMsrBitmap);
781 pVCpu->hm.s.svm.HCPhysMsrBitmap = RTR0MemObjGetPagePhysAddr(pVCpu->hm.s.svm.hMemObjMsrBitmap, 0 /* iPage */);
782 /* Set all bits to intercept all MSR accesses (changed later on). */
783 ASMMemFill32(pVCpu->hm.s.svm.pvMsrBitmap, SVM_MSRPM_PAGES << X86_PAGE_4K_SHIFT, UINT32_C(0xffffffff));
784 }
785
786 return VINF_SUCCESS;
787
788failure_cleanup:
789 hmR0SvmFreeStructs(pVM);
790 return rc;
791}
792
793
794/**
795 * Does per-VM AMD-V termination.
796 *
797 * @returns VBox status code.
798 * @param pVM The cross context VM structure.
799 */
800VMMR0DECL(int) SVMR0TermVM(PVM pVM)
801{
802 hmR0SvmFreeStructs(pVM);
803 return VINF_SUCCESS;
804}
805
806
807/**
808 * Returns whether the VMCB Clean Bits feature is supported.
809 *
810 * @return @c true if supported, @c false otherwise.
811 * @param pVCpu The cross context virtual CPU structure.
812 * @param pCtx Pointer to the guest-CPU context.
813 */
814DECLINLINE(bool) hmR0SvmSupportsVmcbCleanBits(PVMCPU pVCpu, PCCPUMCTX pCtx)
815{
816 PVM pVM = pVCpu->CTX_SUFF(pVM);
817#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
818 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
819 {
820 return (pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_VMCB_CLEAN)
821 && pVM->cpum.ro.GuestFeatures.fSvmVmcbClean;
822 }
823#else
824 RT_NOREF(pCtx);
825#endif
826 return RT_BOOL(pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_VMCB_CLEAN);
827}
828
829
830/**
831 * Returns whether the decode assists feature is supported.
832 *
833 * @return @c true if supported, @c false otherwise.
834 * @param pVCpu The cross context virtual CPU structure.
835 * @param pCtx Pointer to the guest-CPU context.
836 */
837DECLINLINE(bool) hmR0SvmSupportsDecodeAssists(PVMCPU pVCpu, PCPUMCTX pCtx)
838{
839 PVM pVM = pVCpu->CTX_SUFF(pVM);
840#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
841 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
842 {
843 return (pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_DECODE_ASSISTS)
844 && pVM->cpum.ro.GuestFeatures.fSvmDecodeAssists;
845 }
846#else
847 RT_NOREF(pCtx);
848#endif
849 return RT_BOOL(pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_DECODE_ASSISTS);
850}
851
852
853/**
854 * Returns whether the NRIP_SAVE feature is supported.
855 *
856 * @return @c true if supported, @c false otherwise.
857 * @param pVCpu The cross context virtual CPU structure.
858 * @param pCtx Pointer to the guest-CPU context.
859 */
860DECLINLINE(bool) hmR0SvmSupportsNextRipSave(PVMCPU pVCpu, PCPUMCTX pCtx)
861{
862 PVM pVM = pVCpu->CTX_SUFF(pVM);
863#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
864 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
865 {
866 return (pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
867 && pVM->cpum.ro.GuestFeatures.fSvmNextRipSave;
868 }
869#else
870 RT_NOREF(pCtx);
871#endif
872 return RT_BOOL(pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_NRIP_SAVE);
873}
874
875
876/**
877 * Sets the permission bits for the specified MSR in the MSRPM bitmap.
878 *
879 * @param pCtx Pointer to the guest-CPU or nested-guest-CPU context.
880 * @param pbMsrBitmap Pointer to the MSR bitmap.
881 * @param idMsr The MSR for which the permissions are being set.
882 * @param enmRead MSR read permissions.
883 * @param enmWrite MSR write permissions.
884 *
885 * @remarks This function does -not- clear the VMCB clean bits for MSRPM. The
886 * caller needs to take care of this.
887 */
888static void hmR0SvmSetMsrPermission(PCCPUMCTX pCtx, uint8_t *pbMsrBitmap, uint32_t idMsr, SVMMSREXITREAD enmRead,
889 SVMMSREXITWRITE enmWrite)
890{
891 bool const fInNestedGuestMode = CPUMIsGuestInSvmNestedHwVirtMode(pCtx);
892 uint16_t offMsrpm;
893 uint8_t uMsrpmBit;
894 int rc = HMSvmGetMsrpmOffsetAndBit(idMsr, &offMsrpm, &uMsrpmBit);
895 AssertRC(rc);
896
897 Assert(uMsrpmBit == 0 || uMsrpmBit == 2 || uMsrpmBit == 4 || uMsrpmBit == 6);
898 Assert(offMsrpm < SVM_MSRPM_PAGES << X86_PAGE_4K_SHIFT);
899
900 pbMsrBitmap += offMsrpm;
901 if (enmRead == SVMMSREXIT_INTERCEPT_READ)
902 *pbMsrBitmap |= RT_BIT(uMsrpmBit);
903 else
904 {
905 if (!fInNestedGuestMode)
906 *pbMsrBitmap &= ~RT_BIT(uMsrpmBit);
907#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
908 else
909 {
910 /* Only clear the bit if the nested-guest is also not intercepting the MSR read.*/
911 uint8_t const *pbNstGstMsrBitmap = (uint8_t *)pCtx->hwvirt.svm.CTX_SUFF(pvMsrBitmap);
912 pbNstGstMsrBitmap += offMsrpm;
913 if (!(*pbNstGstMsrBitmap & RT_BIT(uMsrpmBit)))
914 *pbMsrBitmap &= ~RT_BIT(uMsrpmBit);
915 else
916 Assert(*pbMsrBitmap & RT_BIT(uMsrpmBit));
917 }
918#endif
919 }
920
921 if (enmWrite == SVMMSREXIT_INTERCEPT_WRITE)
922 *pbMsrBitmap |= RT_BIT(uMsrpmBit + 1);
923 else
924 {
925 if (!fInNestedGuestMode)
926 *pbMsrBitmap &= ~RT_BIT(uMsrpmBit + 1);
927#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
928 else
929 {
930 /* Only clear the bit if the nested-guest is also not intercepting the MSR write.*/
931 uint8_t const *pbNstGstMsrBitmap = (uint8_t *)pCtx->hwvirt.svm.CTX_SUFF(pvMsrBitmap);
932 pbNstGstMsrBitmap += offMsrpm;
933 if (!(*pbNstGstMsrBitmap & RT_BIT(uMsrpmBit + 1)))
934 *pbMsrBitmap &= ~RT_BIT(uMsrpmBit + 1);
935 else
936 Assert(*pbMsrBitmap & RT_BIT(uMsrpmBit + 1));
937 }
938#endif
939 }
940}
941
942
943/**
944 * Sets up AMD-V for the specified VM.
945 * This function is only called once per-VM during initalization.
946 *
947 * @returns VBox status code.
948 * @param pVM The cross context VM structure.
949 */
950VMMR0DECL(int) SVMR0SetupVM(PVM pVM)
951{
952 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
953 AssertReturn(pVM, VERR_INVALID_PARAMETER);
954 Assert(pVM->hm.s.svm.fSupported);
955
956 bool const fPauseFilter = RT_BOOL(pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_PAUSE_FILTER);
957 bool const fPauseFilterThreshold = RT_BOOL(pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_PAUSE_FILTER_THRESHOLD);
958 bool const fUsePauseFilter = fPauseFilter && pVM->hm.s.svm.cPauseFilter;
959
960 bool const fLbrVirt = RT_BOOL(pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_LBR_VIRT);
961 bool const fUseLbrVirt = fLbrVirt; /** @todo CFGM, IEM implementation etc. */
962
963#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
964 bool const fVirtVmsaveVmload = RT_BOOL(pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_VIRT_VMSAVE_VMLOAD);
965 bool const fUseVirtVmsaveVmload = fVirtVmsaveVmload && pVM->hm.s.svm.fVirtVmsaveVmload && pVM->hm.s.fNestedPaging;
966
967 bool const fVGif = RT_BOOL(pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_VGIF);
968 bool const fUseVGif = fVGif && pVM->hm.s.svm.fVGif;
969#endif
970
971 PVMCPU pVCpu = &pVM->aCpus[0];
972 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
973 AssertMsgReturn(pVmcb, ("Invalid pVmcb for vcpu[0]\n"), VERR_SVM_INVALID_PVMCB);
974 PSVMVMCBCTRL pVmcbCtrl = &pVmcb->ctrl;
975
976 /* Always trap #AC for reasons of security. */
977 pVmcbCtrl->u32InterceptXcpt |= RT_BIT_32(X86_XCPT_AC);
978
979 /* Always trap #DB for reasons of security. */
980 pVmcbCtrl->u32InterceptXcpt |= RT_BIT_32(X86_XCPT_DB);
981
982 /* Trap exceptions unconditionally (debug purposes). */
983#ifdef HMSVM_ALWAYS_TRAP_PF
984 pVmcbCtrl->u32InterceptXcpt |= RT_BIT(X86_XCPT_PF);
985#endif
986#ifdef HMSVM_ALWAYS_TRAP_ALL_XCPTS
987 /* If you add any exceptions here, make sure to update hmR0SvmHandleExit(). */
988 pVmcbCtrl->u32InterceptXcpt |= 0
989 | RT_BIT(X86_XCPT_BP)
990 | RT_BIT(X86_XCPT_DE)
991 | RT_BIT(X86_XCPT_NM)
992 | RT_BIT(X86_XCPT_UD)
993 | RT_BIT(X86_XCPT_NP)
994 | RT_BIT(X86_XCPT_SS)
995 | RT_BIT(X86_XCPT_GP)
996 | RT_BIT(X86_XCPT_PF)
997 | RT_BIT(X86_XCPT_MF)
998 ;
999#endif
1000
1001 /* Apply the exceptions intercepts needed by the GIM provider. */
1002 if (pVCpu->hm.s.fGIMTrapXcptUD)
1003 pVmcbCtrl->u32InterceptXcpt |= RT_BIT(X86_XCPT_UD);
1004
1005 /* Set up unconditional intercepts and conditions. */
1006 pVmcbCtrl->u64InterceptCtrl = HMSVM_MANDATORY_GUEST_CTRL_INTERCEPTS
1007 | SVM_CTRL_INTERCEPT_VMMCALL;
1008
1009#ifdef HMSVM_ALWAYS_TRAP_TASK_SWITCH
1010 pVmcbCtrl->u64InterceptCtrl |= SVM_CTRL_INTERCEPT_TASK_SWITCH;
1011#endif
1012
1013#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
1014 /* Virtualized VMSAVE/VMLOAD. */
1015 pVmcbCtrl->LbrVirt.n.u1VirtVmsaveVmload = fUseVirtVmsaveVmload;
1016 if (!fUseVirtVmsaveVmload)
1017 {
1018 pVmcbCtrl->u64InterceptCtrl |= SVM_CTRL_INTERCEPT_VMSAVE
1019 | SVM_CTRL_INTERCEPT_VMLOAD;
1020 }
1021
1022 /* Virtual GIF. */
1023 pVmcbCtrl->IntCtrl.n.u1VGifEnable = fUseVGif;
1024 if (!fUseVGif)
1025 {
1026 pVmcbCtrl->u64InterceptCtrl |= SVM_CTRL_INTERCEPT_CLGI
1027 | SVM_CTRL_INTERCEPT_STGI;
1028 }
1029#endif
1030
1031 /* CR4 writes must always be intercepted for tracking PGM mode changes. */
1032 pVmcbCtrl->u16InterceptWrCRx = RT_BIT(4);
1033
1034 /* Intercept all DRx reads and writes by default. Changed later on. */
1035 pVmcbCtrl->u16InterceptRdDRx = 0xffff;
1036 pVmcbCtrl->u16InterceptWrDRx = 0xffff;
1037
1038 /* Virtualize masking of INTR interrupts. (reads/writes from/to CR8 go to the V_TPR register) */
1039 pVmcbCtrl->IntCtrl.n.u1VIntrMasking = 1;
1040
1041 /* Ignore the priority in the virtual TPR. This is necessary for delivering PIC style (ExtInt) interrupts
1042 and we currently deliver both PIC and APIC interrupts alike, see hmR0SvmEvaluatePendingEvent() */
1043 pVmcbCtrl->IntCtrl.n.u1IgnoreTPR = 1;
1044
1045 /* Set the IO permission bitmap physical addresses. */
1046 pVmcbCtrl->u64IOPMPhysAddr = g_HCPhysIOBitmap;
1047
1048 /* LBR virtualization. */
1049 pVmcbCtrl->LbrVirt.n.u1LbrVirt = fUseLbrVirt;
1050
1051 /* The host ASID MBZ, for the guest start with 1. */
1052 pVmcbCtrl->TLBCtrl.n.u32ASID = 1;
1053
1054 /* Setup Nested Paging. This doesn't change throughout the execution time of the VM. */
1055 pVmcbCtrl->NestedPagingCtrl.n.u1NestedPaging = pVM->hm.s.fNestedPaging;
1056
1057 /* Without Nested Paging, we need additionally intercepts. */
1058 if (!pVM->hm.s.fNestedPaging)
1059 {
1060 /* CR3 reads/writes must be intercepted; our shadow values differ from the guest values. */
1061 pVmcbCtrl->u16InterceptRdCRx |= RT_BIT(3);
1062 pVmcbCtrl->u16InterceptWrCRx |= RT_BIT(3);
1063
1064 /* Intercept INVLPG and task switches (may change CR3, EFLAGS, LDT). */
1065 pVmcbCtrl->u64InterceptCtrl |= SVM_CTRL_INTERCEPT_INVLPG
1066 | SVM_CTRL_INTERCEPT_TASK_SWITCH;
1067
1068 /* Page faults must be intercepted to implement shadow paging. */
1069 pVmcbCtrl->u32InterceptXcpt |= RT_BIT(X86_XCPT_PF);
1070 }
1071
1072 /* Setup Pause Filter for guest pause-loop (spinlock) exiting. */
1073 if (fUsePauseFilter)
1074 {
1075 Assert(pVM->hm.s.svm.cPauseFilter > 0);
1076 pVmcbCtrl->u16PauseFilterCount = pVM->hm.s.svm.cPauseFilter;
1077 if (fPauseFilterThreshold)
1078 pVmcbCtrl->u16PauseFilterThreshold = pVM->hm.s.svm.cPauseFilterThresholdTicks;
1079 pVmcbCtrl->u64InterceptCtrl |= SVM_CTRL_INTERCEPT_PAUSE;
1080 }
1081
1082 /*
1083 * Setup the MSR permission bitmap.
1084 * The following MSRs are saved/restored automatically during the world-switch.
1085 * Don't intercept guest read/write accesses to these MSRs.
1086 */
1087 uint8_t *pbMsrBitmap = (uint8_t *)pVCpu->hm.s.svm.pvMsrBitmap;
1088 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
1089 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_LSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1090 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_CSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1091 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K6_STAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1092 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_SF_MASK, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1093 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_FS_BASE, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1094 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_GS_BASE, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1095 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_KERNEL_GS_BASE, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1096 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_IA32_SYSENTER_CS, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1097 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_IA32_SYSENTER_ESP, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1098 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_IA32_SYSENTER_EIP, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1099 pVmcbCtrl->u64MSRPMPhysAddr = pVCpu->hm.s.svm.HCPhysMsrBitmap;
1100
1101 /* Initially all VMCB clean bits MBZ indicating that everything should be loaded from the VMCB in memory. */
1102 Assert(pVmcbCtrl->u32VmcbCleanBits == 0);
1103
1104 for (VMCPUID i = 1; i < pVM->cCpus; i++)
1105 {
1106 PVMCPU pVCpuCur = &pVM->aCpus[i];
1107 PSVMVMCB pVmcbCur = pVM->aCpus[i].hm.s.svm.pVmcb;
1108 AssertMsgReturn(pVmcbCur, ("Invalid pVmcb for vcpu[%u]\n", i), VERR_SVM_INVALID_PVMCB);
1109 PSVMVMCBCTRL pVmcbCtrlCur = &pVmcbCur->ctrl;
1110
1111 /* Copy the VMCB control area. */
1112 memcpy(pVmcbCtrlCur, pVmcbCtrl, sizeof(*pVmcbCtrlCur));
1113
1114 /* Copy the MSR bitmap and setup the VCPU-specific host physical address. */
1115 uint8_t *pbMsrBitmapCur = (uint8_t *)pVCpuCur->hm.s.svm.pvMsrBitmap;
1116 memcpy(pbMsrBitmapCur, pbMsrBitmap, SVM_MSRPM_PAGES << X86_PAGE_4K_SHIFT);
1117 pVmcbCtrlCur->u64MSRPMPhysAddr = pVCpuCur->hm.s.svm.HCPhysMsrBitmap;
1118
1119 /* Initially all VMCB clean bits MBZ indicating that everything should be loaded from the VMCB in memory. */
1120 Assert(pVmcbCtrlCur->u32VmcbCleanBits == 0);
1121
1122 /* Verify our assumption that GIM providers trap #UD uniformly across VCPUs initially. */
1123 Assert(pVCpuCur->hm.s.fGIMTrapXcptUD == pVCpu->hm.s.fGIMTrapXcptUD);
1124 }
1125
1126 return VINF_SUCCESS;
1127}
1128
1129
1130/**
1131 * Gets a pointer to the currently active guest (or nested-guest) VMCB.
1132 *
1133 * @returns Pointer to the current context VMCB.
1134 * @param pVCpu The cross context virtual CPU structure.
1135 * @param pCtx Pointer to the guest-CPU context.
1136 */
1137DECLINLINE(PSVMVMCB) hmR0SvmGetCurrentVmcb(PVMCPU pVCpu, PCPUMCTX pCtx)
1138{
1139#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
1140 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
1141 return pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
1142#else
1143 RT_NOREF(pCtx);
1144#endif
1145 return pVCpu->hm.s.svm.pVmcb;
1146}
1147
1148
1149/**
1150 * Gets a pointer to the nested-guest VMCB cache.
1151 *
1152 * @returns Pointer to the nested-guest VMCB cache.
1153 * @param pVCpu The cross context virtual CPU structure.
1154 */
1155DECLINLINE(PSVMNESTEDVMCBCACHE) hmR0SvmGetNestedVmcbCache(PVMCPU pVCpu)
1156{
1157#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
1158 Assert(pVCpu->hm.s.svm.NstGstVmcbCache.fCacheValid);
1159 return &pVCpu->hm.s.svm.NstGstVmcbCache;
1160#else
1161 RT_NOREF(pVCpu);
1162 return NULL;
1163#endif
1164}
1165
1166
1167/**
1168 * Invalidates a guest page by guest virtual address.
1169 *
1170 * @returns VBox status code.
1171 * @param pVM The cross context VM structure.
1172 * @param pVCpu The cross context virtual CPU structure.
1173 * @param GCVirt Guest virtual address of the page to invalidate.
1174 */
1175VMMR0DECL(int) SVMR0InvalidatePage(PVM pVM, PVMCPU pVCpu, RTGCPTR GCVirt)
1176{
1177 AssertReturn(pVM, VERR_INVALID_PARAMETER);
1178 Assert(pVM->hm.s.svm.fSupported);
1179
1180 bool fFlushPending = pVM->hm.s.svm.fAlwaysFlushTLB || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_TLB_FLUSH);
1181
1182 /* Skip it if a TLB flush is already pending. */
1183 if (!fFlushPending)
1184 {
1185 Log4Func(("%#RGv\n", GCVirt));
1186
1187 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
1188 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
1189 AssertMsgReturn(pVmcb, ("Invalid pVmcb!\n"), VERR_SVM_INVALID_PVMCB);
1190
1191#if HC_ARCH_BITS == 32
1192 /* If we get a flush in 64-bit guest mode, then force a full TLB flush. INVLPGA takes only 32-bit addresses. */
1193 if (CPUMIsGuestInLongMode(pVCpu))
1194 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
1195 else
1196#endif
1197 {
1198 SVMR0InvlpgA(GCVirt, pVmcb->ctrl.TLBCtrl.n.u32ASID);
1199 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbInvlpgVirt);
1200 }
1201 }
1202 return VINF_SUCCESS;
1203}
1204
1205
1206/**
1207 * Flushes the appropriate tagged-TLB entries.
1208 *
1209 * @param pVCpu The cross context virtual CPU structure.
1210 * @param pCtx Pointer to the guest-CPU or nested-guest-CPU context.
1211 * @param pVmcb Pointer to the VM control block.
1212 * @param pHostCpu Pointer to the HM host-CPU info.
1213 */
1214static void hmR0SvmFlushTaggedTlb(PVMCPU pVCpu, PCCPUMCTX pCtx, PSVMVMCB pVmcb, PHMGLOBALCPUINFO pHostCpu)
1215{
1216#ifndef VBOX_WITH_NESTED_HWVIRT_SVM
1217 RT_NOREF(pCtx);
1218#endif
1219 PVM pVM = pVCpu->CTX_SUFF(pVM);
1220
1221 /*
1222 * Force a TLB flush for the first world switch if the current CPU differs from the one
1223 * we ran on last. This can happen both for start & resume due to long jumps back to
1224 * ring-3.
1225 *
1226 * We also force a TLB flush every time when executing a nested-guest VCPU as there is no
1227 * correlation between it and the physical CPU.
1228 *
1229 * If the TLB flush count changed, another VM (VCPU rather) has hit the ASID limit while
1230 * flushing the TLB, so we cannot reuse the ASIDs without flushing.
1231 */
1232 bool fNewAsid = false;
1233 Assert(pHostCpu->idCpu != NIL_RTCPUID);
1234 if ( pVCpu->hm.s.idLastCpu != pHostCpu->idCpu
1235 || pVCpu->hm.s.cTlbFlushes != pHostCpu->cTlbFlushes
1236#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
1237 || CPUMIsGuestInSvmNestedHwVirtMode(pCtx)
1238#endif
1239 )
1240 {
1241 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
1242 pVCpu->hm.s.fForceTLBFlush = true;
1243 fNewAsid = true;
1244 }
1245
1246 /* Set TLB flush state as checked until we return from the world switch. */
1247 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true);
1248
1249 /* Check for explicit TLB flushes. */
1250 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
1251 {
1252 pVCpu->hm.s.fForceTLBFlush = true;
1253 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
1254 }
1255
1256 /*
1257 * If the AMD CPU erratum 170, We need to flush the entire TLB for each world switch. Sad.
1258 * This Host CPU requirement takes precedence.
1259 */
1260 if (pVM->hm.s.svm.fAlwaysFlushTLB)
1261 {
1262 pHostCpu->uCurrentAsid = 1;
1263 pVCpu->hm.s.uCurrentAsid = 1;
1264 pVCpu->hm.s.cTlbFlushes = pHostCpu->cTlbFlushes;
1265 pVCpu->hm.s.idLastCpu = pHostCpu->idCpu;
1266 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1267
1268 /* Clear the VMCB Clean Bit for NP while flushing the TLB. See @bugref{7152}. */
1269 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_NP;
1270 }
1271 else
1272 {
1273 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_NOTHING;
1274 if (pVCpu->hm.s.fForceTLBFlush)
1275 {
1276 /* Clear the VMCB Clean Bit for NP while flushing the TLB. See @bugref{7152}. */
1277 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_NP;
1278
1279 if (fNewAsid)
1280 {
1281 ++pHostCpu->uCurrentAsid;
1282
1283 bool fHitASIDLimit = false;
1284 if (pHostCpu->uCurrentAsid >= pVM->hm.s.uMaxAsid)
1285 {
1286 pHostCpu->uCurrentAsid = 1; /* Wraparound at 1; host uses 0 */
1287 pHostCpu->cTlbFlushes++; /* All VCPUs that run on this host CPU must use a new ASID. */
1288 fHitASIDLimit = true;
1289 }
1290
1291 if ( fHitASIDLimit
1292 || pHostCpu->fFlushAsidBeforeUse)
1293 {
1294 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1295 pHostCpu->fFlushAsidBeforeUse = false;
1296 }
1297
1298 pVCpu->hm.s.uCurrentAsid = pHostCpu->uCurrentAsid;
1299 pVCpu->hm.s.idLastCpu = pHostCpu->idCpu;
1300 pVCpu->hm.s.cTlbFlushes = pHostCpu->cTlbFlushes;
1301 }
1302 else
1303 {
1304 if (pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
1305 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
1306 else
1307 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1308 }
1309
1310 pVCpu->hm.s.fForceTLBFlush = false;
1311 }
1312 }
1313
1314 /* Update VMCB with the ASID. */
1315 if (pVmcb->ctrl.TLBCtrl.n.u32ASID != pVCpu->hm.s.uCurrentAsid)
1316 {
1317 pVmcb->ctrl.TLBCtrl.n.u32ASID = pVCpu->hm.s.uCurrentAsid;
1318 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_ASID;
1319 }
1320
1321 AssertMsg(pVCpu->hm.s.idLastCpu == pHostCpu->idCpu,
1322 ("vcpu idLastCpu=%u hostcpu idCpu=%u\n", pVCpu->hm.s.idLastCpu, pHostCpu->idCpu));
1323 AssertMsg(pVCpu->hm.s.cTlbFlushes == pHostCpu->cTlbFlushes,
1324 ("Flush count mismatch for cpu %u (%u vs %u)\n", pHostCpu->idCpu, pVCpu->hm.s.cTlbFlushes, pHostCpu->cTlbFlushes));
1325 AssertMsg(pHostCpu->uCurrentAsid >= 1 && pHostCpu->uCurrentAsid < pVM->hm.s.uMaxAsid,
1326 ("cpu%d uCurrentAsid = %x\n", pHostCpu->idCpu, pHostCpu->uCurrentAsid));
1327 AssertMsg(pVCpu->hm.s.uCurrentAsid >= 1 && pVCpu->hm.s.uCurrentAsid < pVM->hm.s.uMaxAsid,
1328 ("cpu%d VM uCurrentAsid = %x\n", pHostCpu->idCpu, pVCpu->hm.s.uCurrentAsid));
1329
1330#ifdef VBOX_WITH_STATISTICS
1331 if (pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_NOTHING)
1332 STAM_COUNTER_INC(&pVCpu->hm.s.StatNoFlushTlbWorldSwitch);
1333 else if ( pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_SINGLE_CONTEXT
1334 || pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_SINGLE_CONTEXT_RETAIN_GLOBALS)
1335 {
1336 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushAsid);
1337 }
1338 else
1339 {
1340 Assert(pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_ENTIRE);
1341 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushEntire);
1342 }
1343#endif
1344}
1345
1346
1347/** @name 64-bit guest on 32-bit host OS helper functions.
1348 *
1349 * The host CPU is still 64-bit capable but the host OS is running in 32-bit
1350 * mode (code segment, paging). These wrappers/helpers perform the necessary
1351 * bits for the 32->64 switcher.
1352 *
1353 * @{ */
1354#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS)
1355/**
1356 * Prepares for and executes VMRUN (64-bit guests on a 32-bit host).
1357 *
1358 * @returns VBox status code.
1359 * @param HCPhysVmcbHost Physical address of host VMCB.
1360 * @param HCPhysVmcb Physical address of the VMCB.
1361 * @param pCtx Pointer to the guest-CPU context.
1362 * @param pVM The cross context VM structure.
1363 * @param pVCpu The cross context virtual CPU structure.
1364 */
1365DECLASM(int) SVMR0VMSwitcherRun64(RTHCPHYS HCPhysVmcbHost, RTHCPHYS HCPhysVmcb, PCPUMCTX pCtx, PVM pVM, PVMCPU pVCpu)
1366{
1367 RT_NOREF2(pVM, pCtx);
1368 uint32_t aParam[8];
1369 aParam[0] = RT_LO_U32(HCPhysVmcbHost); /* Param 1: HCPhysVmcbHost - Lo. */
1370 aParam[1] = RT_HI_U32(HCPhysVmcbHost); /* Param 1: HCPhysVmcbHost - Hi. */
1371 aParam[2] = RT_LO_U32(HCPhysVmcb); /* Param 2: HCPhysVmcb - Lo. */
1372 aParam[3] = RT_HI_U32(HCPhysVmcb); /* Param 2: HCPhysVmcb - Hi. */
1373 aParam[4] = VM_RC_ADDR(pVM, pVM);
1374 aParam[5] = 0;
1375 aParam[6] = VM_RC_ADDR(pVM, pVCpu);
1376 aParam[7] = 0;
1377
1378 return SVMR0Execute64BitsHandler(pVCpu, HM64ON32OP_SVMRCVMRun64, RT_ELEMENTS(aParam), &aParam[0]);
1379}
1380
1381
1382/**
1383 * Executes the specified VMRUN handler in 64-bit mode.
1384 *
1385 * @returns VBox status code.
1386 * @param pVCpu The cross context virtual CPU structure.
1387 * @param enmOp The operation to perform.
1388 * @param cParams Number of parameters.
1389 * @param paParam Array of 32-bit parameters.
1390 */
1391VMMR0DECL(int) SVMR0Execute64BitsHandler(PVMCPU pVCpu, HM64ON32OP enmOp, uint32_t cParams, uint32_t *paParam)
1392{
1393 PVM pVM = pVCpu->CTX_SUFF(pVM);
1394 AssertReturn(pVM->hm.s.pfnHost32ToGuest64R0, VERR_HM_NO_32_TO_64_SWITCHER);
1395 Assert(enmOp > HM64ON32OP_INVALID && enmOp < HM64ON32OP_END);
1396
1397 /* Disable interrupts. */
1398 RTHCUINTREG const fEFlags = ASMIntDisableFlags();
1399
1400#ifdef VBOX_WITH_VMMR0_DISABLE_LAPIC_NMI
1401 RTCPUID idHostCpu = RTMpCpuId();
1402 CPUMR0SetLApic(pVCpu, idHostCpu);
1403#endif
1404
1405 CPUMSetHyperESP(pVCpu, VMMGetStackRC(pVCpu));
1406 CPUMSetHyperEIP(pVCpu, enmOp);
1407 for (int i = (int)cParams - 1; i >= 0; i--)
1408 CPUMPushHyper(pVCpu, paParam[i]);
1409
1410 /* Call the switcher. */
1411 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatWorldSwitch3264, z);
1412 int rc = pVM->hm.s.pfnHost32ToGuest64R0(pVM, RT_OFFSETOF(VM, aCpus[pVCpu->idCpu].cpum) - RT_OFFSETOF(VM, cpum));
1413 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatWorldSwitch3264, z);
1414
1415 /* Restore interrupts. */
1416 ASMSetFlags(fEFlags);
1417 return rc;
1418}
1419
1420#endif /* HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) */
1421/** @} */
1422
1423
1424/**
1425 * Sets an exception intercept in the specified VMCB.
1426 *
1427 * @param pVmcb Pointer to the VM control block.
1428 * @param uXcpt The exception (X86_XCPT_*).
1429 */
1430DECLINLINE(void) hmR0SvmSetXcptIntercept(PSVMVMCB pVmcb, uint8_t uXcpt)
1431{
1432 if (!(pVmcb->ctrl.u32InterceptXcpt & RT_BIT(uXcpt)))
1433 {
1434 pVmcb->ctrl.u32InterceptXcpt |= RT_BIT(uXcpt);
1435 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1436 }
1437}
1438
1439
1440/**
1441 * Clears an exception intercept in the specified VMCB.
1442 *
1443 * @param pVCpu The cross context virtual CPU structure.
1444 * @param pVmcb Pointer to the VM control block.
1445 * @param uXcpt The exception (X86_XCPT_*).
1446 *
1447 * @remarks This takes into account if we're executing a nested-guest and only
1448 * removes the exception intercept if both the guest -and- nested-guest
1449 * are not intercepting it.
1450 */
1451DECLINLINE(void) hmR0SvmClearXcptIntercept(PVMCPU pVCpu, PSVMVMCB pVmcb, uint8_t uXcpt)
1452{
1453 Assert(uXcpt != X86_XCPT_DB);
1454 Assert(uXcpt != X86_XCPT_AC);
1455#ifndef HMSVM_ALWAYS_TRAP_ALL_XCPTS
1456 if (pVmcb->ctrl.u32InterceptXcpt & RT_BIT(uXcpt))
1457 {
1458 bool fRemove = true;
1459# ifdef VBOX_WITH_NESTED_HWVIRT_SVM
1460 /* Only remove the intercept if the nested-guest is also not intercepting it! */
1461 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
1462 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
1463 {
1464 PCSVMNESTEDVMCBCACHE pVmcbNstGstCache = hmR0SvmGetNestedVmcbCache(pVCpu);
1465 fRemove = !(pVmcbNstGstCache->u32InterceptXcpt & RT_BIT(uXcpt));
1466 }
1467# else
1468 RT_NOREF(pVCpu);
1469# endif
1470 if (fRemove)
1471 {
1472 pVmcb->ctrl.u32InterceptXcpt &= ~RT_BIT(uXcpt);
1473 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1474 }
1475 }
1476#else
1477 RT_NOREF3(pVCpu, pVmcb, uXcpt);
1478#endif
1479}
1480
1481
1482/**
1483 * Sets a control intercept in the specified VMCB.
1484 *
1485 * @param pVmcb Pointer to the VM control block.
1486 * @param fCtrlIntercept The control intercept (SVM_CTRL_INTERCEPT_*).
1487 */
1488DECLINLINE(void) hmR0SvmSetCtrlIntercept(PSVMVMCB pVmcb, uint64_t fCtrlIntercept)
1489{
1490 if (!(pVmcb->ctrl.u64InterceptCtrl & fCtrlIntercept))
1491 {
1492 pVmcb->ctrl.u64InterceptCtrl |= fCtrlIntercept;
1493 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1494 }
1495}
1496
1497
1498/**
1499 * Clears a control intercept in the specified VMCB.
1500 *
1501 * @returns @c true if the intercept is still set, @c false otherwise.
1502 * @param pVCpu The cross context virtual CPU structure.
1503 * @param pCtx Pointer to the guest-CPU context.
1504 * @param pVmcb Pointer to the VM control block.
1505 * @param fCtrlIntercept The control intercept (SVM_CTRL_INTERCEPT_*).
1506 *
1507 * @remarks This takes into account if we're executing a nested-guest and only
1508 * removes the control intercept if both the guest -and- nested-guest
1509 * are not intercepting it.
1510 */
1511DECLINLINE(bool) hmR0SvmClearCtrlIntercept(PVMCPU pVCpu, PCCPUMCTX pCtx, PSVMVMCB pVmcb, uint64_t fCtrlIntercept)
1512{
1513 if (pVmcb->ctrl.u64InterceptCtrl & fCtrlIntercept)
1514 {
1515 bool fRemove = true;
1516#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
1517 /* Only remove the control intercept if the nested-guest is also not intercepting it! */
1518 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
1519 {
1520 PCSVMNESTEDVMCBCACHE pVmcbNstGstCache = hmR0SvmGetNestedVmcbCache(pVCpu);
1521 fRemove = !(pVmcbNstGstCache->u64InterceptCtrl & fCtrlIntercept);
1522 }
1523#else
1524 RT_NOREF2(pVCpu, pCtx);
1525#endif
1526 if (fRemove)
1527 {
1528 pVmcb->ctrl.u64InterceptCtrl &= ~fCtrlIntercept;
1529 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1530 }
1531 }
1532
1533 return RT_BOOL(pVmcb->ctrl.u64InterceptCtrl & fCtrlIntercept);
1534}
1535
1536
1537/**
1538 * Exports the guest (or nested-guest) CR0 into the VMCB.
1539 *
1540 * @param pVCpu The cross context virtual CPU structure.
1541 * @param pVmcb Pointer to the VM control block.
1542 *
1543 * @remarks This assumes we always pre-load the guest FPU.
1544 * @remarks No-long-jump zone!!!
1545 */
1546static void hmR0SvmExportGuestCR0(PVMCPU pVCpu, PSVMVMCB pVmcb)
1547{
1548 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1549
1550 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
1551 uint64_t const uGuestCr0 = pCtx->cr0;
1552 uint64_t uShadowCr0 = uGuestCr0;
1553
1554 /* Always enable caching. */
1555 uShadowCr0 &= ~(X86_CR0_CD | X86_CR0_NW);
1556
1557 /* When Nested Paging is not available use shadow page tables and intercept #PFs (latter done in SVMR0SetupVM()). */
1558 if (!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging)
1559 {
1560 uShadowCr0 |= X86_CR0_PG /* Use shadow page tables. */
1561 | X86_CR0_WP; /* Guest CPL 0 writes to its read-only pages should cause a #PF #VMEXIT. */
1562 }
1563
1564 /*
1565 * Use the #MF style of legacy-FPU error reporting for now. Although AMD-V has MSRs that
1566 * lets us isolate the host from it, IEM/REM still needs work to emulate it properly,
1567 * see @bugref{7243#c103}.
1568 */
1569 if (!(uGuestCr0 & X86_CR0_NE))
1570 {
1571 uShadowCr0 |= X86_CR0_NE;
1572 hmR0SvmSetXcptIntercept(pVmcb, X86_XCPT_MF);
1573 }
1574 else
1575 hmR0SvmClearXcptIntercept(pVCpu, pVmcb, X86_XCPT_MF);
1576
1577 /*
1578 * If the shadow and guest CR0 are identical we can avoid intercepting CR0 reads.
1579 *
1580 * CR0 writes still needs interception as PGM requires tracking paging mode changes,
1581 * see @bugref{6944}.
1582 *
1583 * We also don't ever want to honor weird things like cache disable from the guest.
1584 * However, we can avoid intercepting changes to the TS & MP bits by clearing the CR0
1585 * write intercept below and keeping SVM_CTRL_INTERCEPT_CR0_SEL_WRITE instead.
1586 */
1587 if (uShadowCr0 == uGuestCr0)
1588 {
1589 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
1590 {
1591 pVmcb->ctrl.u16InterceptRdCRx &= ~RT_BIT(0);
1592 pVmcb->ctrl.u16InterceptWrCRx &= ~RT_BIT(0);
1593 Assert(pVmcb->ctrl.u64InterceptCtrl & SVM_CTRL_INTERCEPT_CR0_SEL_WRITE);
1594 }
1595 else
1596 {
1597 /* If the nested-hypervisor intercepts CR0 reads/writes, we need to continue intercepting them. */
1598 PCSVMNESTEDVMCBCACHE pVmcbNstGstCache = hmR0SvmGetNestedVmcbCache(pVCpu);
1599 pVmcb->ctrl.u16InterceptRdCRx = (pVmcb->ctrl.u16InterceptRdCRx & ~RT_BIT(0))
1600 | (pVmcbNstGstCache->u16InterceptRdCRx & RT_BIT(0));
1601 pVmcb->ctrl.u16InterceptWrCRx = (pVmcb->ctrl.u16InterceptWrCRx & ~RT_BIT(0))
1602 | (pVmcbNstGstCache->u16InterceptWrCRx & RT_BIT(0));
1603 }
1604 }
1605 else
1606 {
1607 pVmcb->ctrl.u16InterceptRdCRx |= RT_BIT(0);
1608 pVmcb->ctrl.u16InterceptWrCRx |= RT_BIT(0);
1609 }
1610 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1611
1612 Assert(RT_HI_U32(uShadowCr0) == 0);
1613 if (pVmcb->guest.u64CR0 != uShadowCr0)
1614 {
1615 pVmcb->guest.u64CR0 = uShadowCr0;
1616 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1617 }
1618}
1619
1620
1621/**
1622 * Exports the guest (or nested-guest) CR3 into the VMCB.
1623 *
1624 * @param pVCpu The cross context virtual CPU structure.
1625 * @param pVmcb Pointer to the VM control block.
1626 *
1627 * @remarks No-long-jump zone!!!
1628 */
1629static void hmR0SvmExportGuestCR3(PVMCPU pVCpu, PSVMVMCB pVmcb)
1630{
1631 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1632
1633 PVM pVM = pVCpu->CTX_SUFF(pVM);
1634 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
1635 if (pVM->hm.s.fNestedPaging)
1636 {
1637 PGMMODE enmShwPagingMode;
1638#if HC_ARCH_BITS == 32
1639 if (CPUMIsGuestInLongModeEx(pCtx))
1640 enmShwPagingMode = PGMMODE_AMD64_NX;
1641 else
1642#endif
1643 enmShwPagingMode = PGMGetHostMode(pVM);
1644
1645 pVmcb->ctrl.u64NestedPagingCR3 = PGMGetNestedCR3(pVCpu, enmShwPagingMode);
1646 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_NP;
1647 pVmcb->guest.u64CR3 = pCtx->cr3;
1648 Assert(pVmcb->ctrl.u64NestedPagingCR3);
1649 }
1650 else
1651 pVmcb->guest.u64CR3 = PGMGetHyperCR3(pVCpu);
1652
1653 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1654}
1655
1656
1657/**
1658 * Exports the guest (or nested-guest) CR4 into the VMCB.
1659 *
1660 * @param pVCpu The cross context virtual CPU structure.
1661 * @param pVmcb Pointer to the VM control block.
1662 *
1663 * @remarks No-long-jump zone!!!
1664 */
1665static int hmR0SvmExportGuestCR4(PVMCPU pVCpu, PSVMVMCB pVmcb)
1666{
1667 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1668
1669 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
1670 uint64_t uShadowCr4 = pCtx->cr4;
1671 if (!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging)
1672 {
1673 switch (pVCpu->hm.s.enmShadowMode)
1674 {
1675 case PGMMODE_REAL:
1676 case PGMMODE_PROTECTED: /* Protected mode, no paging. */
1677 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1678
1679 case PGMMODE_32_BIT: /* 32-bit paging. */
1680 uShadowCr4 &= ~X86_CR4_PAE;
1681 break;
1682
1683 case PGMMODE_PAE: /* PAE paging. */
1684 case PGMMODE_PAE_NX: /* PAE paging with NX enabled. */
1685 /** Must use PAE paging as we could use physical memory > 4 GB */
1686 uShadowCr4 |= X86_CR4_PAE;
1687 break;
1688
1689 case PGMMODE_AMD64: /* 64-bit AMD paging (long mode). */
1690 case PGMMODE_AMD64_NX: /* 64-bit AMD paging (long mode) with NX enabled. */
1691#ifdef VBOX_ENABLE_64_BITS_GUESTS
1692 break;
1693#else
1694 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1695#endif
1696
1697 default: /* shut up gcc */
1698 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1699 }
1700 }
1701
1702 /* Whether to save/load/restore XCR0 during world switch depends on CR4.OSXSAVE and host+guest XCR0. */
1703 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pCtx->cr4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
1704
1705 /* Avoid intercepting CR4 reads if the guest and shadow CR4 values are identical. */
1706 if (uShadowCr4 == pCtx->cr4)
1707 {
1708 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
1709 pVmcb->ctrl.u16InterceptRdCRx &= ~RT_BIT(4);
1710 else
1711 {
1712 /* If the nested-hypervisor intercepts CR4 reads, we need to continue intercepting them. */
1713 PCSVMNESTEDVMCBCACHE pVmcbNstGstCache = hmR0SvmGetNestedVmcbCache(pVCpu);
1714 pVmcb->ctrl.u16InterceptRdCRx = (pVmcb->ctrl.u16InterceptRdCRx & ~RT_BIT(4))
1715 | (pVmcbNstGstCache->u16InterceptRdCRx & RT_BIT(4));
1716 }
1717 }
1718 else
1719 pVmcb->ctrl.u16InterceptRdCRx |= RT_BIT(4);
1720
1721 /* CR4 writes are always intercepted (both guest, nested-guest) for tracking PGM mode changes. */
1722 Assert(pVmcb->ctrl.u16InterceptWrCRx & RT_BIT(4));
1723
1724 /* Update VMCB with the shadow CR4 the appropriate VMCB clean bits. */
1725 Assert(RT_HI_U32(uShadowCr4) == 0);
1726 pVmcb->guest.u64CR4 = uShadowCr4;
1727 pVmcb->ctrl.u32VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_CRX_EFER | HMSVM_VMCB_CLEAN_INTERCEPTS);
1728
1729 return VINF_SUCCESS;
1730}
1731
1732
1733/**
1734 * Exports the guest (or nested-guest) control registers into the VMCB.
1735 *
1736 * @returns VBox status code.
1737 * @param pVCpu The cross context virtual CPU structure.
1738 * @param pVmcb Pointer to the VM control block.
1739 *
1740 * @remarks No-long-jump zone!!!
1741 */
1742static int hmR0SvmExportGuestControlRegs(PVMCPU pVCpu, PSVMVMCB pVmcb)
1743{
1744 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1745
1746 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_CR_MASK)
1747 {
1748 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_CR0)
1749 hmR0SvmExportGuestCR0(pVCpu, pVmcb);
1750
1751 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_CR2)
1752 {
1753 pVmcb->guest.u64CR2 = pVCpu->cpum.GstCtx.cr2;
1754 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CR2;
1755 }
1756
1757 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_CR3)
1758 hmR0SvmExportGuestCR3(pVCpu, pVmcb);
1759
1760 /* CR4 re-loading is ASSUMED to be done everytime we get in from ring-3! (XCR0) */
1761 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_CR4)
1762 {
1763 int rc = hmR0SvmExportGuestCR4(pVCpu, pVmcb);
1764 if (RT_FAILURE(rc))
1765 return rc;
1766 }
1767
1768 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_GUEST_CR_MASK;
1769 }
1770 return VINF_SUCCESS;
1771}
1772
1773
1774/**
1775 * Exports the guest (or nested-guest) segment registers into the VMCB.
1776 *
1777 * @returns VBox status code.
1778 * @param pVCpu The cross context virtual CPU structure.
1779 * @param pVmcb Pointer to the VM control block.
1780 *
1781 * @remarks No-long-jump zone!!!
1782 */
1783static void hmR0SvmExportGuestSegmentRegs(PVMCPU pVCpu, PSVMVMCB pVmcb)
1784{
1785 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1786 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
1787
1788 /* Guest segment registers. */
1789 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_SREG_MASK)
1790 {
1791 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_CS)
1792 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, &pVmcb->guest, CS, cs);
1793
1794 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_SS)
1795 {
1796 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, &pVmcb->guest, SS, ss);
1797 pVmcb->guest.u8CPL = pCtx->ss.Attr.n.u2Dpl;
1798 }
1799
1800 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_DS)
1801 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, &pVmcb->guest, DS, ds);
1802
1803 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_ES)
1804 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, &pVmcb->guest, ES, es);
1805
1806 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_FS)
1807 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, &pVmcb->guest, FS, fs);
1808
1809 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_GS)
1810 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, &pVmcb->guest, GS, gs);
1811
1812 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_SEG;
1813 }
1814
1815 /* Guest TR. */
1816 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_TR)
1817 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, &pVmcb->guest, TR, tr);
1818
1819 /* Guest LDTR. */
1820 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_LDTR)
1821 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, &pVmcb->guest, LDTR, ldtr);
1822
1823 /* Guest GDTR. */
1824 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_GDTR)
1825 {
1826 pVmcb->guest.GDTR.u32Limit = pCtx->gdtr.cbGdt;
1827 pVmcb->guest.GDTR.u64Base = pCtx->gdtr.pGdt;
1828 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DT;
1829 }
1830
1831 /* Guest IDTR. */
1832 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_IDTR)
1833 {
1834 pVmcb->guest.IDTR.u32Limit = pCtx->idtr.cbIdt;
1835 pVmcb->guest.IDTR.u64Base = pCtx->idtr.pIdt;
1836 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DT;
1837 }
1838
1839 pVCpu->hm.s.fCtxChanged &= ~( HM_CHANGED_GUEST_SREG_MASK
1840 | HM_CHANGED_GUEST_TABLE_MASK);
1841}
1842
1843
1844/**
1845 * Exports the guest (or nested-guest) MSRs into the VMCB.
1846 *
1847 * @param pVCpu The cross context virtual CPU structure.
1848 * @param pVmcb Pointer to the VM control block.
1849 *
1850 * @remarks No-long-jump zone!!!
1851 */
1852static void hmR0SvmExportGuestMsrs(PVMCPU pVCpu, PSVMVMCB pVmcb)
1853{
1854 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1855 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
1856
1857 /* Guest Sysenter MSRs. */
1858 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_SYSENTER_MSR_MASK)
1859 {
1860 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_SYSENTER_CS_MSR)
1861 pVmcb->guest.u64SysEnterCS = pCtx->SysEnter.cs;
1862
1863 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_SYSENTER_EIP_MSR)
1864 pVmcb->guest.u64SysEnterEIP = pCtx->SysEnter.eip;
1865
1866 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_SYSENTER_ESP_MSR)
1867 pVmcb->guest.u64SysEnterESP = pCtx->SysEnter.esp;
1868 }
1869
1870 /*
1871 * Guest EFER MSR.
1872 * AMD-V requires guest EFER.SVME to be set. Weird.
1873 * See AMD spec. 15.5.1 "Basic Operation" | "Canonicalization and Consistency Checks".
1874 */
1875 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_EFER_MSR)
1876 {
1877 pVmcb->guest.u64EFER = pCtx->msrEFER | MSR_K6_EFER_SVME;
1878 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1879 }
1880
1881 /* If the guest isn't in 64-bit mode, clear MSR_K6_LME bit, otherwise SVM expects amd64 shadow paging. */
1882 if ( !CPUMIsGuestInLongModeEx(pCtx)
1883 && (pCtx->msrEFER & MSR_K6_EFER_LME))
1884 {
1885 pVmcb->guest.u64EFER &= ~MSR_K6_EFER_LME;
1886 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1887 }
1888
1889 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_SYSCALL_MSRS)
1890 {
1891 pVmcb->guest.u64STAR = pCtx->msrSTAR;
1892 pVmcb->guest.u64LSTAR = pCtx->msrLSTAR;
1893 pVmcb->guest.u64CSTAR = pCtx->msrCSTAR;
1894 pVmcb->guest.u64SFMASK = pCtx->msrSFMASK;
1895 }
1896
1897 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_KERNEL_GS_BASE)
1898 pVmcb->guest.u64KernelGSBase = pCtx->msrKERNELGSBASE;
1899
1900 pVCpu->hm.s.fCtxChanged &= ~( HM_CHANGED_GUEST_SYSENTER_MSR_MASK
1901 | HM_CHANGED_GUEST_EFER_MSR
1902 | HM_CHANGED_GUEST_SYSCALL_MSRS
1903 | HM_CHANGED_GUEST_KERNEL_GS_BASE);
1904
1905 /*
1906 * Setup the PAT MSR (applicable for Nested Paging only).
1907 *
1908 * While guests can modify and see the modified values through the shadow values,
1909 * we shall not honor any guest modifications of this MSR to ensure caching is always
1910 * enabled similar to how we clear CR0.CD and NW bits.
1911 *
1912 * For nested-guests this needs to always be set as well, see @bugref{7243#c109}.
1913 */
1914 pVmcb->guest.u64PAT = MSR_IA32_CR_PAT_INIT_VAL;
1915
1916 /* Enable the last branch record bit if LBR virtualization is enabled. */
1917 if (pVmcb->ctrl.LbrVirt.n.u1LbrVirt)
1918 pVmcb->guest.u64DBGCTL = MSR_IA32_DEBUGCTL_LBR;
1919}
1920
1921
1922/**
1923 * Exports the guest (or nested-guest) debug state into the VMCB and programs
1924 * the necessary intercepts accordingly.
1925 *
1926 * @param pVCpu The cross context virtual CPU structure.
1927 * @param pVmcb Pointer to the VM control block.
1928 *
1929 * @remarks No-long-jump zone!!!
1930 * @remarks Requires EFLAGS to be up-to-date in the VMCB!
1931 */
1932static void hmR0SvmExportSharedDebugState(PVMCPU pVCpu, PSVMVMCB pVmcb)
1933{
1934 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
1935
1936 /*
1937 * Anyone single stepping on the host side? If so, we'll have to use the
1938 * trap flag in the guest EFLAGS since AMD-V doesn't have a trap flag on
1939 * the VMM level like the VT-x implementations does.
1940 */
1941 bool fInterceptMovDRx = false;
1942 bool const fStepping = pVCpu->hm.s.fSingleInstruction || DBGFIsStepping(pVCpu);
1943 if (fStepping)
1944 {
1945 pVCpu->hm.s.fClearTrapFlag = true;
1946 pVmcb->guest.u64RFlags |= X86_EFL_TF;
1947 fInterceptMovDRx = true; /* Need clean DR6, no guest mess. */
1948 }
1949
1950 if ( fStepping
1951 || (CPUMGetHyperDR7(pVCpu) & X86_DR7_ENABLED_MASK))
1952 {
1953 /*
1954 * Use the combined guest and host DRx values found in the hypervisor
1955 * register set because the debugger has breakpoints active or someone
1956 * is single stepping on the host side.
1957 *
1958 * Note! DBGF expects a clean DR6 state before executing guest code.
1959 */
1960#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
1961 if ( CPUMIsGuestInLongModeEx(pCtx)
1962 && !CPUMIsHyperDebugStateActivePending(pVCpu))
1963 {
1964 CPUMR0LoadHyperDebugState(pVCpu, false /* include DR6 */);
1965 Assert(!CPUMIsGuestDebugStateActivePending(pVCpu));
1966 Assert(CPUMIsHyperDebugStateActivePending(pVCpu));
1967 }
1968 else
1969#endif
1970 if (!CPUMIsHyperDebugStateActive(pVCpu))
1971 {
1972 CPUMR0LoadHyperDebugState(pVCpu, false /* include DR6 */);
1973 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
1974 Assert(CPUMIsHyperDebugStateActive(pVCpu));
1975 }
1976
1977 /* Update DR6 & DR7. (The other DRx values are handled by CPUM one way or the other.) */
1978 if ( pVmcb->guest.u64DR6 != X86_DR6_INIT_VAL
1979 || pVmcb->guest.u64DR7 != CPUMGetHyperDR7(pVCpu))
1980 {
1981 pVmcb->guest.u64DR7 = CPUMGetHyperDR7(pVCpu);
1982 pVmcb->guest.u64DR6 = X86_DR6_INIT_VAL;
1983 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
1984 }
1985
1986 /** @todo If we cared, we could optimize to allow the guest to read registers
1987 * with the same values. */
1988 fInterceptMovDRx = true;
1989 pVCpu->hm.s.fUsingHyperDR7 = true;
1990 Log5(("hmR0SvmExportSharedDebugState: Loaded hyper DRx\n"));
1991 }
1992 else
1993 {
1994 /*
1995 * Update DR6, DR7 with the guest values if necessary.
1996 */
1997 if ( pVmcb->guest.u64DR7 != pCtx->dr[7]
1998 || pVmcb->guest.u64DR6 != pCtx->dr[6])
1999 {
2000 pVmcb->guest.u64DR7 = pCtx->dr[7];
2001 pVmcb->guest.u64DR6 = pCtx->dr[6];
2002 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
2003 }
2004 pVCpu->hm.s.fUsingHyperDR7 = false;
2005
2006 /*
2007 * If the guest has enabled debug registers, we need to load them prior to
2008 * executing guest code so they'll trigger at the right time.
2009 */
2010 if (pCtx->dr[7] & (X86_DR7_ENABLED_MASK | X86_DR7_GD)) /** @todo Why GD? */
2011 {
2012#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
2013 if ( CPUMIsGuestInLongModeEx(pCtx)
2014 && !CPUMIsGuestDebugStateActivePending(pVCpu))
2015 {
2016 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
2017 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
2018 Assert(!CPUMIsHyperDebugStateActivePending(pVCpu));
2019 Assert(CPUMIsGuestDebugStateActivePending(pVCpu));
2020 }
2021 else
2022#endif
2023 if (!CPUMIsGuestDebugStateActive(pVCpu))
2024 {
2025 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
2026 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
2027 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
2028 Assert(CPUMIsGuestDebugStateActive(pVCpu));
2029 }
2030 Log5(("hmR0SvmExportSharedDebugState: Loaded guest DRx\n"));
2031 }
2032 /*
2033 * If no debugging enabled, we'll lazy load DR0-3. We don't need to
2034 * intercept #DB as DR6 is updated in the VMCB.
2035 *
2036 * Note! If we cared and dared, we could skip intercepting \#DB here.
2037 * However, \#DB shouldn't be performance critical, so we'll play safe
2038 * and keep the code similar to the VT-x code and always intercept it.
2039 */
2040#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
2041 else if ( !CPUMIsGuestDebugStateActivePending(pVCpu)
2042 && !CPUMIsGuestDebugStateActive(pVCpu))
2043#else
2044 else if (!CPUMIsGuestDebugStateActive(pVCpu))
2045#endif
2046 {
2047 fInterceptMovDRx = true;
2048 }
2049 }
2050
2051 Assert(pVmcb->ctrl.u32InterceptXcpt & RT_BIT_32(X86_XCPT_DB));
2052 if (fInterceptMovDRx)
2053 {
2054 if ( pVmcb->ctrl.u16InterceptRdDRx != 0xffff
2055 || pVmcb->ctrl.u16InterceptWrDRx != 0xffff)
2056 {
2057 pVmcb->ctrl.u16InterceptRdDRx = 0xffff;
2058 pVmcb->ctrl.u16InterceptWrDRx = 0xffff;
2059 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
2060 }
2061 }
2062 else
2063 {
2064 if ( pVmcb->ctrl.u16InterceptRdDRx
2065 || pVmcb->ctrl.u16InterceptWrDRx)
2066 {
2067 pVmcb->ctrl.u16InterceptRdDRx = 0;
2068 pVmcb->ctrl.u16InterceptWrDRx = 0;
2069 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
2070 }
2071 }
2072 Log4Func(("DR6=%#RX64 DR7=%#RX64\n", pCtx->dr[6], pCtx->dr[7]));
2073}
2074
2075#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
2076/**
2077 * Exports the nested-guest hardware virtualization state into the nested-guest
2078 * VMCB.
2079 *
2080 * @param pVCpu The cross context virtual CPU structure.
2081 * @param pVmcbNstGst Pointer to the nested-guest VM control block.
2082 *
2083 * @remarks No-long-jump zone!!!
2084 */
2085static void hmR0SvmExportGuestHwvirtStateNested(PVMCPU pVCpu, PSVMVMCB pVmcbNstGst)
2086{
2087 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2088
2089 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_HWVIRT)
2090 {
2091 /*
2092 * Ensure the nested-guest pause-filter counters don't exceed the outer guest values esp.
2093 * since SVM doesn't have a preemption timer.
2094 *
2095 * We do this here rather than in hmR0SvmSetupVmcbNested() as we may have been executing the
2096 * nested-guest in IEM incl. PAUSE instructions which would update the pause-filter counters
2097 * and may continue execution in SVM R0 without a nested-guest #VMEXIT in between.
2098 */
2099 PVM pVM = pVCpu->CTX_SUFF(pVM);
2100 PSVMVMCBCTRL pVmcbNstGstCtrl = &pVmcbNstGst->ctrl;
2101 uint16_t const uGuestPauseFilterCount = pVM->hm.s.svm.cPauseFilter;
2102 uint16_t const uGuestPauseFilterThreshold = pVM->hm.s.svm.cPauseFilterThresholdTicks;
2103 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_PAUSE))
2104 {
2105 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
2106 pVmcbNstGstCtrl->u16PauseFilterCount = RT_MIN(pCtx->hwvirt.svm.cPauseFilter, uGuestPauseFilterCount);
2107 pVmcbNstGstCtrl->u16PauseFilterThreshold = RT_MIN(pCtx->hwvirt.svm.cPauseFilterThreshold, uGuestPauseFilterThreshold);
2108 pVmcbNstGstCtrl->u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
2109 }
2110 else
2111 {
2112 pVmcbNstGstCtrl->u16PauseFilterCount = uGuestPauseFilterCount;
2113 pVmcbNstGstCtrl->u16PauseFilterThreshold = uGuestPauseFilterThreshold;
2114 }
2115
2116 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_GUEST_HWVIRT;
2117 }
2118}
2119#endif
2120
2121/**
2122 * Exports the guest APIC TPR state into the VMCB.
2123 *
2124 * @returns VBox status code.
2125 * @param pVCpu The cross context virtual CPU structure.
2126 * @param pVmcb Pointer to the VM control block.
2127 */
2128static int hmR0SvmExportGuestApicTpr(PVMCPU pVCpu, PSVMVMCB pVmcb)
2129{
2130 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_APIC_TPR)
2131 {
2132 PVM pVM = pVCpu->CTX_SUFF(pVM);
2133 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
2134 if ( PDMHasApic(pVM)
2135 && APICIsEnabled(pVCpu))
2136 {
2137 bool fPendingIntr;
2138 uint8_t u8Tpr;
2139 int rc = APICGetTpr(pVCpu, &u8Tpr, &fPendingIntr, NULL /* pu8PendingIrq */);
2140 AssertRCReturn(rc, rc);
2141
2142 /* Assume that we need to trap all TPR accesses and thus need not check on
2143 every #VMEXIT if we should update the TPR. */
2144 Assert(pVmcb->ctrl.IntCtrl.n.u1VIntrMasking);
2145 pVCpu->hm.s.svm.fSyncVTpr = false;
2146
2147 if (!pVM->hm.s.fTPRPatchingActive)
2148 {
2149 /* Bits 3-0 of the VTPR field correspond to bits 7-4 of the TPR (which is the Task-Priority Class). */
2150 pVmcb->ctrl.IntCtrl.n.u8VTPR = (u8Tpr >> 4);
2151
2152 /* If there are interrupts pending, intercept CR8 writes to evaluate ASAP if we
2153 can deliver the interrupt to the guest. */
2154 if (fPendingIntr)
2155 pVmcb->ctrl.u16InterceptWrCRx |= RT_BIT(8);
2156 else
2157 {
2158 pVmcb->ctrl.u16InterceptWrCRx &= ~RT_BIT(8);
2159 pVCpu->hm.s.svm.fSyncVTpr = true;
2160 }
2161
2162 pVmcb->ctrl.u32VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_INT_CTRL);
2163 }
2164 else
2165 {
2166 /* 32-bit guests uses LSTAR MSR for patching guest code which touches the TPR. */
2167 pVmcb->guest.u64LSTAR = u8Tpr;
2168 uint8_t *pbMsrBitmap = (uint8_t *)pVCpu->hm.s.svm.pvMsrBitmap;
2169
2170 /* If there are interrupts pending, intercept LSTAR writes, otherwise don't intercept reads or writes. */
2171 if (fPendingIntr)
2172 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_LSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_INTERCEPT_WRITE);
2173 else
2174 {
2175 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_LSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
2176 pVCpu->hm.s.svm.fSyncVTpr = true;
2177 }
2178 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_IOPM_MSRPM;
2179 }
2180 }
2181 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_APIC_TPR);
2182 }
2183 return VINF_SUCCESS;
2184}
2185
2186
2187/**
2188 * Sets up the exception interrupts required for guest (or nested-guest)
2189 * execution in the VMCB.
2190 *
2191 * @param pVCpu The cross context virtual CPU structure.
2192 * @param pVmcb Pointer to the VM control block.
2193 *
2194 * @remarks No-long-jump zone!!!
2195 */
2196static void hmR0SvmExportGuestXcptIntercepts(PVMCPU pVCpu, PSVMVMCB pVmcb)
2197{
2198 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2199
2200 /* If we modify intercepts from here, please check & adjust hmR0SvmMergeVmcbCtrlsNested() if required. */
2201 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_SVM_GUEST_XCPT_INTERCEPTS)
2202 {
2203 /* Trap #UD for GIM provider (e.g. for hypercalls). */
2204 if (pVCpu->hm.s.fGIMTrapXcptUD)
2205 hmR0SvmSetXcptIntercept(pVmcb, X86_XCPT_UD);
2206 else
2207 hmR0SvmClearXcptIntercept(pVCpu, pVmcb, X86_XCPT_UD);
2208
2209 /* Trap #BP for INT3 debug breakpoints set by the VM debugger. */
2210 if (pVCpu->CTX_SUFF(pVM)->dbgf.ro.cEnabledInt3Breakpoints)
2211 hmR0SvmSetXcptIntercept(pVmcb, X86_XCPT_BP);
2212 else
2213 hmR0SvmClearXcptIntercept(pVCpu, pVmcb, X86_XCPT_BP);
2214
2215 /* The remaining intercepts are handled elsewhere, e.g. in hmR0SvmExportGuestCR0(). */
2216 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_SVM_GUEST_XCPT_INTERCEPTS;
2217 }
2218}
2219
2220
2221#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
2222/**
2223 * Merges guest and nested-guest intercepts for executing the nested-guest using
2224 * hardware-assisted SVM.
2225 *
2226 * This merges the guest and nested-guest intercepts in a way that if the outer
2227 * guest intercept is set we need to intercept it in the nested-guest as
2228 * well.
2229 *
2230 * @param pVCpu The cross context virtual CPU structure.
2231 * @param pVmcbNstGst Pointer to the nested-guest VM control block.
2232 * @param pCtx Pointer to the nested-guest-CPU context.
2233 */
2234static void hmR0SvmMergeVmcbCtrlsNested(PVMCPU pVCpu, PCCPUMCTX pCtx)
2235{
2236 PVM pVM = pVCpu->CTX_SUFF(pVM);
2237 PCSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
2238 PSVMVMCB pVmcbNstGst = pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
2239 PSVMVMCBCTRL pVmcbNstGstCtrl = &pVmcbNstGst->ctrl;
2240
2241 /* Merge the guest's CR intercepts into the nested-guest VMCB. */
2242 pVmcbNstGstCtrl->u16InterceptRdCRx |= pVmcb->ctrl.u16InterceptRdCRx;
2243 pVmcbNstGstCtrl->u16InterceptWrCRx |= pVmcb->ctrl.u16InterceptWrCRx;
2244
2245 /* Always intercept CR4 writes for tracking PGM mode changes. */
2246 pVmcbNstGstCtrl->u16InterceptWrCRx |= RT_BIT(4);
2247
2248 /* Without nested paging, intercept CR3 reads and writes as we load shadow page tables. */
2249 if (!pVM->hm.s.fNestedPaging)
2250 {
2251 pVmcbNstGstCtrl->u16InterceptRdCRx |= RT_BIT(3);
2252 pVmcbNstGstCtrl->u16InterceptWrCRx |= RT_BIT(3);
2253 }
2254
2255 /** @todo Figure out debugging with nested-guests, till then just intercept
2256 * all DR[0-15] accesses. */
2257 pVmcbNstGstCtrl->u16InterceptRdDRx |= 0xffff;
2258 pVmcbNstGstCtrl->u16InterceptWrDRx |= 0xffff;
2259
2260 /*
2261 * Merge the guest's exception intercepts into the nested-guest VMCB.
2262 *
2263 * - \#UD: Exclude these as the outer guest's GIM hypercalls are not applicable
2264 * while executing the nested-guest.
2265 *
2266 * - \#BP: Exclude breakpoints set by the VM debugger for the outer guest. This can
2267 * be tweaked later depending on how we wish to implement breakpoints.
2268 *
2269 * Warning!! This ASSUMES we only intercept \#UD for hypercall purposes and \#BP
2270 * for VM debugger breakpoints, see hmR0SvmExportGuestXcptIntercepts().
2271 */
2272#ifndef HMSVM_ALWAYS_TRAP_ALL_XCPTS
2273 pVmcbNstGstCtrl->u32InterceptXcpt |= (pVmcb->ctrl.u32InterceptXcpt & ~( RT_BIT(X86_XCPT_UD)
2274 | RT_BIT(X86_XCPT_BP)));
2275#else
2276 pVmcbNstGstCtrl->u32InterceptXcpt |= pVmcb->ctrl.u32InterceptXcpt;
2277#endif
2278
2279 /*
2280 * Adjust intercepts while executing the nested-guest that differ from the
2281 * outer guest intercepts.
2282 *
2283 * - VINTR: Exclude the outer guest intercept as we don't need to cause VINTR #VMEXITs
2284 * that belong to the nested-guest to the outer guest.
2285 *
2286 * - VMMCALL: Exclude the outer guest intercept as when it's also not intercepted by
2287 * the nested-guest, the physical CPU raises a \#UD exception as expected.
2288 */
2289 pVmcbNstGstCtrl->u64InterceptCtrl |= (pVmcb->ctrl.u64InterceptCtrl & ~( SVM_CTRL_INTERCEPT_VINTR
2290 | SVM_CTRL_INTERCEPT_VMMCALL))
2291 | HMSVM_MANDATORY_GUEST_CTRL_INTERCEPTS;
2292
2293 Assert( (pVmcbNstGstCtrl->u64InterceptCtrl & HMSVM_MANDATORY_GUEST_CTRL_INTERCEPTS)
2294 == HMSVM_MANDATORY_GUEST_CTRL_INTERCEPTS);
2295
2296 /* Finally, update the VMCB clean bits. */
2297 pVmcbNstGstCtrl->u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
2298}
2299#endif
2300
2301
2302/**
2303 * Selects the appropriate function to run guest code.
2304 *
2305 * @returns VBox status code.
2306 * @param pVCpu The cross context virtual CPU structure.
2307 *
2308 * @remarks No-long-jump zone!!!
2309 */
2310static int hmR0SvmSelectVMRunHandler(PVMCPU pVCpu)
2311{
2312 if (CPUMIsGuestInLongMode(pVCpu))
2313 {
2314#ifndef VBOX_ENABLE_64_BITS_GUESTS
2315 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
2316#endif
2317 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests); /* Guaranteed by hmR3InitFinalizeR0(). */
2318#if HC_ARCH_BITS == 32
2319 /* 32-bit host. We need to switch to 64-bit before running the 64-bit guest. */
2320 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMSwitcherRun64;
2321#else
2322 /* 64-bit host or hybrid host. */
2323 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun64;
2324#endif
2325 }
2326 else
2327 {
2328 /* Guest is not in long mode, use the 32-bit handler. */
2329 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun;
2330 }
2331 return VINF_SUCCESS;
2332}
2333
2334
2335/**
2336 * Enters the AMD-V session.
2337 *
2338 * @returns VBox status code.
2339 * @param pVM The cross context VM structure.
2340 * @param pVCpu The cross context virtual CPU structure.
2341 * @param pCpu Pointer to the CPU info struct.
2342 */
2343VMMR0DECL(int) SVMR0Enter(PVM pVM, PVMCPU pVCpu, PHMGLOBALCPUINFO pCpu)
2344{
2345 AssertPtr(pVM);
2346 AssertPtr(pVCpu);
2347 Assert(pVM->hm.s.svm.fSupported);
2348 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2349 NOREF(pVM); NOREF(pCpu);
2350
2351 LogFlowFunc(("pVM=%p pVCpu=%p\n", pVM, pVCpu));
2352 Assert((pVCpu->hm.s.fCtxChanged & (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_SVM_HOST_GUEST_SHARED_STATE))
2353 == (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_SVM_HOST_GUEST_SHARED_STATE));
2354
2355 pVCpu->hm.s.fLeaveDone = false;
2356 return VINF_SUCCESS;
2357}
2358
2359
2360/**
2361 * Thread-context callback for AMD-V.
2362 *
2363 * @param enmEvent The thread-context event.
2364 * @param pVCpu The cross context virtual CPU structure.
2365 * @param fGlobalInit Whether global VT-x/AMD-V init. is used.
2366 * @thread EMT(pVCpu)
2367 */
2368VMMR0DECL(void) SVMR0ThreadCtxCallback(RTTHREADCTXEVENT enmEvent, PVMCPU pVCpu, bool fGlobalInit)
2369{
2370 NOREF(fGlobalInit);
2371
2372 switch (enmEvent)
2373 {
2374 case RTTHREADCTXEVENT_OUT:
2375 {
2376 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2377 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
2378 VMCPU_ASSERT_EMT(pVCpu);
2379
2380 /* No longjmps (log-flush, locks) in this fragile context. */
2381 VMMRZCallRing3Disable(pVCpu);
2382
2383 if (!pVCpu->hm.s.fLeaveDone)
2384 {
2385 hmR0SvmLeave(pVCpu, false /* fImportState */);
2386 pVCpu->hm.s.fLeaveDone = true;
2387 }
2388
2389 /* Leave HM context, takes care of local init (term). */
2390 int rc = HMR0LeaveCpu(pVCpu);
2391 AssertRC(rc); NOREF(rc);
2392
2393 /* Restore longjmp state. */
2394 VMMRZCallRing3Enable(pVCpu);
2395 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatSwitchPreempt);
2396 break;
2397 }
2398
2399 case RTTHREADCTXEVENT_IN:
2400 {
2401 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2402 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
2403 VMCPU_ASSERT_EMT(pVCpu);
2404
2405 /* No longjmps (log-flush, locks) in this fragile context. */
2406 VMMRZCallRing3Disable(pVCpu);
2407
2408 /*
2409 * Initialize the bare minimum state required for HM. This takes care of
2410 * initializing AMD-V if necessary (onlined CPUs, local init etc.)
2411 */
2412 int rc = HMR0EnterCpu(pVCpu);
2413 AssertRC(rc); NOREF(rc);
2414 Assert((pVCpu->hm.s.fCtxChanged & (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_SVM_HOST_GUEST_SHARED_STATE))
2415 == (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_SVM_HOST_GUEST_SHARED_STATE));
2416
2417 pVCpu->hm.s.fLeaveDone = false;
2418
2419 /* Restore longjmp state. */
2420 VMMRZCallRing3Enable(pVCpu);
2421 break;
2422 }
2423
2424 default:
2425 break;
2426 }
2427}
2428
2429
2430/**
2431 * Saves the host state.
2432 *
2433 * @returns VBox status code.
2434 * @param pVCpu The cross context virtual CPU structure.
2435 *
2436 * @remarks No-long-jump zone!!!
2437 */
2438VMMR0DECL(int) SVMR0ExportHostState(PVMCPU pVCpu)
2439{
2440 NOREF(pVCpu);
2441
2442 /* Nothing to do here. AMD-V does this for us automatically during the world-switch. */
2443 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_HOST_CONTEXT);
2444 return VINF_SUCCESS;
2445}
2446
2447
2448/**
2449 * Exports the guest state from the guest-CPU context into the VMCB.
2450 *
2451 * The CPU state will be loaded from these fields on every successful VM-entry.
2452 * Also sets up the appropriate VMRUN function to execute guest code based on
2453 * the guest CPU mode.
2454 *
2455 * @returns VBox status code.
2456 * @param pVCpu The cross context virtual CPU structure.
2457 *
2458 * @remarks No-long-jump zone!!!
2459 */
2460static int hmR0SvmExportGuestState(PVMCPU pVCpu)
2461{
2462 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExportGuestState, x);
2463
2464 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
2465 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
2466
2467 Assert(pVmcb);
2468 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
2469
2470 pVmcb->guest.u64RIP = pCtx->rip;
2471 pVmcb->guest.u64RSP = pCtx->rsp;
2472 pVmcb->guest.u64RFlags = pCtx->eflags.u32;
2473 pVmcb->guest.u64RAX = pCtx->rax;
2474#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
2475 if (pVmcb->ctrl.IntCtrl.n.u1VGifEnable)
2476 {
2477 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_VGIF);
2478 pVmcb->ctrl.IntCtrl.n.u1VGif = pCtx->hwvirt.fGif;
2479 }
2480#endif
2481
2482 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
2483
2484 int rc = hmR0SvmExportGuestControlRegs(pVCpu, pVmcb);
2485 AssertRCReturnStmt(rc, ASMSetFlags(fEFlags), rc);
2486
2487 hmR0SvmExportGuestSegmentRegs(pVCpu, pVmcb);
2488 hmR0SvmExportGuestMsrs(pVCpu, pVmcb);
2489 hmR0SvmExportGuestXcptIntercepts(pVCpu, pVmcb);
2490
2491 ASMSetFlags(fEFlags);
2492
2493 /* hmR0SvmExportGuestApicTpr() must be called -after- hmR0SvmExportGuestMsrs() as we
2494 otherwise we would overwrite the LSTAR MSR that we use for TPR patching. */
2495 hmR0SvmExportGuestApicTpr(pVCpu, pVmcb);
2496
2497 rc = hmR0SvmSelectVMRunHandler(pVCpu);
2498 AssertRCReturn(rc, rc);
2499
2500 /* Clear any bits that may be set but exported unconditionally or unused/reserved bits. */
2501 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~( HM_CHANGED_GUEST_RIP
2502 | HM_CHANGED_GUEST_RFLAGS
2503 | HM_CHANGED_GUEST_GPRS_MASK
2504 | HM_CHANGED_GUEST_X87
2505 | HM_CHANGED_GUEST_SSE_AVX
2506 | HM_CHANGED_GUEST_OTHER_XSAVE
2507 | HM_CHANGED_GUEST_XCRx
2508 | HM_CHANGED_GUEST_TSC_AUX
2509 | HM_CHANGED_GUEST_OTHER_MSRS
2510 | HM_CHANGED_GUEST_HWVIRT
2511 | (HM_CHANGED_KEEPER_STATE_MASK & ~HM_CHANGED_SVM_GUEST_XCPT_INTERCEPTS)));
2512
2513#ifdef VBOX_STRICT
2514 /*
2515 * All of the guest-CPU state and SVM keeper bits should be exported here by now,
2516 * except for the host-context and/or shared host-guest context bits.
2517 */
2518 uint64_t const fCtxChanged = ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged);
2519 AssertMsg(!(fCtxChanged & (HM_CHANGED_ALL_GUEST & ~HM_CHANGED_SVM_HOST_GUEST_SHARED_STATE)),
2520 ("fCtxChanged=%#RX64\n", fCtxChanged));
2521
2522 /*
2523 * If we need to log state that isn't always imported, we'll need to import them here.
2524 * See hmR0SvmPostRunGuest() for which part of the state is imported uncondtionally.
2525 */
2526 hmR0SvmLogState(pVCpu, pVmcb, "hmR0SvmExportGuestState", 0 /* fFlags */, 0 /* uVerbose */);
2527#endif
2528
2529 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExportGuestState, x);
2530 return VINF_SUCCESS;
2531}
2532
2533
2534#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
2535/**
2536 * Merges the guest and nested-guest MSR permission bitmap.
2537 *
2538 * If the guest is intercepting an MSR we need to intercept it regardless of
2539 * whether the nested-guest is intercepting it or not.
2540 *
2541 * @param pHostCpu Pointer to the physical CPU HM info. struct.
2542 * @param pVCpu The cross context virtual CPU structure.
2543 * @param pCtx Pointer to the nested-guest-CPU context.
2544 *
2545 * @remarks No-long-jmp zone!!!
2546 */
2547DECLINLINE(void) hmR0SvmMergeMsrpmNested(PHMGLOBALCPUINFO pHostCpu, PVMCPU pVCpu, PCCPUMCTX pCtx)
2548{
2549 uint64_t const *pu64GstMsrpm = (uint64_t const *)pVCpu->hm.s.svm.pvMsrBitmap;
2550 uint64_t const *pu64NstGstMsrpm = (uint64_t const *)pCtx->hwvirt.svm.CTX_SUFF(pvMsrBitmap);
2551 uint64_t *pu64DstMsrpm = (uint64_t *)pHostCpu->n.svm.pvNstGstMsrpm;
2552
2553 /* MSRPM bytes from offset 0x1800 are reserved, so we stop merging there. */
2554 uint32_t const offRsvdQwords = 0x1800 >> 3;
2555 for (uint32_t i = 0; i < offRsvdQwords; i++)
2556 pu64DstMsrpm[i] = pu64NstGstMsrpm[i] | pu64GstMsrpm[i];
2557}
2558
2559
2560/**
2561 * Caches the nested-guest VMCB fields before we modify them for execution using
2562 * hardware-assisted SVM.
2563 *
2564 * @returns true if the VMCB was previously already cached, false otherwise.
2565 * @param pCtx Pointer to the guest-CPU context.
2566 *
2567 * @sa HMSvmNstGstVmExitNotify.
2568 */
2569static bool hmR0SvmCacheVmcbNested(PVMCPU pVCpu, PCCPUMCTX pCtx)
2570{
2571 /*
2572 * Cache the nested-guest programmed VMCB fields if we have not cached it yet.
2573 * Otherwise we risk re-caching the values we may have modified, see @bugref{7243#c44}.
2574 *
2575 * Nested-paging CR3 is not saved back into the VMCB on #VMEXIT, hence no need to
2576 * cache and restore it, see AMD spec. 15.25.4 "Nested Paging and VMRUN/#VMEXIT".
2577 */
2578 PSVMNESTEDVMCBCACHE pVmcbNstGstCache = &pVCpu->hm.s.svm.NstGstVmcbCache;
2579 bool const fWasCached = pVmcbNstGstCache->fCacheValid;
2580 if (!fWasCached)
2581 {
2582 PCSVMVMCB pVmcbNstGst = pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
2583 PCSVMVMCBCTRL pVmcbNstGstCtrl = &pVmcbNstGst->ctrl;
2584 pVmcbNstGstCache->u16InterceptRdCRx = pVmcbNstGstCtrl->u16InterceptRdCRx;
2585 pVmcbNstGstCache->u16InterceptWrCRx = pVmcbNstGstCtrl->u16InterceptWrCRx;
2586 pVmcbNstGstCache->u16InterceptRdDRx = pVmcbNstGstCtrl->u16InterceptRdDRx;
2587 pVmcbNstGstCache->u16InterceptWrDRx = pVmcbNstGstCtrl->u16InterceptWrDRx;
2588 pVmcbNstGstCache->u16PauseFilterThreshold = pVmcbNstGstCtrl->u16PauseFilterThreshold;
2589 pVmcbNstGstCache->u16PauseFilterCount = pVmcbNstGstCtrl->u16PauseFilterCount;
2590 pVmcbNstGstCache->u32InterceptXcpt = pVmcbNstGstCtrl->u32InterceptXcpt;
2591 pVmcbNstGstCache->u64InterceptCtrl = pVmcbNstGstCtrl->u64InterceptCtrl;
2592 pVmcbNstGstCache->u64TSCOffset = pVmcbNstGstCtrl->u64TSCOffset;
2593 pVmcbNstGstCache->fVIntrMasking = pVmcbNstGstCtrl->IntCtrl.n.u1VIntrMasking;
2594 pVmcbNstGstCache->fNestedPaging = pVmcbNstGstCtrl->NestedPagingCtrl.n.u1NestedPaging;
2595 pVmcbNstGstCache->fLbrVirt = pVmcbNstGstCtrl->LbrVirt.n.u1LbrVirt;
2596 pVmcbNstGstCache->fCacheValid = true;
2597 Log4Func(("Cached VMCB fields\n"));
2598 }
2599
2600 return fWasCached;
2601}
2602
2603
2604/**
2605 * Sets up the nested-guest VMCB for execution using hardware-assisted SVM.
2606 *
2607 * This is done the first time we enter nested-guest execution using SVM R0
2608 * until the nested-guest \#VMEXIT (not to be confused with physical CPU
2609 * \#VMEXITs which may or may not cause a corresponding nested-guest \#VMEXIT).
2610 *
2611 * @param pVCpu The cross context virtual CPU structure.
2612 */
2613static void hmR0SvmSetupVmcbNested(PVMCPU pVCpu)
2614{
2615 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
2616 PSVMVMCB pVmcbNstGst = pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
2617 PSVMVMCBCTRL pVmcbNstGstCtrl = &pVmcbNstGst->ctrl;
2618
2619 /*
2620 * First cache the nested-guest VMCB fields we may potentially modify.
2621 */
2622 bool const fVmcbCached = hmR0SvmCacheVmcbNested(pVCpu, pCtx);
2623 if (!fVmcbCached)
2624 {
2625 /*
2626 * The IOPM of the nested-guest can be ignored because the the guest always
2627 * intercepts all IO port accesses. Thus, we'll swap to the guest IOPM rather
2628 * than the nested-guest IOPM and swap the field back on the #VMEXIT.
2629 */
2630 pVmcbNstGstCtrl->u64IOPMPhysAddr = g_HCPhysIOBitmap;
2631
2632 /*
2633 * Use the same nested-paging as the outer guest. We can't dynamically switch off
2634 * nested-paging suddenly while executing a VM (see assertion at the end of
2635 * Trap0eHandler() in PGMAllBth.h).
2636 */
2637 pVmcbNstGstCtrl->NestedPagingCtrl.n.u1NestedPaging = pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging;
2638
2639 /* Always enable V_INTR_MASKING as we do not want to allow access to the physical APIC TPR. */
2640 pVmcbNstGstCtrl->IntCtrl.n.u1VIntrMasking = 1;
2641
2642 /*
2643 * Turn off TPR syncing on #VMEXIT for nested-guests as CR8 intercepts are subject
2644 * to the nested-guest intercepts and we always run with V_INTR_MASKING.
2645 */
2646 pVCpu->hm.s.svm.fSyncVTpr = false;
2647
2648#ifdef DEBUG_ramshankar
2649 /* For debugging purposes - copy the LBR info. from outer guest VMCB. */
2650 pVmcbNstGstCtrl->LbrVirt.n.u1LbrVirt = pVmcb->ctrl.LbrVirt.n.u1LbrVirt;
2651#endif
2652
2653 /*
2654 * If we don't expose Virtualized-VMSAVE/VMLOAD feature to the outer guest, we
2655 * need to intercept VMSAVE/VMLOAD instructions executed by the nested-guest.
2656 */
2657 if (!pVCpu->CTX_SUFF(pVM)->cpum.ro.GuestFeatures.fSvmVirtVmsaveVmload)
2658 pVmcbNstGstCtrl->u64InterceptCtrl |= SVM_CTRL_INTERCEPT_VMSAVE
2659 | SVM_CTRL_INTERCEPT_VMLOAD;
2660
2661 /*
2662 * If we don't expose Virtual GIF feature to the outer guest, we need to intercept
2663 * CLGI/STGI instructions executed by the nested-guest.
2664 */
2665 if (!pVCpu->CTX_SUFF(pVM)->cpum.ro.GuestFeatures.fSvmVGif)
2666 pVmcbNstGstCtrl->u64InterceptCtrl |= SVM_CTRL_INTERCEPT_CLGI
2667 | SVM_CTRL_INTERCEPT_STGI;
2668
2669 /* Merge the guest and nested-guest intercepts. */
2670 hmR0SvmMergeVmcbCtrlsNested(pVCpu, pCtx);
2671
2672 /* Update the VMCB clean bits. */
2673 pVmcbNstGstCtrl->u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
2674 }
2675 else
2676 {
2677 Assert(!pVCpu->hm.s.svm.fSyncVTpr);
2678 Assert(pVmcbNstGstCtrl->u64IOPMPhysAddr == g_HCPhysIOBitmap);
2679 Assert(RT_BOOL(pVmcbNstGstCtrl->NestedPagingCtrl.n.u1NestedPaging) == pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
2680 }
2681}
2682
2683
2684/**
2685 * Exports the nested-guest state into the VMCB.
2686 *
2687 * We need to export the entire state as we could be continuing nested-guest
2688 * execution at any point (not just immediately after VMRUN) and thus the VMCB
2689 * can be out-of-sync with the nested-guest state if it was executed in IEM.
2690 *
2691 * @returns VBox status code.
2692 * @param pVCpu The cross context virtual CPU structure.
2693 * @param pCtx Pointer to the guest-CPU context.
2694 *
2695 * @remarks No-long-jump zone!!!
2696 */
2697static int hmR0SvmExportGuestStateNested(PVMCPU pVCpu)
2698{
2699 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExportGuestState, x);
2700
2701 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
2702 PSVMVMCB pVmcbNstGst = pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
2703 Assert(pVmcbNstGst);
2704
2705 hmR0SvmSetupVmcbNested(pVCpu);
2706
2707 pVmcbNstGst->guest.u64RIP = pCtx->rip;
2708 pVmcbNstGst->guest.u64RSP = pCtx->rsp;
2709 pVmcbNstGst->guest.u64RFlags = pCtx->eflags.u32;
2710 pVmcbNstGst->guest.u64RAX = pCtx->rax;
2711
2712 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
2713
2714 int rc = hmR0SvmExportGuestControlRegs(pVCpu, pVmcbNstGst);
2715 AssertRCReturnStmt(rc, ASMSetFlags(fEFlags), rc);
2716
2717 hmR0SvmExportGuestSegmentRegs(pVCpu, pVmcbNstGst);
2718 hmR0SvmExportGuestMsrs(pVCpu, pVmcbNstGst);
2719 hmR0SvmExportGuestHwvirtStateNested(pVCpu, pVmcbNstGst);
2720
2721 ASMSetFlags(fEFlags);
2722
2723 /* Nested VGIF not supported yet. */
2724 Assert(!pVmcbNstGst->ctrl.IntCtrl.n.u1VGifEnable);
2725
2726 rc = hmR0SvmSelectVMRunHandler(pVCpu);
2727 AssertRCReturn(rc, rc);
2728
2729 /* Clear any bits that may be set but exported unconditionally or unused/reserved bits. */
2730 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~( HM_CHANGED_GUEST_RIP
2731 | HM_CHANGED_GUEST_RFLAGS
2732 | HM_CHANGED_GUEST_GPRS_MASK
2733 | HM_CHANGED_GUEST_APIC_TPR
2734 | HM_CHANGED_GUEST_X87
2735 | HM_CHANGED_GUEST_SSE_AVX
2736 | HM_CHANGED_GUEST_OTHER_XSAVE
2737 | HM_CHANGED_GUEST_XCRx
2738 | HM_CHANGED_GUEST_TSC_AUX
2739 | HM_CHANGED_GUEST_OTHER_MSRS
2740 | HM_CHANGED_SVM_GUEST_XCPT_INTERCEPTS
2741 | (HM_CHANGED_KEEPER_STATE_MASK & ~HM_CHANGED_SVM_MASK)));
2742
2743#ifdef VBOX_STRICT
2744 /*
2745 * All of the guest-CPU state and SVM keeper bits should be exported here by now, except
2746 * for the host-context and/or shared host-guest context bits.
2747 */
2748 uint64_t const fCtxChanged = ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged);
2749 AssertMsg(!(fCtxChanged & (HM_CHANGED_ALL_GUEST & ~HM_CHANGED_SVM_HOST_GUEST_SHARED_STATE)),
2750 ("fCtxChanged=%#RX64\n", fCtxChanged));
2751
2752 /*
2753 * If we need to log state that isn't always imported, we'll need to import them here.
2754 * See hmR0SvmPostRunGuest() for which part of the state is imported uncondtionally.
2755 */
2756 hmR0SvmLogState(pVCpu, pVmcbNstGst, "hmR0SvmExportGuestStateNested", 0 /* fFlags */, 0 /* uVerbose */);
2757#endif
2758
2759 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExportGuestState, x);
2760 return rc;
2761}
2762#endif /* VBOX_WITH_NESTED_HWVIRT_SVM */
2763
2764
2765/**
2766 * Exports the state shared between the host and guest (or nested-guest) into
2767 * the VMCB.
2768 *
2769 * @param pVCpu The cross context virtual CPU structure.
2770 * @param pVmcb Pointer to the VM control block.
2771 *
2772 * @remarks No-long-jump zone!!!
2773 */
2774static void hmR0SvmExportSharedState(PVMCPU pVCpu, PSVMVMCB pVmcb)
2775{
2776 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2777 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2778
2779 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_DR_MASK)
2780 {
2781 /** @todo Figure out stepping with nested-guest. */
2782 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
2783 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
2784 hmR0SvmExportSharedDebugState(pVCpu, pVmcb);
2785 else
2786 {
2787 pVmcb->guest.u64DR6 = pCtx->dr[6];
2788 pVmcb->guest.u64DR7 = pCtx->dr[7];
2789 }
2790 }
2791
2792 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_GUEST_DR_MASK;
2793 AssertMsg(!(pVCpu->hm.s.fCtxChanged & HM_CHANGED_SVM_HOST_GUEST_SHARED_STATE),
2794 ("fCtxChanged=%#RX64\n", pVCpu->hm.s.fCtxChanged));
2795}
2796
2797
2798/**
2799 * Worker for SVMR0ImportStateOnDemand.
2800 *
2801 * @param pVCpu The cross context virtual CPU structure.
2802 * @param fWhat What to import, CPUMCTX_EXTRN_XXX.
2803 */
2804static void hmR0SvmImportGuestState(PVMCPU pVCpu, uint64_t fWhat)
2805{
2806 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatImportGuestState, x);
2807
2808 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
2809 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
2810 PCSVMVMCBSTATESAVE pVmcbGuest = &pVmcb->guest;
2811 PCSVMVMCBCTRL pVmcbCtrl = &pVmcb->ctrl;
2812
2813 Log4Func(("fExtrn=%#RX64 fWhat=%#RX64\n", pCtx->fExtrn, fWhat));
2814
2815 /*
2816 * We disable interrupts to make the updating of the state and in particular
2817 * the fExtrn modification atomic wrt to preemption hooks.
2818 */
2819 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
2820
2821 fWhat &= pCtx->fExtrn;
2822 if (fWhat)
2823 {
2824#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
2825 if (fWhat & CPUMCTX_EXTRN_HWVIRT)
2826 {
2827 if ( !CPUMIsGuestInSvmNestedHwVirtMode(pCtx)
2828 && pVmcbCtrl->IntCtrl.n.u1VGifEnable)
2829 {
2830 /* We don't yet support passing VGIF feature to the guest. */
2831 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.svm.fVGif);
2832 pCtx->hwvirt.fGif = pVmcbCtrl->IntCtrl.n.u1VGif;
2833 }
2834 }
2835
2836 if (fWhat & CPUMCTX_EXTRN_HM_SVM_HWVIRT_VIRQ)
2837 {
2838 if ( !pVmcbCtrl->IntCtrl.n.u1VIrqPending
2839 && VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NESTED_GUEST))
2840 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NESTED_GUEST);
2841 }
2842#endif
2843
2844 if (fWhat & CPUMCTX_EXTRN_HM_SVM_INT_SHADOW)
2845 {
2846 if (pVmcbCtrl->IntShadow.n.u1IntShadow)
2847 EMSetInhibitInterruptsPC(pVCpu, pVmcbGuest->u64RIP);
2848 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
2849 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
2850 }
2851
2852 if (fWhat & CPUMCTX_EXTRN_RIP)
2853 pCtx->rip = pVmcbGuest->u64RIP;
2854
2855 if (fWhat & CPUMCTX_EXTRN_RFLAGS)
2856 pCtx->eflags.u32 = pVmcbGuest->u64RFlags;
2857
2858 if (fWhat & CPUMCTX_EXTRN_RSP)
2859 pCtx->rsp = pVmcbGuest->u64RSP;
2860
2861 if (fWhat & CPUMCTX_EXTRN_RAX)
2862 pCtx->rax = pVmcbGuest->u64RAX;
2863
2864 if (fWhat & CPUMCTX_EXTRN_SREG_MASK)
2865 {
2866 if (fWhat & CPUMCTX_EXTRN_CS)
2867 {
2868 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, CS, cs);
2869 /* Correct the CS granularity bit. Haven't seen it being wrong in any other register (yet). */
2870 /** @todo SELM might need to be fixed as it too should not care about the
2871 * granularity bit. See @bugref{6785}. */
2872 if ( !pCtx->cs.Attr.n.u1Granularity
2873 && pCtx->cs.Attr.n.u1Present
2874 && pCtx->cs.u32Limit > UINT32_C(0xfffff))
2875 {
2876 Assert((pCtx->cs.u32Limit & 0xfff) == 0xfff);
2877 pCtx->cs.Attr.n.u1Granularity = 1;
2878 }
2879 HMSVM_ASSERT_SEG_GRANULARITY(pCtx, cs);
2880 }
2881 if (fWhat & CPUMCTX_EXTRN_SS)
2882 {
2883 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, SS, ss);
2884 HMSVM_ASSERT_SEG_GRANULARITY(pCtx, ss);
2885 /*
2886 * Sync the hidden SS DPL field. AMD CPUs have a separate CPL field in the
2887 * VMCB and uses that and thus it's possible that when the CPL changes during
2888 * guest execution that the SS DPL isn't updated by AMD-V. Observed on some
2889 * AMD Fusion CPUs with 64-bit guests.
2890 *
2891 * See AMD spec. 15.5.1 "Basic operation".
2892 */
2893 Assert(!(pVmcbGuest->u8CPL & ~0x3));
2894 uint8_t const uCpl = pVmcbGuest->u8CPL;
2895 if (pCtx->ss.Attr.n.u2Dpl != uCpl)
2896 pCtx->ss.Attr.n.u2Dpl = uCpl & 0x3;
2897 }
2898 if (fWhat & CPUMCTX_EXTRN_DS)
2899 {
2900 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, DS, ds);
2901 HMSVM_ASSERT_SEG_GRANULARITY(pCtx, ds);
2902 }
2903 if (fWhat & CPUMCTX_EXTRN_ES)
2904 {
2905 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, ES, es);
2906 HMSVM_ASSERT_SEG_GRANULARITY(pCtx, es);
2907 }
2908 if (fWhat & CPUMCTX_EXTRN_FS)
2909 {
2910 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, FS, fs);
2911 HMSVM_ASSERT_SEG_GRANULARITY(pCtx, fs);
2912 }
2913 if (fWhat & CPUMCTX_EXTRN_GS)
2914 {
2915 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, GS, gs);
2916 HMSVM_ASSERT_SEG_GRANULARITY(pCtx, gs);
2917 }
2918 }
2919
2920 if (fWhat & CPUMCTX_EXTRN_TABLE_MASK)
2921 {
2922 if (fWhat & CPUMCTX_EXTRN_TR)
2923 {
2924 /*
2925 * Fixup TR attributes so it's compatible with Intel. Important when saved-states
2926 * are used between Intel and AMD, see @bugref{6208#c39}.
2927 * ASSUME that it's normally correct and that we're in 32-bit or 64-bit mode.
2928 */
2929 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, TR, tr);
2930 if (pCtx->tr.Attr.n.u4Type != X86_SEL_TYPE_SYS_386_TSS_BUSY)
2931 {
2932 if ( pCtx->tr.Attr.n.u4Type == X86_SEL_TYPE_SYS_386_TSS_AVAIL
2933 || CPUMIsGuestInLongModeEx(pCtx))
2934 pCtx->tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_386_TSS_BUSY;
2935 else if (pCtx->tr.Attr.n.u4Type == X86_SEL_TYPE_SYS_286_TSS_AVAIL)
2936 pCtx->tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_286_TSS_BUSY;
2937 }
2938 }
2939
2940 if (fWhat & CPUMCTX_EXTRN_LDTR)
2941 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, LDTR, ldtr);
2942
2943 if (fWhat & CPUMCTX_EXTRN_GDTR)
2944 {
2945 pCtx->gdtr.cbGdt = pVmcbGuest->GDTR.u32Limit;
2946 pCtx->gdtr.pGdt = pVmcbGuest->GDTR.u64Base;
2947 }
2948
2949 if (fWhat & CPUMCTX_EXTRN_IDTR)
2950 {
2951 pCtx->idtr.cbIdt = pVmcbGuest->IDTR.u32Limit;
2952 pCtx->idtr.pIdt = pVmcbGuest->IDTR.u64Base;
2953 }
2954 }
2955
2956 if (fWhat & CPUMCTX_EXTRN_SYSCALL_MSRS)
2957 {
2958 pCtx->msrSTAR = pVmcbGuest->u64STAR;
2959 pCtx->msrLSTAR = pVmcbGuest->u64LSTAR;
2960 pCtx->msrCSTAR = pVmcbGuest->u64CSTAR;
2961 pCtx->msrSFMASK = pVmcbGuest->u64SFMASK;
2962 }
2963
2964 if (fWhat & CPUMCTX_EXTRN_SYSENTER_MSRS)
2965 {
2966 pCtx->SysEnter.cs = pVmcbGuest->u64SysEnterCS;
2967 pCtx->SysEnter.eip = pVmcbGuest->u64SysEnterEIP;
2968 pCtx->SysEnter.esp = pVmcbGuest->u64SysEnterESP;
2969 }
2970
2971 if (fWhat & CPUMCTX_EXTRN_KERNEL_GS_BASE)
2972 pCtx->msrKERNELGSBASE = pVmcbGuest->u64KernelGSBase;
2973
2974 if (fWhat & CPUMCTX_EXTRN_DR_MASK)
2975 {
2976 if (fWhat & CPUMCTX_EXTRN_DR6)
2977 {
2978 if (!pVCpu->hm.s.fUsingHyperDR7)
2979 pCtx->dr[6] = pVmcbGuest->u64DR6;
2980 else
2981 CPUMSetHyperDR6(pVCpu, pVmcbGuest->u64DR6);
2982 }
2983
2984 if (fWhat & CPUMCTX_EXTRN_DR7)
2985 {
2986 if (!pVCpu->hm.s.fUsingHyperDR7)
2987 pCtx->dr[7] = pVmcbGuest->u64DR7;
2988 else
2989 Assert(pVmcbGuest->u64DR7 == CPUMGetHyperDR7(pVCpu));
2990 }
2991 }
2992
2993 if (fWhat & CPUMCTX_EXTRN_CR_MASK)
2994 {
2995 if (fWhat & CPUMCTX_EXTRN_CR0)
2996 {
2997 /* We intercept changes to all CR0 bits except maybe TS & MP bits. */
2998 uint64_t const uCr0 = (pCtx->cr0 & ~(X86_CR0_TS | X86_CR0_MP))
2999 | (pVmcbGuest->u64CR0 & (X86_CR0_TS | X86_CR0_MP));
3000 VMMRZCallRing3Disable(pVCpu); /* Calls into PGM which has Log statements. */
3001 CPUMSetGuestCR0(pVCpu, uCr0);
3002 VMMRZCallRing3Enable(pVCpu);
3003 }
3004
3005 if (fWhat & CPUMCTX_EXTRN_CR2)
3006 pCtx->cr2 = pVmcbGuest->u64CR2;
3007
3008 if (fWhat & CPUMCTX_EXTRN_CR3)
3009 {
3010 if ( pVmcbCtrl->NestedPagingCtrl.n.u1NestedPaging
3011 && pCtx->cr3 != pVmcbGuest->u64CR3)
3012 {
3013 CPUMSetGuestCR3(pVCpu, pVmcbGuest->u64CR3);
3014 VMCPU_FF_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3);
3015 }
3016 }
3017
3018 /* Changes to CR4 are always intercepted. */
3019 }
3020
3021 /* Update fExtrn. */
3022 pCtx->fExtrn &= ~fWhat;
3023
3024 /* If everything has been imported, clear the HM keeper bit. */
3025 if (!(pCtx->fExtrn & HMSVM_CPUMCTX_EXTRN_ALL))
3026 {
3027 pCtx->fExtrn &= ~CPUMCTX_EXTRN_KEEPER_HM;
3028 Assert(!pCtx->fExtrn);
3029 }
3030 }
3031 else
3032 Assert(!pCtx->fExtrn || (pCtx->fExtrn & HMSVM_CPUMCTX_EXTRN_ALL));
3033
3034 ASMSetFlags(fEFlags);
3035
3036 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatImportGuestState, x);
3037
3038 /*
3039 * Honor any pending CR3 updates.
3040 *
3041 * Consider this scenario: #VMEXIT -> VMMRZCallRing3Enable() -> do stuff that causes a longjmp
3042 * -> hmR0SvmCallRing3Callback() -> VMMRZCallRing3Disable() -> hmR0SvmImportGuestState()
3043 * -> Sets VMCPU_FF_HM_UPDATE_CR3 pending -> return from the longjmp -> continue with #VMEXIT
3044 * handling -> hmR0SvmImportGuestState() and here we are.
3045 *
3046 * The reason for such complicated handling is because VM-exits that call into PGM expect
3047 * CR3 to be up-to-date and thus any CR3-saves -before- the VM-exit (longjmp) would've
3048 * postponed the CR3 update via the force-flag and cleared CR3 from fExtrn. Any SVM R0
3049 * VM-exit handler that requests CR3 to be saved will end up here and we call PGMUpdateCR3().
3050 *
3051 * The longjmp exit path can't check these CR3 force-flags and call code that takes a lock again,
3052 * and does not process force-flag like regular exits to ring-3 either, we cover for it here.
3053 */
3054 if ( VMMRZCallRing3IsEnabled(pVCpu)
3055 && VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
3056 {
3057 Assert(pCtx->cr3 == pVmcbGuest->u64CR3);
3058 PGMUpdateCR3(pVCpu, pCtx->cr3);
3059 }
3060}
3061
3062
3063/**
3064 * Saves the guest (or nested-guest) state from the VMCB into the guest-CPU
3065 * context.
3066 *
3067 * Currently there is no residual state left in the CPU that is not updated in the
3068 * VMCB.
3069 *
3070 * @returns VBox status code.
3071 * @param pVCpu The cross context virtual CPU structure.
3072 * @param fWhat What to import, CPUMCTX_EXTRN_XXX.
3073 */
3074VMMR0DECL(int) SVMR0ImportStateOnDemand(PVMCPU pVCpu, uint64_t fWhat)
3075{
3076 hmR0SvmImportGuestState(pVCpu, fWhat);
3077 return VINF_SUCCESS;
3078}
3079
3080
3081/**
3082 * Does the necessary state syncing before returning to ring-3 for any reason
3083 * (longjmp, preemption, voluntary exits to ring-3) from AMD-V.
3084 *
3085 * @param pVCpu The cross context virtual CPU structure.
3086 * @param fImportState Whether to import the guest state from the VMCB back
3087 * to the guest-CPU context.
3088 *
3089 * @remarks No-long-jmp zone!!!
3090 */
3091static void hmR0SvmLeave(PVMCPU pVCpu, bool fImportState)
3092{
3093 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
3094 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
3095 Assert(VMMR0IsLogFlushDisabled(pVCpu));
3096
3097 /*
3098 * !!! IMPORTANT !!!
3099 * If you modify code here, make sure to check whether hmR0SvmCallRing3Callback() needs to be updated too.
3100 */
3101
3102 /* Save the guest state if necessary. */
3103 if (fImportState)
3104 hmR0SvmImportGuestState(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
3105
3106 /* Restore host FPU state if necessary and resync on next R0 reentry. */
3107 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
3108 Assert(!CPUMIsGuestFPUStateActive(pVCpu));
3109
3110 /*
3111 * Restore host debug registers if necessary and resync on next R0 reentry.
3112 */
3113#ifdef VBOX_STRICT
3114 if (CPUMIsHyperDebugStateActive(pVCpu))
3115 {
3116 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb; /** @todo nested-guest. */
3117 Assert(pVmcb->ctrl.u16InterceptRdDRx == 0xffff);
3118 Assert(pVmcb->ctrl.u16InterceptWrDRx == 0xffff);
3119 }
3120#endif
3121 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, false /* save DR6 */);
3122 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
3123 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
3124
3125 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatEntry);
3126 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatImportGuestState);
3127 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExportGuestState);
3128 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit1);
3129 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit2);
3130 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
3131
3132 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
3133}
3134
3135
3136/**
3137 * Leaves the AMD-V session.
3138 *
3139 * Only used while returning to ring-3 either due to longjump or exits to
3140 * ring-3.
3141 *
3142 * @returns VBox status code.
3143 * @param pVCpu The cross context virtual CPU structure.
3144 */
3145static int hmR0SvmLeaveSession(PVMCPU pVCpu)
3146{
3147 HM_DISABLE_PREEMPT();
3148 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
3149 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
3150
3151 /* When thread-context hooks are used, we can avoid doing the leave again if we had been preempted before
3152 and done this from the SVMR0ThreadCtxCallback(). */
3153 if (!pVCpu->hm.s.fLeaveDone)
3154 {
3155 hmR0SvmLeave(pVCpu, true /* fImportState */);
3156 pVCpu->hm.s.fLeaveDone = true;
3157 }
3158
3159 /*
3160 * !!! IMPORTANT !!!
3161 * If you modify code here, make sure to check whether hmR0SvmCallRing3Callback() needs to be updated too.
3162 */
3163
3164 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
3165 /* Deregister hook now that we've left HM context before re-enabling preemption. */
3166 VMMR0ThreadCtxHookDisable(pVCpu);
3167
3168 /* Leave HM context. This takes care of local init (term). */
3169 int rc = HMR0LeaveCpu(pVCpu);
3170
3171 HM_RESTORE_PREEMPT();
3172 return rc;
3173}
3174
3175
3176/**
3177 * Does the necessary state syncing before doing a longjmp to ring-3.
3178 *
3179 * @returns VBox status code.
3180 * @param pVCpu The cross context virtual CPU structure.
3181 *
3182 * @remarks No-long-jmp zone!!!
3183 */
3184static int hmR0SvmLongJmpToRing3(PVMCPU pVCpu)
3185{
3186 return hmR0SvmLeaveSession(pVCpu);
3187}
3188
3189
3190/**
3191 * VMMRZCallRing3() callback wrapper which saves the guest state (or restores
3192 * any remaining host state) before we longjump to ring-3 and possibly get
3193 * preempted.
3194 *
3195 * @param pVCpu The cross context virtual CPU structure.
3196 * @param enmOperation The operation causing the ring-3 longjump.
3197 * @param pvUser The user argument (pointer to the possibly
3198 * out-of-date guest-CPU context).
3199 */
3200static DECLCALLBACK(int) hmR0SvmCallRing3Callback(PVMCPU pVCpu, VMMCALLRING3 enmOperation, void *pvUser)
3201{
3202 RT_NOREF_PV(pvUser);
3203
3204 if (enmOperation == VMMCALLRING3_VM_R0_ASSERTION)
3205 {
3206 /*
3207 * !!! IMPORTANT !!!
3208 * If you modify code here, make sure to check whether hmR0SvmLeave() and hmR0SvmLeaveSession() needs
3209 * to be updated too. This is a stripped down version which gets out ASAP trying to not trigger any assertion.
3210 */
3211 VMMRZCallRing3RemoveNotification(pVCpu);
3212 VMMRZCallRing3Disable(pVCpu);
3213 HM_DISABLE_PREEMPT();
3214
3215 /* Restore host FPU state if necessary and resync on next R0 reentry. */
3216 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
3217
3218 /* Restore host debug registers if necessary and resync on next R0 reentry. */
3219 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, false /* save DR6 */);
3220
3221 /* Deregister the hook now that we've left HM context before re-enabling preemption. */
3222 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
3223 VMMR0ThreadCtxHookDisable(pVCpu);
3224
3225 /* Leave HM context. This takes care of local init (term). */
3226 HMR0LeaveCpu(pVCpu);
3227
3228 HM_RESTORE_PREEMPT();
3229 return VINF_SUCCESS;
3230 }
3231
3232 Assert(pVCpu);
3233 Assert(pvUser);
3234 Assert(VMMRZCallRing3IsEnabled(pVCpu));
3235 HMSVM_ASSERT_PREEMPT_SAFE();
3236
3237 VMMRZCallRing3Disable(pVCpu);
3238 Assert(VMMR0IsLogFlushDisabled(pVCpu));
3239
3240 Log4Func(("Calling hmR0SvmLongJmpToRing3\n"));
3241 int rc = hmR0SvmLongJmpToRing3(pVCpu);
3242 AssertRCReturn(rc, rc);
3243
3244 VMMRZCallRing3Enable(pVCpu);
3245 return VINF_SUCCESS;
3246}
3247
3248
3249/**
3250 * Take necessary actions before going back to ring-3.
3251 *
3252 * An action requires us to go back to ring-3. This function does the necessary
3253 * steps before we can safely return to ring-3. This is not the same as longjmps
3254 * to ring-3, this is voluntary.
3255 *
3256 * @returns VBox status code.
3257 * @param pVM The cross context VM structure.
3258 * @param pVCpu The cross context virtual CPU structure.
3259 * @param pCtx Pointer to the guest-CPU context.
3260 * @param rcExit The reason for exiting to ring-3. Can be
3261 * VINF_VMM_UNKNOWN_RING3_CALL.
3262 */
3263static int hmR0SvmExitToRing3(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int rcExit)
3264{
3265 Assert(pVM);
3266 Assert(pVCpu);
3267 Assert(pCtx);
3268 HMSVM_ASSERT_PREEMPT_SAFE();
3269
3270 /* Please, no longjumps here (any logging shouldn't flush jump back to ring-3). NO LOGGING BEFORE THIS POINT! */
3271 VMMRZCallRing3Disable(pVCpu);
3272 Log4Func(("rcExit=%d LocalFF=%#RX32 GlobalFF=%#RX32\n", rcExit, pVCpu->fLocalForcedActions, pVM->fGlobalForcedActions));
3273
3274 /* We need to do this only while truly exiting the "inner loop" back to ring-3 and -not- for any longjmp to ring3. */
3275 if (pVCpu->hm.s.Event.fPending)
3276 {
3277 hmR0SvmPendingEventToTrpmTrap(pVCpu);
3278 Assert(!pVCpu->hm.s.Event.fPending);
3279 }
3280
3281 /* Sync. the necessary state for going back to ring-3. */
3282 hmR0SvmLeaveSession(pVCpu);
3283 STAM_COUNTER_DEC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
3284
3285 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
3286 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR
3287 | CPUM_CHANGED_LDTR
3288 | CPUM_CHANGED_GDTR
3289 | CPUM_CHANGED_IDTR
3290 | CPUM_CHANGED_TR
3291 | CPUM_CHANGED_HIDDEN_SEL_REGS);
3292 if ( pVM->hm.s.fNestedPaging
3293 && CPUMIsGuestPagingEnabledEx(pCtx))
3294 {
3295 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_GLOBAL_TLB_FLUSH);
3296 }
3297
3298 /* Update the exit-to-ring 3 reason. */
3299 pVCpu->hm.s.rcLastExitToR3 = rcExit;
3300
3301 /* On our way back from ring-3 reload the guest state if there is a possibility of it being changed. */
3302 if (rcExit != VINF_EM_RAW_INTERRUPT)
3303 {
3304 Assert(!(pCtx->fExtrn & HMSVM_CPUMCTX_EXTRN_ALL));
3305 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
3306 }
3307
3308 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchExitToR3);
3309
3310 /* We do -not- want any longjmp notifications after this! We must return to ring-3 ASAP. */
3311 VMMRZCallRing3RemoveNotification(pVCpu);
3312 VMMRZCallRing3Enable(pVCpu);
3313
3314 /*
3315 * If we're emulating an instruction, we shouldn't have any TRPM traps pending
3316 * and if we're injecting an event we should have a TRPM trap pending.
3317 */
3318 AssertReturnStmt(rcExit != VINF_EM_RAW_INJECT_TRPM_EVENT || TRPMHasTrap(pVCpu),
3319 pVCpu->hm.s.u32HMError = rcExit,
3320 VERR_SVM_IPE_5);
3321 AssertReturnStmt(rcExit != VINF_EM_RAW_EMULATE_INSTR || !TRPMHasTrap(pVCpu),
3322 pVCpu->hm.s.u32HMError = rcExit,
3323 VERR_SVM_IPE_4);
3324
3325 return rcExit;
3326}
3327
3328
3329/**
3330 * Updates the use of TSC offsetting mode for the CPU and adjusts the necessary
3331 * intercepts.
3332 *
3333 * @param pVM The cross context VM structure.
3334 * @param pVCpu The cross context virtual CPU structure.
3335 * @param pCtx Pointer to the guest-CPU or nested-guest-CPU context.
3336 * @param pVmcb Pointer to the VM control block.
3337 *
3338 * @remarks No-long-jump zone!!!
3339 */
3340static void hmR0SvmUpdateTscOffsetting(PVM pVM, PVMCPU pVCpu, PCCPUMCTX pCtx, PSVMVMCB pVmcb)
3341{
3342 /*
3343 * Avoid intercepting RDTSC/RDTSCP if we determined the host TSC (++) is stable
3344 * and in case of a nested-guest, if the nested-VMCB specifies it is not intercepting
3345 * RDTSC/RDTSCP as well.
3346 */
3347 bool fParavirtTsc;
3348 uint64_t uTscOffset;
3349 bool const fCanUseRealTsc = TMCpuTickCanUseRealTSC(pVM, pVCpu, &uTscOffset, &fParavirtTsc);
3350
3351 bool fIntercept;
3352 if (fCanUseRealTsc)
3353 fIntercept = hmR0SvmClearCtrlIntercept(pVCpu, pCtx, pVmcb, SVM_CTRL_INTERCEPT_RDTSC | SVM_CTRL_INTERCEPT_RDTSCP);
3354 else
3355 {
3356 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_RDTSC | SVM_CTRL_INTERCEPT_RDTSCP);
3357 fIntercept = true;
3358 }
3359
3360 if (!fIntercept)
3361 {
3362 /* Apply the nested-guest VMCB's TSC offset over the guest TSC offset. */
3363 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
3364 uTscOffset = HMSvmNstGstApplyTscOffset(pVCpu, uTscOffset);
3365
3366 /* Update the TSC offset in the VMCB and the relevant clean bits. */
3367 pVmcb->ctrl.u64TSCOffset = uTscOffset;
3368 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
3369
3370 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
3371 }
3372 else
3373 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
3374
3375 /* Currently neither Hyper-V nor KVM need to update their paravirt. TSC
3376 information before every VM-entry, hence we have nothing to do here at the moment. */
3377 if (fParavirtTsc)
3378 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscParavirt);
3379}
3380
3381
3382/**
3383 * Sets an event as a pending event to be injected into the guest.
3384 *
3385 * @param pVCpu The cross context virtual CPU structure.
3386 * @param pEvent Pointer to the SVM event.
3387 * @param GCPtrFaultAddress The fault-address (CR2) in case it's a
3388 * page-fault.
3389 *
3390 * @remarks Statistics counter assumes this is a guest event being reflected to
3391 * the guest i.e. 'StatInjectPendingReflect' is incremented always.
3392 */
3393DECLINLINE(void) hmR0SvmSetPendingEvent(PVMCPU pVCpu, PSVMEVENT pEvent, RTGCUINTPTR GCPtrFaultAddress)
3394{
3395 Assert(!pVCpu->hm.s.Event.fPending);
3396 Assert(pEvent->n.u1Valid);
3397
3398 pVCpu->hm.s.Event.u64IntInfo = pEvent->u;
3399 pVCpu->hm.s.Event.fPending = true;
3400 pVCpu->hm.s.Event.GCPtrFaultAddress = GCPtrFaultAddress;
3401
3402 Log4Func(("u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u, pEvent->n.u8Vector,
3403 (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
3404}
3405
3406
3407/**
3408 * Sets an invalid-opcode (\#UD) exception as pending-for-injection into the VM.
3409 *
3410 * @param pVCpu The cross context virtual CPU structure.
3411 */
3412DECLINLINE(void) hmR0SvmSetPendingXcptUD(PVMCPU pVCpu)
3413{
3414 SVMEVENT Event;
3415 Event.u = 0;
3416 Event.n.u1Valid = 1;
3417 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3418 Event.n.u8Vector = X86_XCPT_UD;
3419 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3420}
3421
3422
3423/**
3424 * Sets a debug (\#DB) exception as pending-for-injection into the VM.
3425 *
3426 * @param pVCpu The cross context virtual CPU structure.
3427 */
3428DECLINLINE(void) hmR0SvmSetPendingXcptDB(PVMCPU pVCpu)
3429{
3430 SVMEVENT Event;
3431 Event.u = 0;
3432 Event.n.u1Valid = 1;
3433 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3434 Event.n.u8Vector = X86_XCPT_DB;
3435 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3436}
3437
3438
3439/**
3440 * Sets a page fault (\#PF) exception as pending-for-injection into the VM.
3441 *
3442 * @param pVCpu The cross context virtual CPU structure.
3443 * @param pCtx Pointer to the guest-CPU context.
3444 * @param u32ErrCode The error-code for the page-fault.
3445 * @param uFaultAddress The page fault address (CR2).
3446 *
3447 * @remarks This updates the guest CR2 with @a uFaultAddress!
3448 */
3449DECLINLINE(void) hmR0SvmSetPendingXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t u32ErrCode, RTGCUINTPTR uFaultAddress)
3450{
3451 SVMEVENT Event;
3452 Event.u = 0;
3453 Event.n.u1Valid = 1;
3454 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3455 Event.n.u8Vector = X86_XCPT_PF;
3456 Event.n.u1ErrorCodeValid = 1;
3457 Event.n.u32ErrorCode = u32ErrCode;
3458
3459 /* Update CR2 of the guest. */
3460 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR2);
3461 if (pCtx->cr2 != uFaultAddress)
3462 {
3463 pCtx->cr2 = uFaultAddress;
3464 /* The VMCB clean bit for CR2 will be updated while re-loading the guest state. */
3465 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CR2);
3466 }
3467
3468 hmR0SvmSetPendingEvent(pVCpu, &Event, uFaultAddress);
3469}
3470
3471
3472/**
3473 * Sets a math-fault (\#MF) exception as pending-for-injection into the VM.
3474 *
3475 * @param pVCpu The cross context virtual CPU structure.
3476 */
3477DECLINLINE(void) hmR0SvmSetPendingXcptMF(PVMCPU pVCpu)
3478{
3479 SVMEVENT Event;
3480 Event.u = 0;
3481 Event.n.u1Valid = 1;
3482 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3483 Event.n.u8Vector = X86_XCPT_MF;
3484 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3485}
3486
3487
3488/**
3489 * Sets a double fault (\#DF) exception as pending-for-injection into the VM.
3490 *
3491 * @param pVCpu The cross context virtual CPU structure.
3492 */
3493DECLINLINE(void) hmR0SvmSetPendingXcptDF(PVMCPU pVCpu)
3494{
3495 SVMEVENT Event;
3496 Event.u = 0;
3497 Event.n.u1Valid = 1;
3498 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3499 Event.n.u8Vector = X86_XCPT_DF;
3500 Event.n.u1ErrorCodeValid = 1;
3501 Event.n.u32ErrorCode = 0;
3502 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3503}
3504
3505
3506/**
3507 * Injects an event into the guest upon VMRUN by updating the relevant field
3508 * in the VMCB.
3509 *
3510 * @param pVCpu The cross context virtual CPU structure.
3511 * @param pVmcb Pointer to the guest VM control block.
3512 * @param pEvent Pointer to the event.
3513 *
3514 * @remarks No-long-jump zone!!!
3515 * @remarks Requires CR0!
3516 */
3517DECLINLINE(void) hmR0SvmInjectEventVmcb(PVMCPU pVCpu, PSVMVMCB pVmcb, PSVMEVENT pEvent)
3518{
3519 Assert(!pVmcb->ctrl.EventInject.n.u1Valid);
3520 pVmcb->ctrl.EventInject.u = pEvent->u;
3521 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[pEvent->n.u8Vector & MASK_INJECT_IRQ_STAT]);
3522 RT_NOREF(pVCpu);
3523
3524 Log4Func(("u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u, pEvent->n.u8Vector,
3525 (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
3526}
3527
3528
3529
3530/**
3531 * Converts any TRPM trap into a pending HM event. This is typically used when
3532 * entering from ring-3 (not longjmp returns).
3533 *
3534 * @param pVCpu The cross context virtual CPU structure.
3535 */
3536static void hmR0SvmTrpmTrapToPendingEvent(PVMCPU pVCpu)
3537{
3538 Assert(TRPMHasTrap(pVCpu));
3539 Assert(!pVCpu->hm.s.Event.fPending);
3540
3541 uint8_t uVector;
3542 TRPMEVENT enmTrpmEvent;
3543 RTGCUINT uErrCode;
3544 RTGCUINTPTR GCPtrFaultAddress;
3545 uint8_t cbInstr;
3546
3547 int rc = TRPMQueryTrapAll(pVCpu, &uVector, &enmTrpmEvent, &uErrCode, &GCPtrFaultAddress, &cbInstr);
3548 AssertRC(rc);
3549
3550 SVMEVENT Event;
3551 Event.u = 0;
3552 Event.n.u1Valid = 1;
3553 Event.n.u8Vector = uVector;
3554
3555 /* Refer AMD spec. 15.20 "Event Injection" for the format. */
3556 if (enmTrpmEvent == TRPM_TRAP)
3557 {
3558 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3559 switch (uVector)
3560 {
3561 case X86_XCPT_NMI:
3562 {
3563 Event.n.u3Type = SVM_EVENT_NMI;
3564 break;
3565 }
3566
3567 case X86_XCPT_PF:
3568 case X86_XCPT_DF:
3569 case X86_XCPT_TS:
3570 case X86_XCPT_NP:
3571 case X86_XCPT_SS:
3572 case X86_XCPT_GP:
3573 case X86_XCPT_AC:
3574 {
3575 Event.n.u1ErrorCodeValid = 1;
3576 Event.n.u32ErrorCode = uErrCode;
3577 break;
3578 }
3579 }
3580 }
3581 else if (enmTrpmEvent == TRPM_HARDWARE_INT)
3582 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
3583 else if (enmTrpmEvent == TRPM_SOFTWARE_INT)
3584 Event.n.u3Type = SVM_EVENT_SOFTWARE_INT;
3585 else
3586 AssertMsgFailed(("Invalid TRPM event type %d\n", enmTrpmEvent));
3587
3588 rc = TRPMResetTrap(pVCpu);
3589 AssertRC(rc);
3590
3591 Log4(("TRPM->HM event: u=%#RX64 u8Vector=%#x uErrorCodeValid=%RTbool uErrorCode=%#RX32\n", Event.u, Event.n.u8Vector,
3592 !!Event.n.u1ErrorCodeValid, Event.n.u32ErrorCode));
3593
3594 hmR0SvmSetPendingEvent(pVCpu, &Event, GCPtrFaultAddress);
3595}
3596
3597
3598/**
3599 * Converts any pending SVM event into a TRPM trap. Typically used when leaving
3600 * AMD-V to execute any instruction.
3601 *
3602 * @param pVCpu The cross context virtual CPU structure.
3603 */
3604static void hmR0SvmPendingEventToTrpmTrap(PVMCPU pVCpu)
3605{
3606 Assert(pVCpu->hm.s.Event.fPending);
3607 Assert(TRPMQueryTrap(pVCpu, NULL /* pu8TrapNo */, NULL /* pEnmType */) == VERR_TRPM_NO_ACTIVE_TRAP);
3608
3609 SVMEVENT Event;
3610 Event.u = pVCpu->hm.s.Event.u64IntInfo;
3611
3612 uint8_t uVector = Event.n.u8Vector;
3613 uint8_t uVectorType = Event.n.u3Type;
3614 TRPMEVENT enmTrapType = HMSvmEventToTrpmEventType(&Event);
3615
3616 Log4(("HM event->TRPM: uVector=%#x enmTrapType=%d\n", uVector, uVectorType));
3617
3618 int rc = TRPMAssertTrap(pVCpu, uVector, enmTrapType);
3619 AssertRC(rc);
3620
3621 if (Event.n.u1ErrorCodeValid)
3622 TRPMSetErrorCode(pVCpu, Event.n.u32ErrorCode);
3623
3624 if ( uVectorType == SVM_EVENT_EXCEPTION
3625 && uVector == X86_XCPT_PF)
3626 {
3627 TRPMSetFaultAddress(pVCpu, pVCpu->hm.s.Event.GCPtrFaultAddress);
3628 Assert(pVCpu->hm.s.Event.GCPtrFaultAddress == CPUMGetGuestCR2(pVCpu));
3629 }
3630 else if (uVectorType == SVM_EVENT_SOFTWARE_INT)
3631 {
3632 AssertMsg( uVectorType == SVM_EVENT_SOFTWARE_INT
3633 || (uVector == X86_XCPT_BP || uVector == X86_XCPT_OF),
3634 ("Invalid vector: uVector=%#x uVectorType=%#x\n", uVector, uVectorType));
3635 TRPMSetInstrLength(pVCpu, pVCpu->hm.s.Event.cbInstr);
3636 }
3637 pVCpu->hm.s.Event.fPending = false;
3638}
3639
3640
3641/**
3642 * Checks if the guest (or nested-guest) has an interrupt shadow active right
3643 * now.
3644 *
3645 * @returns @c true if the interrupt shadow is active, @c false otherwise.
3646 * @param pVCpu The cross context virtual CPU structure.
3647 * @param pCtx Pointer to the guest-CPU context.
3648 *
3649 * @remarks No-long-jump zone!!!
3650 * @remarks Has side-effects with VMCPU_FF_INHIBIT_INTERRUPTS force-flag.
3651 */
3652DECLINLINE(bool) hmR0SvmIsIntrShadowActive(PVMCPU pVCpu, PCCPUMCTX pCtx)
3653{
3654 /*
3655 * Instructions like STI and MOV SS inhibit interrupts till the next instruction
3656 * completes. Check if we should inhibit interrupts or clear any existing
3657 * interrupt inhibition.
3658 */
3659 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
3660 {
3661 if (pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
3662 {
3663 /*
3664 * We can clear the inhibit force flag as even if we go back to the recompiler
3665 * without executing guest code in AMD-V, the flag's condition to be cleared is
3666 * met and thus the cleared state is correct.
3667 */
3668 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
3669 return false;
3670 }
3671 return true;
3672 }
3673 return false;
3674}
3675
3676
3677/**
3678 * Sets the virtual interrupt intercept control in the VMCB.
3679 *
3680 * @param pVCpu The cross context virtual CPU structure.
3681 * @param pVmcb Pointer to the VM control block.
3682 * @param pCtx Pointer to the guest-CPU context.
3683 */
3684DECLINLINE(void) hmR0SvmSetIntWindowExiting(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
3685{
3686 /*
3687 * When AVIC isn't supported, set up an interrupt window to cause a #VMEXIT when the guest
3688 * is ready to accept interrupts. At #VMEXIT, we then get the interrupt from the APIC
3689 * (updating ISR at the right time) and inject the interrupt.
3690 *
3691 * With AVIC is supported, we could make use of the asynchronously delivery without
3692 * #VMEXIT and we would be passing the AVIC page to SVM.
3693 *
3694 * In AMD-V, an interrupt window is achieved using a combination of V_IRQ (an interrupt
3695 * is pending), V_IGN_TPR (ignore TPR priorities) and the VINTR intercept all being set.
3696 */
3697#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
3698 /*
3699 * Currently we don't overlay interupt windows and if there's any V_IRQ pending in the
3700 * nested-guest VMCB, we avoid setting up any interrupt window on behalf of the outer
3701 * guest.
3702 */
3703 /** @todo Does this mean we end up prioritizing virtual interrupt
3704 * delivery/window over a physical interrupt (from the outer guest)
3705 * might be pending? */
3706 bool const fEnableIntWindow = !VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NESTED_GUEST);
3707 if (!fEnableIntWindow)
3708 {
3709 Assert(CPUMIsGuestInSvmNestedHwVirtMode(pCtx)); RT_NOREF(pCtx);
3710 Log4(("Nested-guest V_IRQ already pending\n"));
3711 }
3712#else
3713 RT_NOREF2(pVCpu, pCtx);
3714 bool const fEnableIntWindow = true;
3715#endif
3716 if (fEnableIntWindow)
3717 {
3718 Assert(pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR);
3719 pVmcb->ctrl.IntCtrl.n.u1VIrqPending = 1;
3720 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INT_CTRL;
3721 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_VINTR);
3722 Log4(("Set VINTR intercept\n"));
3723 }
3724}
3725
3726
3727/**
3728 * Clears the virtual interrupt intercept control in the VMCB as
3729 * we are figured the guest is unable process any interrupts
3730 * at this point of time.
3731 *
3732 * @param pVCpu The cross context virtual CPU structure.
3733 * @param pVmcb Pointer to the VM control block.
3734 * @param pCtx Pointer to the guest-CPU context.
3735 */
3736DECLINLINE(void) hmR0SvmClearIntWindowExiting(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
3737{
3738 PSVMVMCBCTRL pVmcbCtrl = &pVmcb->ctrl;
3739 if ( pVmcbCtrl->IntCtrl.n.u1VIrqPending
3740 || (pVmcbCtrl->u64InterceptCtrl & SVM_CTRL_INTERCEPT_VINTR))
3741 {
3742 pVmcbCtrl->IntCtrl.n.u1VIrqPending = 0;
3743 pVmcbCtrl->u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INT_CTRL;
3744 hmR0SvmClearCtrlIntercept(pVCpu, pCtx, pVmcb, SVM_CTRL_INTERCEPT_VINTR);
3745 Log4(("Cleared VINTR intercept\n"));
3746 }
3747}
3748
3749#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
3750/**
3751 * Evaluates the event to be delivered to the nested-guest and sets it as the
3752 * pending event.
3753 *
3754 * @returns VBox strict status code.
3755 * @param pVCpu The cross context virtual CPU structure.
3756 * @param pCtx Pointer to the guest-CPU context.
3757 */
3758static VBOXSTRICTRC hmR0SvmEvaluatePendingEventNested(PVMCPU pVCpu, PCPUMCTX pCtx)
3759{
3760 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
3761 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_HWVIRT
3762 | CPUMCTX_EXTRN_RFLAGS
3763 | CPUMCTX_EXTRN_HM_SVM_INT_SHADOW
3764 | CPUMCTX_EXTRN_HM_SVM_HWVIRT_VIRQ);
3765
3766 Assert(!pVCpu->hm.s.Event.fPending);
3767 Assert(pCtx->hwvirt.fGif);
3768 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
3769 Assert(pVmcb);
3770
3771 bool const fVirtualGif = CPUMGetSvmNstGstVGif(pCtx);
3772 bool const fIntShadow = hmR0SvmIsIntrShadowActive(pVCpu, pCtx);
3773 bool const fBlockNmi = VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS);
3774
3775 Log4Func(("fVirtualGif=%RTbool fBlockNmi=%RTbool fIntShadow=%RTbool fIntPending=%RTbool fNmiPending=%RTbool\n",
3776 fVirtualGif, fBlockNmi, fIntShadow, VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC),
3777 VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)));
3778
3779 /** @todo SMI. SMIs take priority over NMIs. */
3780
3781 /*
3782 * Check if the guest can receive NMIs.
3783 * Nested NMIs are not allowed, see AMD spec. 8.1.4 "Masking External Interrupts".
3784 * NMIs take priority over maskable interrupts, see AMD spec. 8.5 "Priorities".
3785 */
3786 if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)
3787 && !fBlockNmi)
3788 {
3789 if ( fVirtualGif
3790 && !fIntShadow)
3791 {
3792 if (CPUMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_NMI))
3793 {
3794 Log4(("Intercepting NMI -> #VMEXIT\n"));
3795 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, IEM_CPUMCTX_EXTRN_SVM_VMEXIT_MASK);
3796 return IEMExecSvmVmexit(pVCpu, SVM_EXIT_NMI, 0, 0);
3797 }
3798
3799 Log4(("Setting NMI pending for injection\n"));
3800 SVMEVENT Event;
3801 Event.u = 0;
3802 Event.n.u1Valid = 1;
3803 Event.n.u8Vector = X86_XCPT_NMI;
3804 Event.n.u3Type = SVM_EVENT_NMI;
3805 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3806 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
3807 }
3808 else if (!fVirtualGif)
3809 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_STGI);
3810 else
3811 hmR0SvmSetIntWindowExiting(pVCpu, pVmcb, pCtx);
3812 }
3813 /*
3814 * Check if the nested-guest can receive external interrupts (generated by the guest's
3815 * PIC/APIC).
3816 *
3817 * External intercepts, NMI, SMI etc. from the physical CPU are -always- intercepted
3818 * when executing using hardware-assisted SVM, see HMSVM_MANDATORY_GUEST_CTRL_INTERCEPTS.
3819 *
3820 * External interrupts that are generated for the outer guest may be intercepted
3821 * depending on how the nested-guest VMCB was programmed by guest software.
3822 *
3823 * Physical interrupts always take priority over virtual interrupts,
3824 * see AMD spec. 15.21.4 "Injecting Virtual (INTR) Interrupts".
3825 */
3826 else if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)
3827 && !pVCpu->hm.s.fSingleInstruction)
3828 {
3829 if ( fVirtualGif
3830 && !fIntShadow
3831 && CPUMCanSvmNstGstTakePhysIntr(pVCpu, pCtx))
3832 {
3833 if (CPUMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_INTR))
3834 {
3835 Log4(("Intercepting INTR -> #VMEXIT\n"));
3836 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, IEM_CPUMCTX_EXTRN_SVM_VMEXIT_MASK);
3837 return IEMExecSvmVmexit(pVCpu, SVM_EXIT_INTR, 0, 0);
3838 }
3839
3840 uint8_t u8Interrupt;
3841 int rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
3842 if (RT_SUCCESS(rc))
3843 {
3844 Log4(("Setting external interrupt %#x pending for injection\n", u8Interrupt));
3845 SVMEVENT Event;
3846 Event.u = 0;
3847 Event.n.u1Valid = 1;
3848 Event.n.u8Vector = u8Interrupt;
3849 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
3850 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3851 }
3852 else if (rc == VERR_APIC_INTR_MASKED_BY_TPR)
3853 {
3854 /*
3855 * AMD-V has no TPR thresholding feature. TPR and the force-flag will be
3856 * updated eventually when the TPR is written by the guest.
3857 */
3858 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchTprMaskedIrq);
3859 }
3860 else
3861 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
3862 }
3863 else if (!fVirtualGif)
3864 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_STGI);
3865 else
3866 hmR0SvmSetIntWindowExiting(pVCpu, pVmcb, pCtx);
3867 }
3868
3869 return VINF_SUCCESS;
3870}
3871#endif
3872
3873/**
3874 * Evaluates the event to be delivered to the guest and sets it as the pending
3875 * event.
3876 *
3877 * @param pVCpu The cross context virtual CPU structure.
3878 * @param pCtx Pointer to the guest-CPU context.
3879 */
3880static void hmR0SvmEvaluatePendingEvent(PVMCPU pVCpu, PCPUMCTX pCtx)
3881{
3882 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
3883 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_HWVIRT
3884 | CPUMCTX_EXTRN_RFLAGS
3885 | CPUMCTX_EXTRN_HM_SVM_INT_SHADOW);
3886
3887 Assert(!pVCpu->hm.s.Event.fPending);
3888 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
3889 Assert(pVmcb);
3890
3891#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
3892 bool const fGif = pCtx->hwvirt.fGif;
3893#else
3894 bool const fGif = true;
3895#endif
3896 bool const fIntShadow = hmR0SvmIsIntrShadowActive(pVCpu, pCtx);
3897 bool const fBlockInt = !(pCtx->eflags.u32 & X86_EFL_IF);
3898 bool const fBlockNmi = VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS);
3899
3900 Log4Func(("fGif=%RTbool fBlockNmi=%RTbool fBlockInt=%RTbool fIntShadow=%RTbool fIntPending=%RTbool NMI pending=%RTbool\n",
3901 fGif, fBlockNmi, fBlockInt, fIntShadow,
3902 VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC),
3903 VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)));
3904
3905 /** @todo SMI. SMIs take priority over NMIs. */
3906
3907 /*
3908 * Check if the guest can receive NMIs.
3909 * Nested NMIs are not allowed, see AMD spec. 8.1.4 "Masking External Interrupts".
3910 * NMIs take priority over maskable interrupts, see AMD spec. 8.5 "Priorities".
3911 */
3912 if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)
3913 && !fBlockNmi)
3914 {
3915 if ( fGif
3916 && !fIntShadow)
3917 {
3918 Log4(("Setting NMI pending for injection\n"));
3919 SVMEVENT Event;
3920 Event.u = 0;
3921 Event.n.u1Valid = 1;
3922 Event.n.u8Vector = X86_XCPT_NMI;
3923 Event.n.u3Type = SVM_EVENT_NMI;
3924 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3925 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
3926 }
3927 else if (!fGif)
3928 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_STGI);
3929 else
3930 hmR0SvmSetIntWindowExiting(pVCpu, pVmcb, pCtx);
3931 }
3932 /*
3933 * Check if the guest can receive external interrupts (PIC/APIC). Once PDMGetInterrupt()
3934 * returns a valid interrupt we -must- deliver the interrupt. We can no longer re-request
3935 * it from the APIC device.
3936 */
3937 else if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)
3938 && !pVCpu->hm.s.fSingleInstruction)
3939 {
3940 if ( fGif
3941 && !fBlockInt
3942 && !fIntShadow)
3943 {
3944 uint8_t u8Interrupt;
3945 int rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
3946 if (RT_SUCCESS(rc))
3947 {
3948 Log4(("Setting external interrupt %#x pending for injection\n", u8Interrupt));
3949 SVMEVENT Event;
3950 Event.u = 0;
3951 Event.n.u1Valid = 1;
3952 Event.n.u8Vector = u8Interrupt;
3953 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
3954 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3955 }
3956 else if (rc == VERR_APIC_INTR_MASKED_BY_TPR)
3957 {
3958 /*
3959 * AMD-V has no TPR thresholding feature. TPR and the force-flag will be
3960 * updated eventually when the TPR is written by the guest.
3961 */
3962 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchTprMaskedIrq);
3963 }
3964 else
3965 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
3966 }
3967 else if (!fGif)
3968 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_STGI);
3969 else
3970 hmR0SvmSetIntWindowExiting(pVCpu, pVmcb, pCtx);
3971 }
3972}
3973
3974
3975/**
3976 * Injects any pending events into the guest (or nested-guest).
3977 *
3978 * @param pVCpu The cross context virtual CPU structure.
3979 * @param pCtx Pointer to the guest-CPU context.
3980 * @param pVmcb Pointer to the VM control block.
3981 *
3982 * @remarks Must only be called when we are guaranteed to enter
3983 * hardware-assisted SVM execution and not return to ring-3
3984 * prematurely.
3985 */
3986static void hmR0SvmInjectPendingEvent(PVMCPU pVCpu, PCCPUMCTX pCtx, PSVMVMCB pVmcb)
3987{
3988 Assert(!TRPMHasTrap(pVCpu));
3989 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
3990
3991 bool const fIntShadow = hmR0SvmIsIntrShadowActive(pVCpu, pCtx);
3992#ifdef VBOX_STRICT
3993 bool const fGif = pCtx->hwvirt.fGif;
3994 bool fAllowInt = fGif;
3995 if (fGif)
3996 {
3997 /*
3998 * For nested-guests we have no way to determine if we're injecting a physical or
3999 * virtual interrupt at this point. Hence the partial verification below.
4000 */
4001 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
4002 fAllowInt = CPUMCanSvmNstGstTakePhysIntr(pVCpu, pCtx) || CPUMCanSvmNstGstTakeVirtIntr(pVCpu, pCtx);
4003 else
4004 fAllowInt = RT_BOOL(pCtx->eflags.u32 & X86_EFL_IF);
4005 }
4006#endif
4007
4008 if (pVCpu->hm.s.Event.fPending)
4009 {
4010 SVMEVENT Event;
4011 Event.u = pVCpu->hm.s.Event.u64IntInfo;
4012 Assert(Event.n.u1Valid);
4013
4014 /*
4015 * Validate event injection pre-conditions.
4016 */
4017 if (Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ)
4018 {
4019 Assert(fAllowInt);
4020 Assert(!fIntShadow);
4021 }
4022 else if (Event.n.u3Type == SVM_EVENT_NMI)
4023 {
4024 Assert(fGif);
4025 Assert(!fIntShadow);
4026 }
4027
4028 /*
4029 * Before injecting an NMI we must set VMCPU_FF_BLOCK_NMIS to prevent nested NMIs. We
4030 * do this only when we are surely going to inject the NMI as otherwise if we return
4031 * to ring-3 prematurely we could leave NMIs blocked indefinitely upon re-entry into
4032 * SVM R0.
4033 *
4034 * With VT-x, this is handled by the Guest interruptibility information VMCS field
4035 * which will set the VMCS field after actually delivering the NMI which we read on
4036 * VM-exit to determine the state.
4037 */
4038 if ( Event.n.u3Type == SVM_EVENT_NMI
4039 && Event.n.u8Vector == X86_XCPT_NMI
4040 && !VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
4041 {
4042 VMCPU_FF_SET(pVCpu, VMCPU_FF_BLOCK_NMIS);
4043 }
4044
4045 /*
4046 * Inject it (update VMCB for injection by the hardware).
4047 */
4048 Log4(("Injecting pending HM event\n"));
4049 hmR0SvmInjectEventVmcb(pVCpu, pVmcb, &Event);
4050 pVCpu->hm.s.Event.fPending = false;
4051
4052 if (Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ)
4053 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterrupt);
4054 else
4055 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectXcpt);
4056 }
4057 else
4058 Assert(pVmcb->ctrl.EventInject.n.u1Valid == 0);
4059
4060 /*
4061 * We could have injected an NMI through IEM and continue guest execution using
4062 * hardware-assisted SVM. In which case, we would not have any events pending (above)
4063 * but we still need to intercept IRET in order to eventually clear NMI inhibition.
4064 */
4065 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
4066 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_IRET);
4067
4068 /*
4069 * Update the guest interrupt shadow in the guest (or nested-guest) VMCB.
4070 *
4071 * For nested-guests: We need to update it too for the scenario where IEM executes
4072 * the nested-guest but execution later continues here with an interrupt shadow active.
4073 */
4074 pVmcb->ctrl.IntShadow.n.u1IntShadow = fIntShadow;
4075}
4076
4077
4078/**
4079 * Reports world-switch error and dumps some useful debug info.
4080 *
4081 * @param pVM The cross context VM structure.
4082 * @param pVCpu The cross context virtual CPU structure.
4083 * @param rcVMRun The return code from VMRUN (or
4084 * VERR_SVM_INVALID_GUEST_STATE for invalid
4085 * guest-state).
4086 * @param pCtx Pointer to the guest-CPU context.
4087 */
4088static void hmR0SvmReportWorldSwitchError(PVM pVM, PVMCPU pVCpu, int rcVMRun, PCPUMCTX pCtx)
4089{
4090 NOREF(pCtx);
4091 HMSVM_ASSERT_PREEMPT_SAFE();
4092 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
4093 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
4094
4095 PCSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
4096 if (rcVMRun == VERR_SVM_INVALID_GUEST_STATE)
4097 {
4098 hmR0DumpRegs(pVM, pVCpu, pCtx); NOREF(pVM);
4099 /** @todo We probably don't need to dump this anymore or we can expand
4100 * hmR0DumpRegs()? */
4101#ifdef VBOX_STRICT
4102 Log4(("ctrl.u32VmcbCleanBits %#RX32\n", pVmcb->ctrl.u32VmcbCleanBits));
4103 Log4(("ctrl.u16InterceptRdCRx %#x\n", pVmcb->ctrl.u16InterceptRdCRx));
4104 Log4(("ctrl.u16InterceptWrCRx %#x\n", pVmcb->ctrl.u16InterceptWrCRx));
4105 Log4(("ctrl.u16InterceptRdDRx %#x\n", pVmcb->ctrl.u16InterceptRdDRx));
4106 Log4(("ctrl.u16InterceptWrDRx %#x\n", pVmcb->ctrl.u16InterceptWrDRx));
4107 Log4(("ctrl.u32InterceptXcpt %#x\n", pVmcb->ctrl.u32InterceptXcpt));
4108 Log4(("ctrl.u64InterceptCtrl %#RX64\n", pVmcb->ctrl.u64InterceptCtrl));
4109 Log4(("ctrl.u64IOPMPhysAddr %#RX64\n", pVmcb->ctrl.u64IOPMPhysAddr));
4110 Log4(("ctrl.u64MSRPMPhysAddr %#RX64\n", pVmcb->ctrl.u64MSRPMPhysAddr));
4111 Log4(("ctrl.u64TSCOffset %#RX64\n", pVmcb->ctrl.u64TSCOffset));
4112
4113 Log4(("ctrl.TLBCtrl.u32ASID %#x\n", pVmcb->ctrl.TLBCtrl.n.u32ASID));
4114 Log4(("ctrl.TLBCtrl.u8TLBFlush %#x\n", pVmcb->ctrl.TLBCtrl.n.u8TLBFlush));
4115 Log4(("ctrl.TLBCtrl.u24Reserved %#x\n", pVmcb->ctrl.TLBCtrl.n.u24Reserved));
4116
4117 Log4(("ctrl.IntCtrl.u8VTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u8VTPR));
4118 Log4(("ctrl.IntCtrl.u1VIrqPending %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqPending));
4119 Log4(("ctrl.IntCtrl.u1VGif %#x\n", pVmcb->ctrl.IntCtrl.n.u1VGif));
4120 Log4(("ctrl.IntCtrl.u6Reserved0 %#x\n", pVmcb->ctrl.IntCtrl.n.u6Reserved));
4121 Log4(("ctrl.IntCtrl.u4VIntrPrio %#x\n", pVmcb->ctrl.IntCtrl.n.u4VIntrPrio));
4122 Log4(("ctrl.IntCtrl.u1IgnoreTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR));
4123 Log4(("ctrl.IntCtrl.u3Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u3Reserved));
4124 Log4(("ctrl.IntCtrl.u1VIntrMasking %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIntrMasking));
4125 Log4(("ctrl.IntCtrl.u1VGifEnable %#x\n", pVmcb->ctrl.IntCtrl.n.u1VGifEnable));
4126 Log4(("ctrl.IntCtrl.u5Reserved1 %#x\n", pVmcb->ctrl.IntCtrl.n.u5Reserved));
4127 Log4(("ctrl.IntCtrl.u8VIntrVector %#x\n", pVmcb->ctrl.IntCtrl.n.u8VIntrVector));
4128 Log4(("ctrl.IntCtrl.u24Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u24Reserved));
4129
4130 Log4(("ctrl.IntShadow.u1IntShadow %#x\n", pVmcb->ctrl.IntShadow.n.u1IntShadow));
4131 Log4(("ctrl.IntShadow.u1GuestIntMask %#x\n", pVmcb->ctrl.IntShadow.n.u1GuestIntMask));
4132 Log4(("ctrl.u64ExitCode %#RX64\n", pVmcb->ctrl.u64ExitCode));
4133 Log4(("ctrl.u64ExitInfo1 %#RX64\n", pVmcb->ctrl.u64ExitInfo1));
4134 Log4(("ctrl.u64ExitInfo2 %#RX64\n", pVmcb->ctrl.u64ExitInfo2));
4135 Log4(("ctrl.ExitIntInfo.u8Vector %#x\n", pVmcb->ctrl.ExitIntInfo.n.u8Vector));
4136 Log4(("ctrl.ExitIntInfo.u3Type %#x\n", pVmcb->ctrl.ExitIntInfo.n.u3Type));
4137 Log4(("ctrl.ExitIntInfo.u1ErrorCodeValid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid));
4138 Log4(("ctrl.ExitIntInfo.u19Reserved %#x\n", pVmcb->ctrl.ExitIntInfo.n.u19Reserved));
4139 Log4(("ctrl.ExitIntInfo.u1Valid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1Valid));
4140 Log4(("ctrl.ExitIntInfo.u32ErrorCode %#x\n", pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
4141 Log4(("ctrl.NestedPagingCtrl.u1NestedPaging %#x\n", pVmcb->ctrl.NestedPagingCtrl.n.u1NestedPaging));
4142 Log4(("ctrl.NestedPagingCtrl.u1Sev %#x\n", pVmcb->ctrl.NestedPagingCtrl.n.u1Sev));
4143 Log4(("ctrl.NestedPagingCtrl.u1SevEs %#x\n", pVmcb->ctrl.NestedPagingCtrl.n.u1SevEs));
4144 Log4(("ctrl.EventInject.u8Vector %#x\n", pVmcb->ctrl.EventInject.n.u8Vector));
4145 Log4(("ctrl.EventInject.u3Type %#x\n", pVmcb->ctrl.EventInject.n.u3Type));
4146 Log4(("ctrl.EventInject.u1ErrorCodeValid %#x\n", pVmcb->ctrl.EventInject.n.u1ErrorCodeValid));
4147 Log4(("ctrl.EventInject.u19Reserved %#x\n", pVmcb->ctrl.EventInject.n.u19Reserved));
4148 Log4(("ctrl.EventInject.u1Valid %#x\n", pVmcb->ctrl.EventInject.n.u1Valid));
4149 Log4(("ctrl.EventInject.u32ErrorCode %#x\n", pVmcb->ctrl.EventInject.n.u32ErrorCode));
4150
4151 Log4(("ctrl.u64NestedPagingCR3 %#RX64\n", pVmcb->ctrl.u64NestedPagingCR3));
4152
4153 Log4(("ctrl.LbrVirt.u1LbrVirt %#x\n", pVmcb->ctrl.LbrVirt.n.u1LbrVirt));
4154 Log4(("ctrl.LbrVirt.u1VirtVmsaveVmload %#x\n", pVmcb->ctrl.LbrVirt.n.u1VirtVmsaveVmload));
4155
4156 Log4(("guest.CS.u16Sel %RTsel\n", pVmcb->guest.CS.u16Sel));
4157 Log4(("guest.CS.u16Attr %#x\n", pVmcb->guest.CS.u16Attr));
4158 Log4(("guest.CS.u32Limit %#RX32\n", pVmcb->guest.CS.u32Limit));
4159 Log4(("guest.CS.u64Base %#RX64\n", pVmcb->guest.CS.u64Base));
4160 Log4(("guest.DS.u16Sel %#RTsel\n", pVmcb->guest.DS.u16Sel));
4161 Log4(("guest.DS.u16Attr %#x\n", pVmcb->guest.DS.u16Attr));
4162 Log4(("guest.DS.u32Limit %#RX32\n", pVmcb->guest.DS.u32Limit));
4163 Log4(("guest.DS.u64Base %#RX64\n", pVmcb->guest.DS.u64Base));
4164 Log4(("guest.ES.u16Sel %RTsel\n", pVmcb->guest.ES.u16Sel));
4165 Log4(("guest.ES.u16Attr %#x\n", pVmcb->guest.ES.u16Attr));
4166 Log4(("guest.ES.u32Limit %#RX32\n", pVmcb->guest.ES.u32Limit));
4167 Log4(("guest.ES.u64Base %#RX64\n", pVmcb->guest.ES.u64Base));
4168 Log4(("guest.FS.u16Sel %RTsel\n", pVmcb->guest.FS.u16Sel));
4169 Log4(("guest.FS.u16Attr %#x\n", pVmcb->guest.FS.u16Attr));
4170 Log4(("guest.FS.u32Limit %#RX32\n", pVmcb->guest.FS.u32Limit));
4171 Log4(("guest.FS.u64Base %#RX64\n", pVmcb->guest.FS.u64Base));
4172 Log4(("guest.GS.u16Sel %RTsel\n", pVmcb->guest.GS.u16Sel));
4173 Log4(("guest.GS.u16Attr %#x\n", pVmcb->guest.GS.u16Attr));
4174 Log4(("guest.GS.u32Limit %#RX32\n", pVmcb->guest.GS.u32Limit));
4175 Log4(("guest.GS.u64Base %#RX64\n", pVmcb->guest.GS.u64Base));
4176
4177 Log4(("guest.GDTR.u32Limit %#RX32\n", pVmcb->guest.GDTR.u32Limit));
4178 Log4(("guest.GDTR.u64Base %#RX64\n", pVmcb->guest.GDTR.u64Base));
4179
4180 Log4(("guest.LDTR.u16Sel %RTsel\n", pVmcb->guest.LDTR.u16Sel));
4181 Log4(("guest.LDTR.u16Attr %#x\n", pVmcb->guest.LDTR.u16Attr));
4182 Log4(("guest.LDTR.u32Limit %#RX32\n", pVmcb->guest.LDTR.u32Limit));
4183 Log4(("guest.LDTR.u64Base %#RX64\n", pVmcb->guest.LDTR.u64Base));
4184
4185 Log4(("guest.IDTR.u32Limit %#RX32\n", pVmcb->guest.IDTR.u32Limit));
4186 Log4(("guest.IDTR.u64Base %#RX64\n", pVmcb->guest.IDTR.u64Base));
4187
4188 Log4(("guest.TR.u16Sel %RTsel\n", pVmcb->guest.TR.u16Sel));
4189 Log4(("guest.TR.u16Attr %#x\n", pVmcb->guest.TR.u16Attr));
4190 Log4(("guest.TR.u32Limit %#RX32\n", pVmcb->guest.TR.u32Limit));
4191 Log4(("guest.TR.u64Base %#RX64\n", pVmcb->guest.TR.u64Base));
4192
4193 Log4(("guest.u8CPL %#x\n", pVmcb->guest.u8CPL));
4194 Log4(("guest.u64CR0 %#RX64\n", pVmcb->guest.u64CR0));
4195 Log4(("guest.u64CR2 %#RX64\n", pVmcb->guest.u64CR2));
4196 Log4(("guest.u64CR3 %#RX64\n", pVmcb->guest.u64CR3));
4197 Log4(("guest.u64CR4 %#RX64\n", pVmcb->guest.u64CR4));
4198 Log4(("guest.u64DR6 %#RX64\n", pVmcb->guest.u64DR6));
4199 Log4(("guest.u64DR7 %#RX64\n", pVmcb->guest.u64DR7));
4200
4201 Log4(("guest.u64RIP %#RX64\n", pVmcb->guest.u64RIP));
4202 Log4(("guest.u64RSP %#RX64\n", pVmcb->guest.u64RSP));
4203 Log4(("guest.u64RAX %#RX64\n", pVmcb->guest.u64RAX));
4204 Log4(("guest.u64RFlags %#RX64\n", pVmcb->guest.u64RFlags));
4205
4206 Log4(("guest.u64SysEnterCS %#RX64\n", pVmcb->guest.u64SysEnterCS));
4207 Log4(("guest.u64SysEnterEIP %#RX64\n", pVmcb->guest.u64SysEnterEIP));
4208 Log4(("guest.u64SysEnterESP %#RX64\n", pVmcb->guest.u64SysEnterESP));
4209
4210 Log4(("guest.u64EFER %#RX64\n", pVmcb->guest.u64EFER));
4211 Log4(("guest.u64STAR %#RX64\n", pVmcb->guest.u64STAR));
4212 Log4(("guest.u64LSTAR %#RX64\n", pVmcb->guest.u64LSTAR));
4213 Log4(("guest.u64CSTAR %#RX64\n", pVmcb->guest.u64CSTAR));
4214 Log4(("guest.u64SFMASK %#RX64\n", pVmcb->guest.u64SFMASK));
4215 Log4(("guest.u64KernelGSBase %#RX64\n", pVmcb->guest.u64KernelGSBase));
4216 Log4(("guest.u64PAT %#RX64\n", pVmcb->guest.u64PAT));
4217 Log4(("guest.u64DBGCTL %#RX64\n", pVmcb->guest.u64DBGCTL));
4218 Log4(("guest.u64BR_FROM %#RX64\n", pVmcb->guest.u64BR_FROM));
4219 Log4(("guest.u64BR_TO %#RX64\n", pVmcb->guest.u64BR_TO));
4220 Log4(("guest.u64LASTEXCPFROM %#RX64\n", pVmcb->guest.u64LASTEXCPFROM));
4221 Log4(("guest.u64LASTEXCPTO %#RX64\n", pVmcb->guest.u64LASTEXCPTO));
4222#endif /* VBOX_STRICT */
4223 }
4224 else
4225 Log4Func(("rcVMRun=%d\n", rcVMRun));
4226
4227 NOREF(pVmcb);
4228}
4229
4230
4231/**
4232 * Check per-VM and per-VCPU force flag actions that require us to go back to
4233 * ring-3 for one reason or another.
4234 *
4235 * @returns VBox status code (information status code included).
4236 * @retval VINF_SUCCESS if we don't have any actions that require going back to
4237 * ring-3.
4238 * @retval VINF_PGM_SYNC_CR3 if we have pending PGM CR3 sync.
4239 * @retval VINF_EM_PENDING_REQUEST if we have pending requests (like hardware
4240 * interrupts)
4241 * @retval VINF_PGM_POOL_FLUSH_PENDING if PGM is doing a pool flush and requires
4242 * all EMTs to be in ring-3.
4243 * @retval VINF_EM_RAW_TO_R3 if there is pending DMA requests.
4244 * @retval VINF_EM_NO_MEMORY PGM is out of memory, we need to return
4245 * to the EM loop.
4246 *
4247 * @param pVM The cross context VM structure.
4248 * @param pVCpu The cross context virtual CPU structure.
4249 * @param pCtx Pointer to the guest-CPU context.
4250 */
4251static int hmR0SvmCheckForceFlags(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4252{
4253 Assert(VMMRZCallRing3IsEnabled(pVCpu));
4254 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
4255
4256 /* Could happen as a result of longjump. */
4257 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
4258 PGMUpdateCR3(pVCpu, CPUMGetGuestCR3(pVCpu));
4259
4260 /* Update pending interrupts into the APIC's IRR. */
4261 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_UPDATE_APIC))
4262 APICUpdatePendingInterrupts(pVCpu);
4263
4264 if ( VM_FF_IS_PENDING(pVM, !pVCpu->hm.s.fSingleInstruction
4265 ? VM_FF_HP_R0_PRE_HM_MASK : VM_FF_HP_R0_PRE_HM_STEP_MASK)
4266 || VMCPU_FF_IS_PENDING(pVCpu, !pVCpu->hm.s.fSingleInstruction
4267 ? VMCPU_FF_HP_R0_PRE_HM_MASK : VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
4268 {
4269 /* Pending PGM C3 sync. */
4270 if (VMCPU_FF_IS_PENDING(pVCpu,VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
4271 {
4272 int rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
4273 if (rc != VINF_SUCCESS)
4274 {
4275 Log4Func(("PGMSyncCR3 forcing us back to ring-3. rc=%d\n", rc));
4276 return rc;
4277 }
4278 }
4279
4280 /* Pending HM-to-R3 operations (critsects, timers, EMT rendezvous etc.) */
4281 /* -XXX- what was that about single stepping? */
4282 if ( VM_FF_IS_PENDING(pVM, VM_FF_HM_TO_R3_MASK)
4283 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
4284 {
4285 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
4286 int rc = RT_UNLIKELY(VM_FF_IS_PENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
4287 Log4Func(("HM_TO_R3 forcing us back to ring-3. rc=%d\n", rc));
4288 return rc;
4289 }
4290
4291 /* Pending VM request packets, such as hardware interrupts. */
4292 if ( VM_FF_IS_PENDING(pVM, VM_FF_REQUEST)
4293 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_REQUEST))
4294 {
4295 Log4Func(("Pending VM request forcing us back to ring-3\n"));
4296 return VINF_EM_PENDING_REQUEST;
4297 }
4298
4299 /* Pending PGM pool flushes. */
4300 if (VM_FF_IS_PENDING(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
4301 {
4302 Log4Func(("PGM pool flush pending forcing us back to ring-3\n"));
4303 return VINF_PGM_POOL_FLUSH_PENDING;
4304 }
4305
4306 /* Pending DMA requests. */
4307 if (VM_FF_IS_PENDING(pVM, VM_FF_PDM_DMA))
4308 {
4309 Log4Func(("Pending DMA request forcing us back to ring-3\n"));
4310 return VINF_EM_RAW_TO_R3;
4311 }
4312 }
4313
4314 return VINF_SUCCESS;
4315}
4316
4317
4318#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
4319/**
4320 * Does the preparations before executing nested-guest code in AMD-V.
4321 *
4322 * @returns VBox status code (informational status codes included).
4323 * @retval VINF_SUCCESS if we can proceed with running the guest.
4324 * @retval VINF_* scheduling changes, we have to go back to ring-3.
4325 *
4326 * @param pVM The cross context VM structure.
4327 * @param pVCpu The cross context virtual CPU structure.
4328 * @param pCtx Pointer to the nested-guest-CPU context.
4329 * @param pSvmTransient Pointer to the SVM transient structure.
4330 *
4331 * @remarks Same caveats regarding longjumps as hmR0SvmPreRunGuest applies.
4332 * @sa hmR0SvmPreRunGuest.
4333 */
4334static int hmR0SvmPreRunGuestNested(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4335{
4336 HMSVM_ASSERT_PREEMPT_SAFE();
4337 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
4338
4339#ifdef VBOX_WITH_NESTED_HWVIRT_SVM_ONLY_IN_IEM
4340 Log2(("hmR0SvmPreRunGuest: Rescheduling to IEM due to nested-hwvirt or forced IEM exec -> VINF_EM_RESCHEDULE_REM\n"));
4341 return VINF_EM_RESCHEDULE_REM;
4342#endif
4343
4344 /* Check force flag actions that might require us to go back to ring-3. */
4345 int rc = hmR0SvmCheckForceFlags(pVM, pVCpu, pCtx);
4346 if (rc != VINF_SUCCESS)
4347 return rc;
4348
4349 if (TRPMHasTrap(pVCpu))
4350 hmR0SvmTrpmTrapToPendingEvent(pVCpu);
4351 else if (!pVCpu->hm.s.Event.fPending)
4352 {
4353 VBOXSTRICTRC rcStrict = hmR0SvmEvaluatePendingEventNested(pVCpu, pCtx);
4354 if ( rcStrict != VINF_SUCCESS
4355 || !CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
4356 return VBOXSTRICTRC_VAL(rcStrict);
4357 }
4358
4359 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
4360
4361 /*
4362 * On the oldest AMD-V systems, we may not get enough information to reinject an NMI.
4363 * Just do it in software, see @bugref{8411}.
4364 * NB: If we could continue a task switch exit we wouldn't need to do this.
4365 */
4366 if (RT_UNLIKELY( !pVM->hm.s.svm.u32Features
4367 && pVCpu->hm.s.Event.fPending
4368 && SVM_EVENT_GET_TYPE(pVCpu->hm.s.Event.u64IntInfo) == SVM_EVENT_NMI))
4369 {
4370 return VINF_EM_RAW_INJECT_TRPM_EVENT;
4371 }
4372
4373#ifdef HMSVM_SYNC_FULL_NESTED_GUEST_STATE
4374 Assert(!(pCtx->fExtrn & HMSVM_CPUMCTX_EXTRN_ALL));
4375 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
4376#endif
4377
4378 /*
4379 * Export the nested-guest state bits that are not shared with the host in any way as we
4380 * can longjmp or get preempted in the midst of exporting some of the state.
4381 */
4382 rc = hmR0SvmExportGuestStateNested(pVCpu);
4383 AssertRCReturn(rc, rc);
4384 STAM_COUNTER_INC(&pVCpu->hm.s.StatExportFull);
4385
4386 /* Ensure we've cached (and hopefully modified) the VMCB for execution using hardware-assisted SVM. */
4387 Assert(pVCpu->hm.s.svm.NstGstVmcbCache.fCacheValid);
4388
4389 /*
4390 * No longjmps to ring-3 from this point on!!!
4391 *
4392 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional,
4393 * better than a kernel panic. This also disables flushing of the R0-logger instance.
4394 */
4395 VMMRZCallRing3Disable(pVCpu);
4396
4397 /*
4398 * We disable interrupts so that we don't miss any interrupts that would flag preemption
4399 * (IPI/timers etc.) when thread-context hooks aren't used and we've been running with
4400 * preemption disabled for a while. Since this is purly to aid the
4401 * RTThreadPreemptIsPending() code, it doesn't matter that it may temporarily reenable and
4402 * disable interrupt on NT.
4403 *
4404 * We need to check for force-flags that could've possible been altered since we last
4405 * checked them (e.g. by PDMGetInterrupt() leaving the PDM critical section,
4406 * see @bugref{6398}).
4407 *
4408 * We also check a couple of other force-flags as a last opportunity to get the EMT back
4409 * to ring-3 before executing guest code.
4410 */
4411 pSvmTransient->fEFlags = ASMIntDisableFlags();
4412 if ( VM_FF_IS_PENDING(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
4413 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
4414 {
4415 ASMSetFlags(pSvmTransient->fEFlags);
4416 VMMRZCallRing3Enable(pVCpu);
4417 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
4418 return VINF_EM_RAW_TO_R3;
4419 }
4420 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
4421 {
4422 ASMSetFlags(pSvmTransient->fEFlags);
4423 VMMRZCallRing3Enable(pVCpu);
4424 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
4425 return VINF_EM_RAW_INTERRUPT;
4426 }
4427 return VINF_SUCCESS;
4428}
4429#endif
4430
4431
4432/**
4433 * Does the preparations before executing guest code in AMD-V.
4434 *
4435 * This may cause longjmps to ring-3 and may even result in rescheduling to the
4436 * recompiler. We must be cautious what we do here regarding committing
4437 * guest-state information into the VMCB assuming we assuredly execute the guest
4438 * in AMD-V. If we fall back to the recompiler after updating the VMCB and
4439 * clearing the common-state (TRPM/forceflags), we must undo those changes so
4440 * that the recompiler can (and should) use them when it resumes guest
4441 * execution. Otherwise such operations must be done when we can no longer
4442 * exit to ring-3.
4443 *
4444 * @returns VBox status code (informational status codes included).
4445 * @retval VINF_SUCCESS if we can proceed with running the guest.
4446 * @retval VINF_* scheduling changes, we have to go back to ring-3.
4447 *
4448 * @param pVM The cross context VM structure.
4449 * @param pVCpu The cross context virtual CPU structure.
4450 * @param pCtx Pointer to the guest-CPU context.
4451 * @param pSvmTransient Pointer to the SVM transient structure.
4452 */
4453static int hmR0SvmPreRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4454{
4455 HMSVM_ASSERT_PREEMPT_SAFE();
4456 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
4457
4458 /* Check force flag actions that might require us to go back to ring-3. */
4459 int rc = hmR0SvmCheckForceFlags(pVM, pVCpu, pCtx);
4460 if (rc != VINF_SUCCESS)
4461 return rc;
4462
4463 if (TRPMHasTrap(pVCpu))
4464 hmR0SvmTrpmTrapToPendingEvent(pVCpu);
4465 else if (!pVCpu->hm.s.Event.fPending)
4466 hmR0SvmEvaluatePendingEvent(pVCpu, pCtx);
4467
4468 /*
4469 * On the oldest AMD-V systems, we may not get enough information to reinject an NMI.
4470 * Just do it in software, see @bugref{8411}.
4471 * NB: If we could continue a task switch exit we wouldn't need to do this.
4472 */
4473 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending && (((pVCpu->hm.s.Event.u64IntInfo >> 8) & 7) == SVM_EVENT_NMI)))
4474 if (RT_UNLIKELY(!pVM->hm.s.svm.u32Features))
4475 return VINF_EM_RAW_INJECT_TRPM_EVENT;
4476
4477#ifdef HMSVM_SYNC_FULL_GUEST_STATE
4478 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
4479 {
4480 Assert(!(pCtx->fExtrn & HMSVM_CPUMCTX_EXTRN_ALL));
4481 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
4482 }
4483#endif
4484#ifdef HMSVM_SYNC_FULL_NESTED_GUEST_STATE
4485 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
4486 {
4487 Assert(!(pCtx->fExtrn & HMSVM_CPUMCTX_EXTRN_ALL));
4488 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
4489 }
4490#endif
4491
4492 /*
4493 * Export the guest state bits that are not shared with the host in any way as we can
4494 * longjmp or get preempted in the midst of exporting some of the state.
4495 */
4496 rc = hmR0SvmExportGuestState(pVCpu);
4497 AssertRCReturn(rc, rc);
4498 STAM_COUNTER_INC(&pVCpu->hm.s.StatExportFull);
4499
4500 /*
4501 * If we're not intercepting TPR changes in the guest, save the guest TPR before the
4502 * world-switch so we can update it on the way back if the guest changed the TPR.
4503 */
4504 if (pVCpu->hm.s.svm.fSyncVTpr)
4505 {
4506 PCSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
4507 if (pVM->hm.s.fTPRPatchingActive)
4508 pSvmTransient->u8GuestTpr = pVmcb->guest.u64LSTAR;
4509 else
4510 pSvmTransient->u8GuestTpr = pVmcb->ctrl.IntCtrl.n.u8VTPR;
4511 }
4512
4513 /*
4514 * No longjmps to ring-3 from this point on!!!
4515 *
4516 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional,
4517 * better than a kernel panic. This also disables flushing of the R0-logger instance.
4518 */
4519 VMMRZCallRing3Disable(pVCpu);
4520
4521 /*
4522 * We disable interrupts so that we don't miss any interrupts that would flag preemption
4523 * (IPI/timers etc.) when thread-context hooks aren't used and we've been running with
4524 * preemption disabled for a while. Since this is purly to aid the
4525 * RTThreadPreemptIsPending() code, it doesn't matter that it may temporarily reenable and
4526 * disable interrupt on NT.
4527 *
4528 * We need to check for force-flags that could've possible been altered since we last
4529 * checked them (e.g. by PDMGetInterrupt() leaving the PDM critical section,
4530 * see @bugref{6398}).
4531 *
4532 * We also check a couple of other force-flags as a last opportunity to get the EMT back
4533 * to ring-3 before executing guest code.
4534 */
4535 pSvmTransient->fEFlags = ASMIntDisableFlags();
4536 if ( VM_FF_IS_PENDING(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
4537 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
4538 {
4539 ASMSetFlags(pSvmTransient->fEFlags);
4540 VMMRZCallRing3Enable(pVCpu);
4541 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
4542 return VINF_EM_RAW_TO_R3;
4543 }
4544 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
4545 {
4546 ASMSetFlags(pSvmTransient->fEFlags);
4547 VMMRZCallRing3Enable(pVCpu);
4548 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
4549 return VINF_EM_RAW_INTERRUPT;
4550 }
4551
4552 return VINF_SUCCESS;
4553}
4554
4555
4556/**
4557 * Prepares to run guest (or nested-guest) code in AMD-V and we've committed to
4558 * doing so.
4559 *
4560 * This means there is no backing out to ring-3 or anywhere else at this point.
4561 *
4562 * @param pVCpu The cross context virtual CPU structure.
4563 * @param pCtx Pointer to the guest-CPU context.
4564 * @param pSvmTransient Pointer to the SVM transient structure.
4565 *
4566 * @remarks Called with preemption disabled.
4567 * @remarks No-long-jump zone!!!
4568 */
4569static void hmR0SvmPreRunGuestCommitted(PVMCPU pVCpu, PCCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4570{
4571 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
4572 Assert(VMMR0IsLogFlushDisabled(pVCpu));
4573 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4574
4575 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
4576 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC); /* Indicate the start of guest execution. */
4577
4578 PVM pVM = pVCpu->CTX_SUFF(pVM);
4579 PSVMVMCB pVmcb = pSvmTransient->pVmcb;
4580
4581 hmR0SvmInjectPendingEvent(pVCpu, pCtx, pVmcb);
4582
4583 if (!CPUMIsGuestFPUStateActive(pVCpu))
4584 {
4585 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestFpuState, x);
4586 CPUMR0LoadGuestFPU(pVM, pVCpu); /* (Ignore rc, no need to set HM_CHANGED_HOST_CONTEXT for SVM.) */
4587 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestFpuState, x);
4588 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadGuestFpu);
4589 }
4590
4591 /* Load the state shared between host and guest (FPU, debug). */
4592 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_SVM_HOST_GUEST_SHARED_STATE)
4593 hmR0SvmExportSharedState(pVCpu, pVmcb);
4594
4595 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_HOST_CONTEXT; /* Preemption might set this, nothing to do on AMD-V. */
4596 AssertMsg(!pVCpu->hm.s.fCtxChanged, ("fCtxChanged=%#RX64\n", pVCpu->hm.s.fCtxChanged));
4597
4598 PHMGLOBALCPUINFO pHostCpu = hmR0GetCurrentCpu();
4599 RTCPUID const idHostCpu = pHostCpu->idCpu;
4600 bool const fMigratedHostCpu = idHostCpu != pVCpu->hm.s.idLastCpu;
4601
4602 /* Setup TSC offsetting. */
4603 if ( pSvmTransient->fUpdateTscOffsetting
4604 || fMigratedHostCpu)
4605 {
4606 hmR0SvmUpdateTscOffsetting(pVM, pVCpu, pCtx, pVmcb);
4607 pSvmTransient->fUpdateTscOffsetting = false;
4608 }
4609
4610 /* If we've migrating CPUs, mark the VMCB Clean bits as dirty. */
4611 if (fMigratedHostCpu)
4612 pVmcb->ctrl.u32VmcbCleanBits = 0;
4613
4614 /* Store status of the shared guest-host state at the time of VMRUN. */
4615#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
4616 if (CPUMIsGuestInLongModeEx(pCtx))
4617 {
4618 pSvmTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActivePending(pVCpu);
4619 pSvmTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActivePending(pVCpu);
4620 }
4621 else
4622#endif
4623 {
4624 pSvmTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActive(pVCpu);
4625 pSvmTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActive(pVCpu);
4626 }
4627
4628#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
4629 uint8_t *pbMsrBitmap;
4630 if (!pSvmTransient->fIsNestedGuest)
4631 pbMsrBitmap = (uint8_t *)pVCpu->hm.s.svm.pvMsrBitmap;
4632 else
4633 {
4634 hmR0SvmMergeMsrpmNested(pHostCpu, pVCpu, pCtx);
4635
4636 /* Update the nested-guest VMCB with the newly merged MSRPM (clean bits updated below). */
4637 pVmcb->ctrl.u64MSRPMPhysAddr = pHostCpu->n.svm.HCPhysNstGstMsrpm;
4638 pbMsrBitmap = (uint8_t *)pHostCpu->n.svm.pvNstGstMsrpm;
4639 }
4640#else
4641 uint8_t *pbMsrBitmap = (uint8_t *)pVCpu->hm.s.svm.pvMsrBitmap;
4642#endif
4643
4644 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB flushing, set this across the world switch. */
4645 /* Flush the appropriate tagged-TLB entries. */
4646 hmR0SvmFlushTaggedTlb(pVCpu, pCtx, pVmcb, pHostCpu);
4647 Assert(pVCpu->hm.s.idLastCpu == idHostCpu);
4648
4649 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
4650
4651 TMNotifyStartOfExecution(pVCpu); /* Finally, notify TM to resume its clocks as we're about
4652 to start executing. */
4653
4654 /*
4655 * Save the current Host TSC_AUX and write the guest TSC_AUX to the host, so that RDTSCPs
4656 * (that don't cause exits) reads the guest MSR, see @bugref{3324}.
4657 *
4658 * This should be done -after- any RDTSCPs for obtaining the host timestamp (TM, STAM etc).
4659 */
4660 if ( (pVM->hm.s.cpuid.u32AMDFeatureEDX & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
4661 && !(pVmcb->ctrl.u64InterceptCtrl & SVM_CTRL_INTERCEPT_RDTSCP))
4662 {
4663 uint64_t const uGuestTscAux = CPUMGetGuestTscAux(pVCpu);
4664 pVCpu->hm.s.u64HostTscAux = ASMRdMsr(MSR_K8_TSC_AUX);
4665 if (uGuestTscAux != pVCpu->hm.s.u64HostTscAux)
4666 ASMWrMsr(MSR_K8_TSC_AUX, uGuestTscAux);
4667 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_TSC_AUX, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
4668 pSvmTransient->fRestoreTscAuxMsr = true;
4669 }
4670 else
4671 {
4672 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_TSC_AUX, SVMMSREXIT_INTERCEPT_READ, SVMMSREXIT_INTERCEPT_WRITE);
4673 pSvmTransient->fRestoreTscAuxMsr = false;
4674 }
4675 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_IOPM_MSRPM;
4676
4677 /*
4678 * If VMCB Clean bits isn't supported by the CPU or exposed to the guest in the nested
4679 * virtualization case, mark all state-bits as dirty indicating to the CPU to re-load
4680 * from the VMCB.
4681 */
4682 bool const fSupportsVmcbCleanBits = hmR0SvmSupportsVmcbCleanBits(pVCpu, pCtx);
4683 if (!fSupportsVmcbCleanBits)
4684 pVmcb->ctrl.u32VmcbCleanBits = 0;
4685}
4686
4687
4688/**
4689 * Wrapper for running the guest code in AMD-V.
4690 *
4691 * @returns VBox strict status code.
4692 * @param pVM The cross context VM structure.
4693 * @param pVCpu The cross context virtual CPU structure.
4694 * @param pCtx Pointer to the guest-CPU context.
4695 *
4696 * @remarks No-long-jump zone!!!
4697 */
4698DECLINLINE(int) hmR0SvmRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4699{
4700 /* Mark that HM is the keeper of all guest-CPU registers now that we're going to execute guest code. */
4701 pCtx->fExtrn |= HMSVM_CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_KEEPER_HM;
4702
4703 /*
4704 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses
4705 * floating-point operations using SSE instructions. Some XMM registers (XMM6-XMM15) are
4706 * callee-saved and thus the need for this XMM wrapper.
4707 *
4708 * Refer MSDN "Configuring Programs for 64-bit/x64 Software Conventions / Register Usage".
4709 */
4710#ifdef VBOX_WITH_KERNEL_USING_XMM
4711 return hmR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
4712 pVCpu->hm.s.svm.pfnVMRun);
4713#else
4714 return pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
4715#endif
4716}
4717
4718
4719#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
4720/**
4721 * Wrapper for running the nested-guest code in AMD-V.
4722 *
4723 * @returns VBox strict status code.
4724 * @param pVM The cross context VM structure.
4725 * @param pVCpu The cross context virtual CPU structure.
4726 * @param pCtx Pointer to the guest-CPU context.
4727 *
4728 * @remarks No-long-jump zone!!!
4729 */
4730DECLINLINE(int) hmR0SvmRunGuestNested(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4731{
4732 /* Mark that HM is the keeper of all guest-CPU registers now that we're going to execute guest code. */
4733 pCtx->fExtrn |= HMSVM_CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_KEEPER_HM;
4734
4735 /*
4736 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses
4737 * floating-point operations using SSE instructions. Some XMM registers (XMM6-XMM15) are
4738 * callee-saved and thus the need for this XMM wrapper.
4739 *
4740 * Refer MSDN "Configuring Programs for 64-bit/x64 Software Conventions / Register Usage".
4741 */
4742#ifdef VBOX_WITH_KERNEL_USING_XMM
4743 return hmR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pCtx->hwvirt.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
4744 pVCpu->hm.s.svm.pfnVMRun);
4745#else
4746 return pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pCtx->hwvirt.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
4747#endif
4748}
4749
4750
4751/**
4752 * Undoes the TSC offset applied for an SVM nested-guest and returns the TSC
4753 * value for the guest.
4754 *
4755 * @returns The TSC offset after undoing any nested-guest TSC offset.
4756 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
4757 * @param uTicks The nested-guest TSC.
4758 *
4759 * @note If you make any changes to this function, please check if
4760 * hmR0SvmNstGstUndoTscOffset() needs adjusting.
4761 *
4762 * @sa HMSvmNstGstApplyTscOffset().
4763 */
4764DECLINLINE(uint64_t) hmR0SvmNstGstUndoTscOffset(PVMCPU pVCpu, uint64_t uTicks)
4765{
4766 PCSVMNESTEDVMCBCACHE pVmcbNstGstCache = &pVCpu->hm.s.svm.NstGstVmcbCache;
4767 Assert(pVmcbNstGstCache->fCacheValid);
4768 return uTicks - pVmcbNstGstCache->u64TSCOffset;
4769}
4770#endif
4771
4772/**
4773 * Performs some essential restoration of state after running guest (or
4774 * nested-guest) code in AMD-V.
4775 *
4776 * @param pVCpu The cross context virtual CPU structure.
4777 * @param pCtx Pointer to the guest-CPU context. The data maybe
4778 * out-of-sync. Make sure to update the required fields
4779 * before using them.
4780 * @param pSvmTransient Pointer to the SVM transient structure.
4781 * @param rcVMRun Return code of VMRUN.
4782 *
4783 * @remarks Called with interrupts disabled.
4784 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
4785 * unconditionally when it is safe to do so.
4786 */
4787static void hmR0SvmPostRunGuest(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient, int rcVMRun)
4788{
4789 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
4790
4791 uint64_t const uHostTsc = ASMReadTSC(); /* Read the TSC as soon as possible. */
4792 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB flushing. */
4793 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for EMT poking. */
4794
4795 PSVMVMCB pVmcb = pSvmTransient->pVmcb;
4796 PSVMVMCBCTRL pVmcbCtrl = &pVmcb->ctrl;
4797
4798 /* TSC read must be done early for maximum accuracy. */
4799 if (!(pVmcbCtrl->u64InterceptCtrl & SVM_CTRL_INTERCEPT_RDTSC))
4800 {
4801 if (!pSvmTransient->fIsNestedGuest)
4802 TMCpuTickSetLastSeen(pVCpu, uHostTsc + pVmcbCtrl->u64TSCOffset);
4803#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
4804 else
4805 {
4806 /* The nested-guest VMCB TSC offset shall eventually be restored on #VMEXIT via HMSvmNstGstVmExitNotify(). */
4807 uint64_t const uGstTsc = hmR0SvmNstGstUndoTscOffset(pVCpu, uHostTsc + pVmcbCtrl->u64TSCOffset);
4808 TMCpuTickSetLastSeen(pVCpu, uGstTsc);
4809 }
4810#endif
4811 }
4812
4813 if (pSvmTransient->fRestoreTscAuxMsr)
4814 {
4815 uint64_t u64GuestTscAuxMsr = ASMRdMsr(MSR_K8_TSC_AUX);
4816 CPUMSetGuestTscAux(pVCpu, u64GuestTscAuxMsr);
4817 if (u64GuestTscAuxMsr != pVCpu->hm.s.u64HostTscAux)
4818 ASMWrMsr(MSR_K8_TSC_AUX, pVCpu->hm.s.u64HostTscAux);
4819 }
4820
4821 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatExit1, x);
4822 TMNotifyEndOfExecution(pVCpu); /* Notify TM that the guest is no longer running. */
4823 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
4824
4825 Assert(!(ASMGetFlags() & X86_EFL_IF));
4826 ASMSetFlags(pSvmTransient->fEFlags); /* Enable interrupts. */
4827 VMMRZCallRing3Enable(pVCpu); /* It is now safe to do longjmps to ring-3!!! */
4828
4829 /* If VMRUN failed, we can bail out early. This does -not- cover SVM_EXIT_INVALID. */
4830 if (RT_UNLIKELY(rcVMRun != VINF_SUCCESS))
4831 {
4832 Log4Func(("VMRUN failure: rcVMRun=%Rrc\n", rcVMRun));
4833 return;
4834 }
4835
4836 pSvmTransient->u64ExitCode = pVmcbCtrl->u64ExitCode; /* Save the #VMEXIT reason. */
4837 pVmcbCtrl->u32VmcbCleanBits = HMSVM_VMCB_CLEAN_ALL; /* Mark the VMCB-state cache as unmodified by VMM. */
4838 pSvmTransient->fVectoringDoublePF = false; /* Vectoring double page-fault needs to be determined later. */
4839 pSvmTransient->fVectoringPF = false; /* Vectoring page-fault needs to be determined later. */
4840
4841#ifdef HMSVM_SYNC_FULL_GUEST_STATE
4842 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
4843 hmR0SvmImportGuestState(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
4844#elif defined(HMSVM_SYNC_FULL_NESTED_GUEST_STATE)
4845 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
4846 hmR0SvmImportGuestState(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
4847#else
4848 /*
4849 * Always import the following:
4850 *
4851 * - RIP for exit optimizations and evaluating event injection on re-entry.
4852 * - RFLAGS for evaluating event injection on VM re-entry and for exporting shared debug
4853 * state on preemption.
4854 * - Interrupt shadow, GIF for evaluating event injection on VM re-entry.
4855 * - CS for exit optimizations.
4856 * - RAX, RSP for simplifying assumptions on GPRs. All other GPRs are swapped by the
4857 * assembly switcher code.
4858 * - Shared state (only DR7 currently) for exporting shared debug state on preemption.
4859 */
4860 hmR0SvmImportGuestState(pVCpu, CPUMCTX_EXTRN_RIP
4861 | CPUMCTX_EXTRN_RFLAGS
4862 | CPUMCTX_EXTRN_RAX
4863 | CPUMCTX_EXTRN_RSP
4864 | CPUMCTX_EXTRN_CS
4865 | CPUMCTX_EXTRN_HWVIRT
4866 | CPUMCTX_EXTRN_HM_SVM_INT_SHADOW
4867 | CPUMCTX_EXTRN_HM_SVM_HWVIRT_VIRQ
4868 | HMSVM_CPUMCTX_SHARED_STATE);
4869#endif
4870
4871#ifdef DEBUG_ramshankar
4872 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
4873 {
4874 hmR0SvmImportGuestState(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
4875 hmR0SvmLogState(pVCpu, pVmcb, pCtx, "hmR0SvmPostRunGuestNested", HMSVM_LOG_ALL & ~HMSVM_LOG_LBR, 0 /* uVerbose */);
4876 }
4877#endif
4878
4879 if ( pSvmTransient->u64ExitCode != SVM_EXIT_INVALID
4880 && pVCpu->hm.s.svm.fSyncVTpr)
4881 {
4882 Assert(!pSvmTransient->fIsNestedGuest);
4883 /* TPR patching (for 32-bit guests) uses LSTAR MSR for holding the TPR value, otherwise uses the VTPR. */
4884 if ( pVCpu->CTX_SUFF(pVM)->hm.s.fTPRPatchingActive
4885 && (pVmcb->guest.u64LSTAR & 0xff) != pSvmTransient->u8GuestTpr)
4886 {
4887 int rc = APICSetTpr(pVCpu, pVmcb->guest.u64LSTAR & 0xff);
4888 AssertRC(rc);
4889 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_APIC_TPR);
4890 }
4891 /* Sync TPR when we aren't intercepting CR8 writes. */
4892 else if (pSvmTransient->u8GuestTpr != pVmcbCtrl->IntCtrl.n.u8VTPR)
4893 {
4894 int rc = APICSetTpr(pVCpu, pVmcbCtrl->IntCtrl.n.u8VTPR << 4);
4895 AssertRC(rc);
4896 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_APIC_TPR);
4897 }
4898 }
4899
4900 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
4901 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_SVM, pSvmTransient->u64ExitCode & EMEXIT_F_TYPE_MASK),
4902 pCtx->cs.u64Base + pCtx->rip, uHostTsc);
4903}
4904
4905
4906/**
4907 * Runs the guest code using AMD-V.
4908 *
4909 * @returns VBox status code.
4910 * @param pVM The cross context VM structure.
4911 * @param pVCpu The cross context virtual CPU structure.
4912 * @param pCtx Pointer to the guest-CPU context.
4913 * @param pcLoops Pointer to the number of executed loops.
4914 */
4915static int hmR0SvmRunGuestCodeNormal(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t *pcLoops)
4916{
4917 uint32_t const cMaxResumeLoops = pVM->hm.s.cMaxResumeLoops;
4918 Assert(pcLoops);
4919 Assert(*pcLoops <= cMaxResumeLoops);
4920
4921 SVMTRANSIENT SvmTransient;
4922 RT_ZERO(SvmTransient);
4923 SvmTransient.fUpdateTscOffsetting = true;
4924 SvmTransient.pVmcb = pVCpu->hm.s.svm.pVmcb;
4925
4926 int rc = VERR_INTERNAL_ERROR_5;
4927 for (;;)
4928 {
4929 Assert(!HMR0SuspendPending());
4930 HMSVM_ASSERT_CPU_SAFE();
4931
4932 /* Preparatory work for running nested-guest code, this may force us to return to
4933 ring-3. This bugger disables interrupts on VINF_SUCCESS! */
4934 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
4935 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
4936 if (rc != VINF_SUCCESS)
4937 break;
4938
4939 /*
4940 * No longjmps to ring-3 from this point on!!!
4941 *
4942 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional,
4943 * better than a kernel panic. This also disables flushing of the R0-logger instance.
4944 */
4945 hmR0SvmPreRunGuestCommitted(pVCpu, pCtx, &SvmTransient);
4946 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
4947
4948 /* Restore any residual host-state and save any bits shared between host and guest
4949 into the guest-CPU state. Re-enables interrupts! */
4950 hmR0SvmPostRunGuest(pVCpu, pCtx, &SvmTransient, rc);
4951
4952 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
4953 || SvmTransient.u64ExitCode == SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
4954 {
4955 if (rc == VINF_SUCCESS)
4956 rc = VERR_SVM_INVALID_GUEST_STATE;
4957 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
4958 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
4959 break;
4960 }
4961
4962 /* Handle the #VMEXIT. */
4963 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
4964 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
4965 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, pVCpu->hm.s.svm.pVmcb);
4966 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
4967 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
4968 if (rc != VINF_SUCCESS)
4969 break;
4970 if (++(*pcLoops) >= cMaxResumeLoops)
4971 {
4972 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
4973 rc = VINF_EM_RAW_INTERRUPT;
4974 break;
4975 }
4976 }
4977
4978 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
4979 return rc;
4980}
4981
4982
4983/**
4984 * Runs the guest code using AMD-V in single step mode.
4985 *
4986 * @returns VBox status code.
4987 * @param pVM The cross context VM structure.
4988 * @param pVCpu The cross context virtual CPU structure.
4989 * @param pCtx Pointer to the guest-CPU context.
4990 * @param pcLoops Pointer to the number of executed loops.
4991 */
4992static int hmR0SvmRunGuestCodeStep(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t *pcLoops)
4993{
4994 uint32_t const cMaxResumeLoops = pVM->hm.s.cMaxResumeLoops;
4995 Assert(pcLoops);
4996 Assert(*pcLoops <= cMaxResumeLoops);
4997
4998 SVMTRANSIENT SvmTransient;
4999 RT_ZERO(SvmTransient);
5000 SvmTransient.fUpdateTscOffsetting = true;
5001 SvmTransient.pVmcb = pVCpu->hm.s.svm.pVmcb;
5002
5003 uint16_t uCsStart = pCtx->cs.Sel;
5004 uint64_t uRipStart = pCtx->rip;
5005
5006 int rc = VERR_INTERNAL_ERROR_5;
5007 for (;;)
5008 {
5009 Assert(!HMR0SuspendPending());
5010 AssertMsg(pVCpu->hm.s.idEnteredCpu == RTMpCpuId(),
5011 ("Illegal migration! Entered on CPU %u Current %u cLoops=%u\n", (unsigned)pVCpu->hm.s.idEnteredCpu,
5012 (unsigned)RTMpCpuId(), *pcLoops));
5013
5014 /* Preparatory work for running nested-guest code, this may force us to return to
5015 ring-3. This bugger disables interrupts on VINF_SUCCESS! */
5016 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
5017 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
5018 if (rc != VINF_SUCCESS)
5019 break;
5020
5021 /*
5022 * No longjmps to ring-3 from this point on!!!
5023 *
5024 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional,
5025 * better than a kernel panic. This also disables flushing of the R0-logger instance.
5026 */
5027 VMMRZCallRing3Disable(pVCpu);
5028 VMMRZCallRing3RemoveNotification(pVCpu);
5029 hmR0SvmPreRunGuestCommitted(pVCpu, pCtx, &SvmTransient);
5030
5031 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
5032
5033 /* Restore any residual host-state and save any bits shared between host and guest
5034 into the guest-CPU state. Re-enables interrupts! */
5035 hmR0SvmPostRunGuest(pVCpu, pCtx, &SvmTransient, rc);
5036
5037 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
5038 || SvmTransient.u64ExitCode == SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
5039 {
5040 if (rc == VINF_SUCCESS)
5041 rc = VERR_SVM_INVALID_GUEST_STATE;
5042 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
5043 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
5044 return rc;
5045 }
5046
5047 /* Handle the #VMEXIT. */
5048 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
5049 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
5050 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, pVCpu->hm.s.svm.pVmcb);
5051 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
5052 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
5053 if (rc != VINF_SUCCESS)
5054 break;
5055 if (++(*pcLoops) >= cMaxResumeLoops)
5056 {
5057 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
5058 rc = VINF_EM_RAW_INTERRUPT;
5059 break;
5060 }
5061
5062 /*
5063 * Did the RIP change, if so, consider it a single step.
5064 * Otherwise, make sure one of the TFs gets set.
5065 */
5066 if ( pCtx->rip != uRipStart
5067 || pCtx->cs.Sel != uCsStart)
5068 {
5069 rc = VINF_EM_DBG_STEPPED;
5070 break;
5071 }
5072 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_GUEST_DR_MASK;
5073 }
5074
5075 /*
5076 * Clear the X86_EFL_TF if necessary.
5077 */
5078 if (pVCpu->hm.s.fClearTrapFlag)
5079 {
5080 pVCpu->hm.s.fClearTrapFlag = false;
5081 pCtx->eflags.Bits.u1TF = 0;
5082 }
5083
5084 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
5085 return rc;
5086}
5087
5088#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
5089/**
5090 * Runs the nested-guest code using AMD-V.
5091 *
5092 * @returns VBox status code.
5093 * @param pVM The cross context VM structure.
5094 * @param pVCpu The cross context virtual CPU structure.
5095 * @param pCtx Pointer to the guest-CPU context.
5096 * @param pcLoops Pointer to the number of executed loops. If we're switching
5097 * from the guest-code execution loop to this nested-guest
5098 * execution loop pass the remainder value, else pass 0.
5099 */
5100static int hmR0SvmRunGuestCodeNested(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t *pcLoops)
5101{
5102 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
5103 Assert(pcLoops);
5104 Assert(*pcLoops <= pVM->hm.s.cMaxResumeLoops);
5105
5106 SVMTRANSIENT SvmTransient;
5107 RT_ZERO(SvmTransient);
5108 SvmTransient.fUpdateTscOffsetting = true;
5109 SvmTransient.pVmcb = pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
5110 SvmTransient.fIsNestedGuest = true;
5111
5112 int rc = VERR_INTERNAL_ERROR_4;
5113 for (;;)
5114 {
5115 Assert(!HMR0SuspendPending());
5116 HMSVM_ASSERT_CPU_SAFE();
5117
5118 /* Preparatory work for running nested-guest code, this may force us to return to
5119 ring-3. This bugger disables interrupts on VINF_SUCCESS! */
5120 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
5121 rc = hmR0SvmPreRunGuestNested(pVM, pVCpu, pCtx, &SvmTransient);
5122 if ( rc != VINF_SUCCESS
5123 || !CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
5124 {
5125 break;
5126 }
5127
5128 /*
5129 * No longjmps to ring-3 from this point on!!!
5130 *
5131 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional,
5132 * better than a kernel panic. This also disables flushing of the R0-logger instance.
5133 */
5134 hmR0SvmPreRunGuestCommitted(pVCpu, pCtx, &SvmTransient);
5135
5136 rc = hmR0SvmRunGuestNested(pVM, pVCpu, pCtx);
5137
5138 /* Restore any residual host-state and save any bits shared between host and guest
5139 into the guest-CPU state. Re-enables interrupts! */
5140 hmR0SvmPostRunGuest(pVCpu, pCtx, &SvmTransient, rc);
5141
5142 if (RT_LIKELY( rc == VINF_SUCCESS
5143 && SvmTransient.u64ExitCode != SVM_EXIT_INVALID))
5144 { /* extremely likely */ }
5145 else
5146 {
5147 /* VMRUN failed, shouldn't really happen, Guru. */
5148 if (rc != VINF_SUCCESS)
5149 break;
5150
5151 /* Invalid nested-guest state. Cause a #VMEXIT but assert on strict builds. */
5152 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
5153 AssertMsgFailed(("Invalid nested-guest state. rc=%Rrc u64ExitCode=%#RX64\n", rc, SvmTransient.u64ExitCode));
5154 rc = VBOXSTRICTRC_TODO(IEMExecSvmVmexit(pVCpu, SVM_EXIT_INVALID, 0, 0));
5155 break;
5156 }
5157
5158 /* Handle the #VMEXIT. */
5159 HMSVM_NESTED_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
5160 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
5161 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, pCtx->hwvirt.svm.CTX_SUFF(pVmcb));
5162 rc = hmR0SvmHandleExitNested(pVCpu, pCtx, &SvmTransient);
5163 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
5164 if ( rc != VINF_SUCCESS
5165 || !CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
5166 break;
5167 if (++(*pcLoops) >= pVM->hm.s.cMaxResumeLoops)
5168 {
5169 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
5170 rc = VINF_EM_RAW_INTERRUPT;
5171 break;
5172 }
5173
5174 /** @todo handle single-stepping */
5175 }
5176
5177 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
5178 return rc;
5179}
5180#endif
5181
5182
5183/**
5184 * Runs the guest code using AMD-V.
5185 *
5186 * @returns Strict VBox status code.
5187 * @param pVM The cross context VM structure.
5188 * @param pVCpu The cross context virtual CPU structure.
5189 * @param pCtx Pointer to the guest-CPU context.
5190 */
5191VMMR0DECL(VBOXSTRICTRC) SVMR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
5192{
5193 Assert(VMMRZCallRing3IsEnabled(pVCpu));
5194 HMSVM_ASSERT_PREEMPT_SAFE();
5195 VMMRZCallRing3SetNotification(pVCpu, hmR0SvmCallRing3Callback, pCtx);
5196
5197 uint32_t cLoops = 0;
5198 int rc;
5199#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
5200 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
5201#endif
5202 {
5203 if (!pVCpu->hm.s.fSingleInstruction)
5204 rc = hmR0SvmRunGuestCodeNormal(pVM, pVCpu, pCtx, &cLoops);
5205 else
5206 rc = hmR0SvmRunGuestCodeStep(pVM, pVCpu, pCtx, &cLoops);
5207 }
5208#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
5209 else
5210 {
5211 rc = VINF_SVM_VMRUN;
5212 }
5213
5214 /* Re-check the nested-guest condition here as we may be transitioning from the normal
5215 execution loop into the nested-guest, hence this is not placed in the 'else' part above. */
5216 if (rc == VINF_SVM_VMRUN)
5217 {
5218 rc = hmR0SvmRunGuestCodeNested(pVM, pVCpu, pCtx, &cLoops);
5219 if (rc == VINF_SVM_VMEXIT)
5220 rc = VINF_SUCCESS;
5221 }
5222#endif
5223
5224 /* Fixup error codes. */
5225 if (rc == VERR_EM_INTERPRETER)
5226 rc = VINF_EM_RAW_EMULATE_INSTR;
5227 else if (rc == VINF_EM_RESET)
5228 rc = VINF_EM_TRIPLE_FAULT;
5229
5230 /* Prepare to return to ring-3. This will remove longjmp notifications. */
5231 rc = hmR0SvmExitToRing3(pVM, pVCpu, pCtx, rc);
5232 Assert(!VMMRZCallRing3IsNotificationSet(pVCpu));
5233 return rc;
5234}
5235
5236
5237#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
5238/**
5239 * Determines whether an IOIO intercept is active for the nested-guest or not.
5240 *
5241 * @param pvIoBitmap Pointer to the nested-guest IO bitmap.
5242 * @param pIoExitInfo Pointer to the SVMIOIOEXITINFO.
5243 */
5244static bool hmR0SvmIsIoInterceptActive(void *pvIoBitmap, PSVMIOIOEXITINFO pIoExitInfo)
5245{
5246 const uint16_t u16Port = pIoExitInfo->n.u16Port;
5247 const SVMIOIOTYPE enmIoType = (SVMIOIOTYPE)pIoExitInfo->n.u1Type;
5248 const uint8_t cbReg = (pIoExitInfo->u >> SVM_IOIO_OP_SIZE_SHIFT) & 7;
5249 const uint8_t cAddrSizeBits = ((pIoExitInfo->u >> SVM_IOIO_ADDR_SIZE_SHIFT) & 7) << 4;
5250 const uint8_t iEffSeg = pIoExitInfo->n.u3Seg;
5251 const bool fRep = pIoExitInfo->n.u1Rep;
5252 const bool fStrIo = pIoExitInfo->n.u1Str;
5253
5254 return HMSvmIsIOInterceptActive(pvIoBitmap, u16Port, enmIoType, cbReg, cAddrSizeBits, iEffSeg, fRep, fStrIo,
5255 NULL /* pIoExitInfo */);
5256}
5257
5258
5259/**
5260 * Handles a nested-guest \#VMEXIT (for all EXITCODE values except
5261 * SVM_EXIT_INVALID).
5262 *
5263 * @returns VBox status code (informational status codes included).
5264 * @param pVCpu The cross context virtual CPU structure.
5265 * @param pCtx Pointer to the guest-CPU context.
5266 * @param pSvmTransient Pointer to the SVM transient structure.
5267 */
5268static int hmR0SvmHandleExitNested(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5269{
5270 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
5271 Assert(pSvmTransient->u64ExitCode != SVM_EXIT_INVALID);
5272 Assert(pSvmTransient->u64ExitCode <= SVM_EXIT_MAX);
5273
5274 /** @todo Figure out why using IEM_CPUMCTX_EXTRN_SVM_VMEXIT_MASK instead of
5275 * HMSVM_CPUMCTX_EXTRN_ALL breaks nested guests (XP Pro, DSL etc.), see
5276 * also HMSvmNstGstVmExitNotify(). */
5277#define NST_GST_VMEXIT_CALL_RET(a_pVCpu, a_pCtx, a_uExitCode, a_uExitInfo1, a_uExitInfo2) \
5278 do { \
5279 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL); \
5280 return VBOXSTRICTRC_TODO(IEMExecSvmVmexit((a_pVCpu), (a_uExitCode), (a_uExitInfo1), (a_uExitInfo2))); \
5281 } while (0)
5282
5283 /*
5284 * For all the #VMEXITs here we primarily figure out if the #VMEXIT is expected by the
5285 * nested-guest. If it isn't, it should be handled by the (outer) guest.
5286 */
5287 PSVMVMCB pVmcbNstGst = pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
5288 PSVMVMCBCTRL pVmcbNstGstCtrl = &pVmcbNstGst->ctrl;
5289 uint64_t const uExitCode = pVmcbNstGstCtrl->u64ExitCode;
5290 uint64_t const uExitInfo1 = pVmcbNstGstCtrl->u64ExitInfo1;
5291 uint64_t const uExitInfo2 = pVmcbNstGstCtrl->u64ExitInfo2;
5292
5293 Assert(uExitCode == pVmcbNstGstCtrl->u64ExitCode);
5294 switch (uExitCode)
5295 {
5296 case SVM_EXIT_CPUID:
5297 {
5298 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_CPUID))
5299 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5300 return hmR0SvmExitCpuid(pVCpu, pCtx, pSvmTransient);
5301 }
5302
5303 case SVM_EXIT_RDTSC:
5304 {
5305 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_RDTSC))
5306 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5307 return hmR0SvmExitRdtsc(pVCpu, pCtx, pSvmTransient);
5308 }
5309
5310 case SVM_EXIT_RDTSCP:
5311 {
5312 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_RDTSCP))
5313 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5314 return hmR0SvmExitRdtscp(pVCpu, pCtx, pSvmTransient);
5315 }
5316
5317 case SVM_EXIT_MONITOR:
5318 {
5319 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_MONITOR))
5320 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5321 return hmR0SvmExitMonitor(pVCpu, pCtx, pSvmTransient);
5322 }
5323
5324 case SVM_EXIT_MWAIT:
5325 {
5326 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_MWAIT))
5327 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5328 return hmR0SvmExitMwait(pVCpu, pCtx, pSvmTransient);
5329 }
5330
5331 case SVM_EXIT_HLT:
5332 {
5333 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_HLT))
5334 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5335 return hmR0SvmExitHlt(pVCpu, pCtx, pSvmTransient);
5336 }
5337
5338 case SVM_EXIT_MSR:
5339 {
5340 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_MSR_PROT))
5341 {
5342 uint32_t const idMsr = pCtx->ecx;
5343 uint16_t offMsrpm;
5344 uint8_t uMsrpmBit;
5345 int rc = HMSvmGetMsrpmOffsetAndBit(idMsr, &offMsrpm, &uMsrpmBit);
5346 if (RT_SUCCESS(rc))
5347 {
5348 Assert(uMsrpmBit == 0 || uMsrpmBit == 2 || uMsrpmBit == 4 || uMsrpmBit == 6);
5349 Assert(offMsrpm < SVM_MSRPM_PAGES << X86_PAGE_4K_SHIFT);
5350
5351 uint8_t const *pbMsrBitmap = (uint8_t const *)pCtx->hwvirt.svm.CTX_SUFF(pvMsrBitmap);
5352 pbMsrBitmap += offMsrpm;
5353 bool const fInterceptRead = RT_BOOL(*pbMsrBitmap & RT_BIT(uMsrpmBit));
5354 bool const fInterceptWrite = RT_BOOL(*pbMsrBitmap & RT_BIT(uMsrpmBit + 1));
5355
5356 if ( (fInterceptWrite && pVmcbNstGstCtrl->u64ExitInfo1 == SVM_EXIT1_MSR_WRITE)
5357 || (fInterceptRead && pVmcbNstGstCtrl->u64ExitInfo1 == SVM_EXIT1_MSR_READ))
5358 {
5359 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5360 }
5361 }
5362 else
5363 {
5364 /*
5365 * MSRs not covered by the MSRPM automatically cause an #VMEXIT.
5366 * See AMD-V spec. "15.11 MSR Intercepts".
5367 */
5368 Assert(rc == VERR_OUT_OF_RANGE);
5369 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5370 }
5371 }
5372 return hmR0SvmExitMsr(pVCpu, pCtx, pSvmTransient);
5373 }
5374
5375 case SVM_EXIT_IOIO:
5376 {
5377 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_IOIO_PROT))
5378 {
5379 void *pvIoBitmap = pCtx->hwvirt.svm.CTX_SUFF(pvIoBitmap);
5380 SVMIOIOEXITINFO IoExitInfo;
5381 IoExitInfo.u = pVmcbNstGst->ctrl.u64ExitInfo1;
5382 bool const fIntercept = hmR0SvmIsIoInterceptActive(pvIoBitmap, &IoExitInfo);
5383 if (fIntercept)
5384 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5385 }
5386 return hmR0SvmExitIOInstr(pVCpu, pCtx, pSvmTransient);
5387 }
5388
5389 case SVM_EXIT_XCPT_PF:
5390 {
5391 PVM pVM = pVCpu->CTX_SUFF(pVM);
5392 if (pVM->hm.s.fNestedPaging)
5393 {
5394 uint32_t const u32ErrCode = pVmcbNstGstCtrl->u64ExitInfo1;
5395 uint64_t const uFaultAddress = pVmcbNstGstCtrl->u64ExitInfo2;
5396
5397 /* If the nested-guest is intercepting #PFs, cause a #PF #VMEXIT. */
5398 if (HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_PF))
5399 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, u32ErrCode, uFaultAddress);
5400
5401 /* If the nested-guest is not intercepting #PFs, forward the #PF to the guest. */
5402 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, CPUMCTX_EXTRN_CR2);
5403 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
5404 return VINF_SUCCESS;
5405 }
5406 return hmR0SvmExitXcptPF(pVCpu, pCtx,pSvmTransient);
5407 }
5408
5409 case SVM_EXIT_XCPT_UD:
5410 {
5411 if (HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_UD))
5412 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5413 hmR0SvmSetPendingXcptUD(pVCpu);
5414 return VINF_SUCCESS;
5415 }
5416
5417 case SVM_EXIT_XCPT_MF:
5418 {
5419 if (HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_MF))
5420 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5421 return hmR0SvmExitXcptMF(pVCpu, pCtx, pSvmTransient);
5422 }
5423
5424 case SVM_EXIT_XCPT_DB:
5425 {
5426 if (HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_DB))
5427 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5428 return hmR0SvmNestedExitXcptDB(pVCpu, pCtx, pSvmTransient);
5429 }
5430
5431 case SVM_EXIT_XCPT_AC:
5432 {
5433 if (HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_AC))
5434 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5435 return hmR0SvmExitXcptAC(pVCpu, pCtx, pSvmTransient);
5436 }
5437
5438 case SVM_EXIT_XCPT_BP:
5439 {
5440 if (HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_BP))
5441 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5442 return hmR0SvmNestedExitXcptBP(pVCpu, pCtx, pSvmTransient);
5443 }
5444
5445 case SVM_EXIT_READ_CR0:
5446 case SVM_EXIT_READ_CR3:
5447 case SVM_EXIT_READ_CR4:
5448 {
5449 uint8_t const uCr = uExitCode - SVM_EXIT_READ_CR0;
5450 if (HMIsGuestSvmReadCRxInterceptSet(pVCpu, uCr))
5451 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5452 return hmR0SvmExitReadCRx(pVCpu, pCtx, pSvmTransient);
5453 }
5454
5455 case SVM_EXIT_CR0_SEL_WRITE:
5456 {
5457 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_CR0_SEL_WRITE))
5458 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5459 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
5460 }
5461
5462 case SVM_EXIT_WRITE_CR0:
5463 case SVM_EXIT_WRITE_CR3:
5464 case SVM_EXIT_WRITE_CR4:
5465 case SVM_EXIT_WRITE_CR8: /* CR8 writes would go to the V_TPR rather than here, since we run with V_INTR_MASKING. */
5466 {
5467 uint8_t const uCr = uExitCode - SVM_EXIT_WRITE_CR0;
5468 Log4Func(("Write CR%u: uExitInfo1=%#RX64 uExitInfo2=%#RX64\n", uCr, uExitInfo1, uExitInfo2));
5469
5470 if (HMIsGuestSvmWriteCRxInterceptSet(pVCpu, uCr))
5471 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5472 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
5473 }
5474
5475 case SVM_EXIT_PAUSE:
5476 {
5477 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_PAUSE))
5478 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5479 return hmR0SvmExitPause(pVCpu, pCtx, pSvmTransient);
5480 }
5481
5482 case SVM_EXIT_VINTR:
5483 {
5484 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_VINTR))
5485 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5486 return hmR0SvmExitUnexpected(pVCpu, pCtx, pSvmTransient);
5487 }
5488
5489 case SVM_EXIT_INTR:
5490 case SVM_EXIT_NMI:
5491 case SVM_EXIT_SMI:
5492 case SVM_EXIT_XCPT_NMI: /* Should not occur, SVM_EXIT_NMI is used instead. */
5493 {
5494 /*
5495 * We shouldn't direct physical interrupts, NMIs, SMIs to the nested-guest.
5496 *
5497 * Although we don't intercept SMIs, the nested-guest might. Therefore, we might
5498 * get an SMI #VMEXIT here so simply ignore rather than causing a corresponding
5499 * nested-guest #VMEXIT.
5500 */
5501 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, IEM_CPUMCTX_EXTRN_SVM_VMEXIT_MASK);
5502 return hmR0SvmExitIntr(pVCpu, pCtx, pSvmTransient);
5503 }
5504
5505 case SVM_EXIT_FERR_FREEZE:
5506 {
5507 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_FERR_FREEZE))
5508 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5509 return hmR0SvmExitFerrFreeze(pVCpu, pCtx, pSvmTransient);
5510 }
5511
5512 case SVM_EXIT_INVLPG:
5513 {
5514 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_INVLPG))
5515 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5516 return hmR0SvmExitInvlpg(pVCpu, pCtx, pSvmTransient);
5517 }
5518
5519 case SVM_EXIT_WBINVD:
5520 {
5521 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_WBINVD))
5522 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5523 return hmR0SvmExitWbinvd(pVCpu, pCtx, pSvmTransient);
5524 }
5525
5526 case SVM_EXIT_INVD:
5527 {
5528 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_INVD))
5529 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5530 return hmR0SvmExitInvd(pVCpu, pCtx, pSvmTransient);
5531 }
5532
5533 case SVM_EXIT_RDPMC:
5534 {
5535 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_RDPMC))
5536 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5537 return hmR0SvmExitRdpmc(pVCpu, pCtx, pSvmTransient);
5538 }
5539
5540 default:
5541 {
5542 switch (uExitCode)
5543 {
5544 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
5545 case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7: case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9:
5546 case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11: case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13:
5547 case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
5548 {
5549 uint8_t const uDr = uExitCode - SVM_EXIT_READ_DR0;
5550 if (HMIsGuestSvmReadDRxInterceptSet(pVCpu, uDr))
5551 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5552 return hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
5553 }
5554
5555 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
5556 case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7: case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9:
5557 case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11: case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13:
5558 case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
5559 {
5560 uint8_t const uDr = uExitCode - SVM_EXIT_WRITE_DR0;
5561 if (HMIsGuestSvmWriteDRxInterceptSet(pVCpu, uDr))
5562 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5563 return hmR0SvmExitWriteDRx(pVCpu, pCtx, pSvmTransient);
5564 }
5565
5566 case SVM_EXIT_XCPT_DE:
5567 /* SVM_EXIT_XCPT_DB: */ /* Handled above. */
5568 /* SVM_EXIT_XCPT_NMI: */ /* Handled above. */
5569 /* SVM_EXIT_XCPT_BP: */ /* Handled above. */
5570 case SVM_EXIT_XCPT_OF:
5571 case SVM_EXIT_XCPT_BR:
5572 /* SVM_EXIT_XCPT_UD: */ /* Handled above. */
5573 case SVM_EXIT_XCPT_NM:
5574 case SVM_EXIT_XCPT_DF:
5575 case SVM_EXIT_XCPT_CO_SEG_OVERRUN:
5576 case SVM_EXIT_XCPT_TS:
5577 case SVM_EXIT_XCPT_NP:
5578 case SVM_EXIT_XCPT_SS:
5579 case SVM_EXIT_XCPT_GP:
5580 /* SVM_EXIT_XCPT_PF: */ /* Handled above. */
5581 case SVM_EXIT_XCPT_15: /* Reserved. */
5582 /* SVM_EXIT_XCPT_MF: */ /* Handled above. */
5583 /* SVM_EXIT_XCPT_AC: */ /* Handled above. */
5584 case SVM_EXIT_XCPT_MC:
5585 case SVM_EXIT_XCPT_XF:
5586 case SVM_EXIT_XCPT_20: case SVM_EXIT_XCPT_21: case SVM_EXIT_XCPT_22: case SVM_EXIT_XCPT_23:
5587 case SVM_EXIT_XCPT_24: case SVM_EXIT_XCPT_25: case SVM_EXIT_XCPT_26: case SVM_EXIT_XCPT_27:
5588 case SVM_EXIT_XCPT_28: case SVM_EXIT_XCPT_29: case SVM_EXIT_XCPT_30: case SVM_EXIT_XCPT_31:
5589 {
5590 uint8_t const uVector = uExitCode - SVM_EXIT_XCPT_0;
5591 if (HMIsGuestSvmXcptInterceptSet(pVCpu, uVector))
5592 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5593 return hmR0SvmExitXcptGeneric(pVCpu, pCtx, pSvmTransient);
5594 }
5595
5596 case SVM_EXIT_XSETBV:
5597 {
5598 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_XSETBV))
5599 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5600 return hmR0SvmExitXsetbv(pVCpu, pCtx, pSvmTransient);
5601 }
5602
5603 case SVM_EXIT_TASK_SWITCH:
5604 {
5605 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_TASK_SWITCH))
5606 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5607 return hmR0SvmExitTaskSwitch(pVCpu, pCtx, pSvmTransient);
5608 }
5609
5610 case SVM_EXIT_IRET:
5611 {
5612 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_IRET))
5613 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5614 return hmR0SvmExitIret(pVCpu, pCtx, pSvmTransient);
5615 }
5616
5617 case SVM_EXIT_SHUTDOWN:
5618 {
5619 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_SHUTDOWN))
5620 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5621 return hmR0SvmExitShutdown(pVCpu, pCtx, pSvmTransient);
5622 }
5623
5624 case SVM_EXIT_VMMCALL:
5625 {
5626 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_VMMCALL))
5627 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5628 return hmR0SvmExitVmmCall(pVCpu, pCtx, pSvmTransient);
5629 }
5630
5631 case SVM_EXIT_CLGI:
5632 {
5633 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_CLGI))
5634 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5635 return hmR0SvmExitClgi(pVCpu, pCtx, pSvmTransient);
5636 }
5637
5638 case SVM_EXIT_STGI:
5639 {
5640 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_STGI))
5641 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5642 return hmR0SvmExitStgi(pVCpu, pCtx, pSvmTransient);
5643 }
5644
5645 case SVM_EXIT_VMLOAD:
5646 {
5647 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_VMLOAD))
5648 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5649 return hmR0SvmExitVmload(pVCpu, pCtx, pSvmTransient);
5650 }
5651
5652 case SVM_EXIT_VMSAVE:
5653 {
5654 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_VMSAVE))
5655 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5656 return hmR0SvmExitVmsave(pVCpu, pCtx, pSvmTransient);
5657 }
5658
5659 case SVM_EXIT_INVLPGA:
5660 {
5661 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_INVLPGA))
5662 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5663 return hmR0SvmExitInvlpga(pVCpu, pCtx, pSvmTransient);
5664 }
5665
5666 case SVM_EXIT_VMRUN:
5667 {
5668 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_VMRUN))
5669 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5670 return hmR0SvmExitVmrun(pVCpu, pCtx, pSvmTransient);
5671 }
5672
5673 case SVM_EXIT_RSM:
5674 {
5675 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_RSM))
5676 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5677 hmR0SvmSetPendingXcptUD(pVCpu);
5678 return VINF_SUCCESS;
5679 }
5680
5681 case SVM_EXIT_SKINIT:
5682 {
5683 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_SKINIT))
5684 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5685 hmR0SvmSetPendingXcptUD(pVCpu);
5686 return VINF_SUCCESS;
5687 }
5688
5689 case SVM_EXIT_NPF:
5690 {
5691 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
5692 return hmR0SvmExitNestedPF(pVCpu, pCtx, pSvmTransient);
5693 }
5694
5695 case SVM_EXIT_INIT: /* We shouldn't get INIT signals while executing a nested-guest. */
5696 return hmR0SvmExitUnexpected(pVCpu, pCtx, pSvmTransient);
5697
5698 default:
5699 {
5700 AssertMsgFailed(("hmR0SvmHandleExitNested: Unknown exit code %#x\n", pSvmTransient->u64ExitCode));
5701 pVCpu->hm.s.u32HMError = pSvmTransient->u64ExitCode;
5702 return VERR_SVM_UNKNOWN_EXIT;
5703 }
5704 }
5705 }
5706 }
5707 /* not reached */
5708
5709#undef NST_GST_VMEXIT_CALL_RET
5710}
5711#endif
5712
5713
5714/**
5715 * Handles a guest \#VMEXIT (for all EXITCODE values except SVM_EXIT_INVALID).
5716 *
5717 * @returns VBox status code (informational status codes included).
5718 * @param pVCpu The cross context virtual CPU structure.
5719 * @param pCtx Pointer to the guest-CPU context.
5720 * @param pSvmTransient Pointer to the SVM transient structure.
5721 */
5722static int hmR0SvmHandleExit(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5723{
5724 Assert(pSvmTransient->u64ExitCode != SVM_EXIT_INVALID);
5725 Assert(pSvmTransient->u64ExitCode <= SVM_EXIT_MAX);
5726
5727#ifdef DEBUG_ramshankar
5728# define VMEXIT_CALL_RET(a_fDbg, a_CallExpr) \
5729 do { \
5730 if ((a_fDbg) == 1) \
5731 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL); \
5732 int rc = a_CallExpr; \
5733 if ((a_fDbg) == 1) \
5734 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST); \
5735 return rc; \
5736 } while (0)
5737#else
5738# define VMEXIT_CALL_RET(a_fDbg, a_CallExpr) return a_CallExpr
5739#endif
5740
5741 /*
5742 * The ordering of the case labels is based on most-frequently-occurring #VMEXITs
5743 * for most guests under normal workloads (for some definition of "normal").
5744 */
5745 uint64_t const uExitCode = pSvmTransient->u64ExitCode;
5746 switch (uExitCode)
5747 {
5748 case SVM_EXIT_NPF: VMEXIT_CALL_RET(0, hmR0SvmExitNestedPF(pVCpu, pCtx, pSvmTransient));
5749 case SVM_EXIT_IOIO: VMEXIT_CALL_RET(0, hmR0SvmExitIOInstr(pVCpu, pCtx, pSvmTransient));
5750 case SVM_EXIT_RDTSC: VMEXIT_CALL_RET(0, hmR0SvmExitRdtsc(pVCpu, pCtx, pSvmTransient));
5751 case SVM_EXIT_RDTSCP: VMEXIT_CALL_RET(0, hmR0SvmExitRdtscp(pVCpu, pCtx, pSvmTransient));
5752 case SVM_EXIT_CPUID: VMEXIT_CALL_RET(0, hmR0SvmExitCpuid(pVCpu, pCtx, pSvmTransient));
5753 case SVM_EXIT_XCPT_PF: VMEXIT_CALL_RET(0, hmR0SvmExitXcptPF(pVCpu, pCtx, pSvmTransient));
5754 case SVM_EXIT_MSR: VMEXIT_CALL_RET(0, hmR0SvmExitMsr(pVCpu, pCtx, pSvmTransient));
5755 case SVM_EXIT_MONITOR: VMEXIT_CALL_RET(0, hmR0SvmExitMonitor(pVCpu, pCtx, pSvmTransient));
5756 case SVM_EXIT_MWAIT: VMEXIT_CALL_RET(0, hmR0SvmExitMwait(pVCpu, pCtx, pSvmTransient));
5757 case SVM_EXIT_HLT: VMEXIT_CALL_RET(0, hmR0SvmExitHlt(pVCpu, pCtx, pSvmTransient));
5758
5759 case SVM_EXIT_XCPT_NMI: /* Should not occur, SVM_EXIT_NMI is used instead. */
5760 case SVM_EXIT_INTR:
5761 case SVM_EXIT_NMI: VMEXIT_CALL_RET(0, hmR0SvmExitIntr(pVCpu, pCtx, pSvmTransient));
5762
5763 case SVM_EXIT_READ_CR0:
5764 case SVM_EXIT_READ_CR3:
5765 case SVM_EXIT_READ_CR4: VMEXIT_CALL_RET(0, hmR0SvmExitReadCRx(pVCpu, pCtx, pSvmTransient));
5766
5767 case SVM_EXIT_CR0_SEL_WRITE:
5768 case SVM_EXIT_WRITE_CR0:
5769 case SVM_EXIT_WRITE_CR3:
5770 case SVM_EXIT_WRITE_CR4:
5771 case SVM_EXIT_WRITE_CR8: VMEXIT_CALL_RET(0, hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient));
5772
5773 case SVM_EXIT_VINTR: VMEXIT_CALL_RET(0, hmR0SvmExitVIntr(pVCpu, pCtx, pSvmTransient));
5774 case SVM_EXIT_PAUSE: VMEXIT_CALL_RET(0, hmR0SvmExitPause(pVCpu, pCtx, pSvmTransient));
5775 case SVM_EXIT_VMMCALL: VMEXIT_CALL_RET(0, hmR0SvmExitVmmCall(pVCpu, pCtx, pSvmTransient));
5776 case SVM_EXIT_INVLPG: VMEXIT_CALL_RET(0, hmR0SvmExitInvlpg(pVCpu, pCtx, pSvmTransient));
5777 case SVM_EXIT_WBINVD: VMEXIT_CALL_RET(0, hmR0SvmExitWbinvd(pVCpu, pCtx, pSvmTransient));
5778 case SVM_EXIT_INVD: VMEXIT_CALL_RET(0, hmR0SvmExitInvd(pVCpu, pCtx, pSvmTransient));
5779 case SVM_EXIT_RDPMC: VMEXIT_CALL_RET(0, hmR0SvmExitRdpmc(pVCpu, pCtx, pSvmTransient));
5780 case SVM_EXIT_IRET: VMEXIT_CALL_RET(0, hmR0SvmExitIret(pVCpu, pCtx, pSvmTransient));
5781 case SVM_EXIT_XCPT_UD: VMEXIT_CALL_RET(0, hmR0SvmExitXcptUD(pVCpu, pCtx, pSvmTransient));
5782 case SVM_EXIT_XCPT_MF: VMEXIT_CALL_RET(0, hmR0SvmExitXcptMF(pVCpu, pCtx, pSvmTransient));
5783 case SVM_EXIT_XCPT_DB: VMEXIT_CALL_RET(0, hmR0SvmExitXcptDB(pVCpu, pCtx, pSvmTransient));
5784 case SVM_EXIT_XCPT_AC: VMEXIT_CALL_RET(0, hmR0SvmExitXcptAC(pVCpu, pCtx, pSvmTransient));
5785 case SVM_EXIT_XCPT_BP: VMEXIT_CALL_RET(0, hmR0SvmExitXcptBP(pVCpu, pCtx, pSvmTransient));
5786 case SVM_EXIT_XSETBV: VMEXIT_CALL_RET(0, hmR0SvmExitXsetbv(pVCpu, pCtx, pSvmTransient));
5787 case SVM_EXIT_FERR_FREEZE: VMEXIT_CALL_RET(0, hmR0SvmExitFerrFreeze(pVCpu, pCtx, pSvmTransient));
5788
5789 default:
5790 {
5791 switch (pSvmTransient->u64ExitCode)
5792 {
5793 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
5794 case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7: case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9:
5795 case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11: case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13:
5796 case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
5797 VMEXIT_CALL_RET(0, hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient));
5798
5799 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
5800 case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7: case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9:
5801 case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11: case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13:
5802 case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
5803 VMEXIT_CALL_RET(0, hmR0SvmExitWriteDRx(pVCpu, pCtx, pSvmTransient));
5804
5805 case SVM_EXIT_TASK_SWITCH: VMEXIT_CALL_RET(0, hmR0SvmExitTaskSwitch(pVCpu, pCtx, pSvmTransient));
5806 case SVM_EXIT_SHUTDOWN: VMEXIT_CALL_RET(0, hmR0SvmExitShutdown(pVCpu, pCtx, pSvmTransient));
5807
5808 case SVM_EXIT_SMI:
5809 case SVM_EXIT_INIT:
5810 {
5811 /*
5812 * We don't intercept SMIs. As for INIT signals, it really shouldn't ever happen here.
5813 * If it ever does, we want to know about it so log the exit code and bail.
5814 */
5815 VMEXIT_CALL_RET(0, hmR0SvmExitUnexpected(pVCpu, pCtx, pSvmTransient));
5816 }
5817
5818#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
5819 case SVM_EXIT_CLGI: VMEXIT_CALL_RET(0, hmR0SvmExitClgi(pVCpu, pCtx, pSvmTransient));
5820 case SVM_EXIT_STGI: VMEXIT_CALL_RET(0, hmR0SvmExitStgi(pVCpu, pCtx, pSvmTransient));
5821 case SVM_EXIT_VMLOAD: VMEXIT_CALL_RET(0, hmR0SvmExitVmload(pVCpu, pCtx, pSvmTransient));
5822 case SVM_EXIT_VMSAVE: VMEXIT_CALL_RET(0, hmR0SvmExitVmsave(pVCpu, pCtx, pSvmTransient));
5823 case SVM_EXIT_INVLPGA: VMEXIT_CALL_RET(0, hmR0SvmExitInvlpga(pVCpu, pCtx, pSvmTransient));
5824 case SVM_EXIT_VMRUN: VMEXIT_CALL_RET(0, hmR0SvmExitVmrun(pVCpu, pCtx, pSvmTransient));
5825#else
5826 case SVM_EXIT_CLGI:
5827 case SVM_EXIT_STGI:
5828 case SVM_EXIT_VMLOAD:
5829 case SVM_EXIT_VMSAVE:
5830 case SVM_EXIT_INVLPGA:
5831 case SVM_EXIT_VMRUN:
5832#endif
5833 case SVM_EXIT_RSM:
5834 case SVM_EXIT_SKINIT:
5835 {
5836 hmR0SvmSetPendingXcptUD(pVCpu);
5837 return VINF_SUCCESS;
5838 }
5839
5840#ifdef HMSVM_ALWAYS_TRAP_ALL_XCPTS
5841 case SVM_EXIT_XCPT_DE:
5842 /* SVM_EXIT_XCPT_DB: */ /* Handled above. */
5843 /* SVM_EXIT_XCPT_NMI: */ /* Handled above. */
5844 /* SVM_EXIT_XCPT_BP: */ /* Handled above. */
5845 case SVM_EXIT_XCPT_OF:
5846 case SVM_EXIT_XCPT_BR:
5847 /* SVM_EXIT_XCPT_UD: */ /* Handled above. */
5848 case SVM_EXIT_XCPT_NM:
5849 case SVM_EXIT_XCPT_DF:
5850 case SVM_EXIT_XCPT_CO_SEG_OVERRUN:
5851 case SVM_EXIT_XCPT_TS:
5852 case SVM_EXIT_XCPT_NP:
5853 case SVM_EXIT_XCPT_SS:
5854 case SVM_EXIT_XCPT_GP:
5855 /* SVM_EXIT_XCPT_PF: */
5856 case SVM_EXIT_XCPT_15: /* Reserved. */
5857 /* SVM_EXIT_XCPT_MF: */ /* Handled above. */
5858 /* SVM_EXIT_XCPT_AC: */ /* Handled above. */
5859 case SVM_EXIT_XCPT_MC:
5860 case SVM_EXIT_XCPT_XF:
5861 case SVM_EXIT_XCPT_20: case SVM_EXIT_XCPT_21: case SVM_EXIT_XCPT_22: case SVM_EXIT_XCPT_23:
5862 case SVM_EXIT_XCPT_24: case SVM_EXIT_XCPT_25: case SVM_EXIT_XCPT_26: case SVM_EXIT_XCPT_27:
5863 case SVM_EXIT_XCPT_28: case SVM_EXIT_XCPT_29: case SVM_EXIT_XCPT_30: case SVM_EXIT_XCPT_31:
5864 VMEXIT_CALL_RET(0, hmR0SvmExitXcptGeneric(pVCpu, pCtx, pSvmTransient));
5865#endif /* HMSVM_ALWAYS_TRAP_ALL_XCPTS */
5866
5867 default:
5868 {
5869 AssertMsgFailed(("hmR0SvmHandleExit: Unknown exit code %#RX64\n", uExitCode));
5870 pVCpu->hm.s.u32HMError = uExitCode;
5871 return VERR_SVM_UNKNOWN_EXIT;
5872 }
5873 }
5874 }
5875 }
5876 /* not reached */
5877#undef VMEXIT_CALL_RET
5878}
5879
5880
5881#ifdef DEBUG
5882/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
5883# define HMSVM_ASSERT_PREEMPT_CPUID_VAR() \
5884 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
5885
5886# define HMSVM_ASSERT_PREEMPT_CPUID() \
5887 do \
5888 { \
5889 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
5890 AssertMsg(idAssertCpu == idAssertCpuNow, ("SVM %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
5891 } while (0)
5892
5893# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() \
5894 do { \
5895 AssertPtr(pVCpu); \
5896 AssertPtr(pCtx); \
5897 AssertPtr(pSvmTransient); \
5898 Assert(ASMIntAreEnabled()); \
5899 HMSVM_ASSERT_PREEMPT_SAFE(); \
5900 HMSVM_ASSERT_PREEMPT_CPUID_VAR(); \
5901 Log4Func(("vcpu[%u] -v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-\n", (uint32_t)pVCpu->idCpu)); \
5902 HMSVM_ASSERT_PREEMPT_SAFE(); \
5903 if (VMMR0IsLogFlushDisabled(pVCpu)) \
5904 HMSVM_ASSERT_PREEMPT_CPUID(); \
5905 } while (0)
5906#else /* Release builds */
5907# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() do { NOREF(pVCpu); NOREF(pCtx); NOREF(pSvmTransient); } while (0)
5908#endif
5909
5910
5911/**
5912 * Worker for hmR0SvmInterpretInvlpg().
5913 *
5914 * @return VBox status code.
5915 * @param pVCpu The cross context virtual CPU structure.
5916 * @param pCpu Pointer to the disassembler state.
5917 * @param pCtx The guest CPU context.
5918 */
5919static int hmR0SvmInterpretInvlPgEx(PVMCPU pVCpu, PDISCPUSTATE pCpu, PCPUMCTX pCtx)
5920{
5921 DISQPVPARAMVAL Param1;
5922 RTGCPTR GCPtrPage;
5923
5924 int rc = DISQueryParamVal(CPUMCTX2CORE(pCtx), pCpu, &pCpu->Param1, &Param1, DISQPVWHICH_SRC);
5925 if (RT_FAILURE(rc))
5926 return VERR_EM_INTERPRETER;
5927
5928 if ( Param1.type == DISQPV_TYPE_IMMEDIATE
5929 || Param1.type == DISQPV_TYPE_ADDRESS)
5930 {
5931 if (!(Param1.flags & (DISQPV_FLAG_32 | DISQPV_FLAG_64)))
5932 return VERR_EM_INTERPRETER;
5933
5934 GCPtrPage = Param1.val.val64;
5935 VBOXSTRICTRC rc2 = EMInterpretInvlpg(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx), GCPtrPage);
5936 rc = VBOXSTRICTRC_VAL(rc2);
5937 }
5938 else
5939 {
5940 Log4Func(("Invalid parameter type %#x\n", Param1.type));
5941 rc = VERR_EM_INTERPRETER;
5942 }
5943
5944 return rc;
5945}
5946
5947
5948/**
5949 * Interprets INVLPG.
5950 *
5951 * @returns VBox status code.
5952 * @retval VINF_* Scheduling instructions.
5953 * @retval VERR_EM_INTERPRETER Something we can't cope with.
5954 * @retval VERR_* Fatal errors.
5955 *
5956 * @param pVM The cross context VM structure.
5957 * @param pVCpu The cross context virtual CPU structure.
5958 * @param pCtx The guest CPU context.
5959 *
5960 * @remarks Updates the RIP if the instruction was executed successfully.
5961 */
5962static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
5963{
5964 /* Only allow 32 & 64 bit code. */
5965 if (CPUMGetGuestCodeBits(pVCpu) != 16)
5966 {
5967 PDISSTATE pDis = &pVCpu->hm.s.DisState;
5968 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL /* pcbInstr */);
5969 if ( RT_SUCCESS(rc)
5970 && pDis->pCurInstr->uOpcode == OP_INVLPG)
5971 {
5972 rc = hmR0SvmInterpretInvlPgEx(pVCpu, pDis, pCtx);
5973 if (RT_SUCCESS(rc))
5974 pCtx->rip += pDis->cbInstr;
5975 return rc;
5976 }
5977 else
5978 Log4Func(("EMInterpretDisasCurrent failed! rc=%Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
5979 }
5980 return VERR_EM_INTERPRETER;
5981}
5982
5983
5984/**
5985 * Gets the IEM exception flags for the specified SVM event.
5986 *
5987 * @returns The IEM exception flags.
5988 * @param pEvent Pointer to the SVM event.
5989 *
5990 * @remarks This function currently only constructs flags required for
5991 * IEMEvaluateRecursiveXcpt and not the complete flags (e.g. error-code
5992 * and CR2 aspects of an exception are not included).
5993 */
5994static uint32_t hmR0SvmGetIemXcptFlags(PCSVMEVENT pEvent)
5995{
5996 uint8_t const uEventType = pEvent->n.u3Type;
5997 uint32_t fIemXcptFlags;
5998 switch (uEventType)
5999 {
6000 case SVM_EVENT_EXCEPTION:
6001 /*
6002 * Only INT3 and INTO instructions can raise #BP and #OF exceptions.
6003 * See AMD spec. Table 8-1. "Interrupt Vector Source and Cause".
6004 */
6005 if (pEvent->n.u8Vector == X86_XCPT_BP)
6006 {
6007 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT | IEM_XCPT_FLAGS_BP_INSTR;
6008 break;
6009 }
6010 if (pEvent->n.u8Vector == X86_XCPT_OF)
6011 {
6012 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT | IEM_XCPT_FLAGS_OF_INSTR;
6013 break;
6014 }
6015 /** @todo How do we distinguish ICEBP \#DB from the regular one? */
6016 RT_FALL_THRU();
6017 case SVM_EVENT_NMI:
6018 fIemXcptFlags = IEM_XCPT_FLAGS_T_CPU_XCPT;
6019 break;
6020
6021 case SVM_EVENT_EXTERNAL_IRQ:
6022 fIemXcptFlags = IEM_XCPT_FLAGS_T_EXT_INT;
6023 break;
6024
6025 case SVM_EVENT_SOFTWARE_INT:
6026 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT;
6027 break;
6028
6029 default:
6030 fIemXcptFlags = 0;
6031 AssertMsgFailed(("Unexpected event type! uEventType=%#x uVector=%#x", uEventType, pEvent->n.u8Vector));
6032 break;
6033 }
6034 return fIemXcptFlags;
6035}
6036
6037
6038/**
6039 * Handle a condition that occurred while delivering an event through the guest
6040 * IDT.
6041 *
6042 * @returns VBox status code (informational error codes included).
6043 * @retval VINF_SUCCESS if we should continue handling the \#VMEXIT.
6044 * @retval VINF_HM_DOUBLE_FAULT if a \#DF condition was detected and we ought to
6045 * continue execution of the guest which will delivery the \#DF.
6046 * @retval VINF_EM_RESET if we detected a triple-fault condition.
6047 * @retval VERR_EM_GUEST_CPU_HANG if we detected a guest CPU hang.
6048 *
6049 * @param pVCpu The cross context virtual CPU structure.
6050 * @param pCtx Pointer to the guest-CPU context.
6051 * @param pSvmTransient Pointer to the SVM transient structure.
6052 *
6053 * @remarks No-long-jump zone!!!
6054 */
6055static int hmR0SvmCheckExitDueToEventDelivery(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6056{
6057 int rc = VINF_SUCCESS;
6058 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6059 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, CPUMCTX_EXTRN_CR2);
6060
6061 Log4(("EXITINTINFO: Pending vectoring event %#RX64 Valid=%RTbool ErrValid=%RTbool Err=%#RX32 Type=%u Vector=%u\n",
6062 pVmcb->ctrl.ExitIntInfo.u, !!pVmcb->ctrl.ExitIntInfo.n.u1Valid, !!pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid,
6063 pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode, pVmcb->ctrl.ExitIntInfo.n.u3Type, pVmcb->ctrl.ExitIntInfo.n.u8Vector));
6064
6065 /*
6066 * The EXITINTINFO (if valid) contains the prior exception (IDT vector) that was trying to
6067 * be delivered to the guest which caused a #VMEXIT which was intercepted (Exit vector).
6068 *
6069 * See AMD spec. 15.7.3 "EXITINFO Pseudo-Code".
6070 */
6071 if (pVmcb->ctrl.ExitIntInfo.n.u1Valid)
6072 {
6073 IEMXCPTRAISE enmRaise;
6074 IEMXCPTRAISEINFO fRaiseInfo;
6075 bool const fExitIsHwXcpt = pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0 <= SVM_EXIT_XCPT_31;
6076 uint8_t const uIdtVector = pVmcb->ctrl.ExitIntInfo.n.u8Vector;
6077 if (fExitIsHwXcpt)
6078 {
6079 uint8_t const uExitVector = pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0;
6080 uint32_t const fIdtVectorFlags = hmR0SvmGetIemXcptFlags(&pVmcb->ctrl.ExitIntInfo);
6081 uint32_t const fExitVectorFlags = IEM_XCPT_FLAGS_T_CPU_XCPT;
6082 enmRaise = IEMEvaluateRecursiveXcpt(pVCpu, fIdtVectorFlags, uIdtVector, fExitVectorFlags, uExitVector, &fRaiseInfo);
6083 }
6084 else
6085 {
6086 /*
6087 * If delivery of an event caused a #VMEXIT that is not an exception (e.g. #NPF)
6088 * then we end up here.
6089 *
6090 * If the event was:
6091 * - a software interrupt, we can re-execute the instruction which will
6092 * regenerate the event.
6093 * - an NMI, we need to clear NMI blocking and re-inject the NMI.
6094 * - a hardware exception or external interrupt, we re-inject it.
6095 */
6096 fRaiseInfo = IEMXCPTRAISEINFO_NONE;
6097 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_SOFTWARE_INT)
6098 enmRaise = IEMXCPTRAISE_REEXEC_INSTR;
6099 else
6100 enmRaise = IEMXCPTRAISE_PREV_EVENT;
6101 }
6102
6103 switch (enmRaise)
6104 {
6105 case IEMXCPTRAISE_CURRENT_XCPT:
6106 case IEMXCPTRAISE_PREV_EVENT:
6107 {
6108 /* For software interrupts, we shall re-execute the instruction. */
6109 if (!(fRaiseInfo & IEMXCPTRAISEINFO_SOFT_INT_XCPT))
6110 {
6111 RTGCUINTPTR GCPtrFaultAddress = 0;
6112
6113 /* If we are re-injecting an NMI, clear NMI blocking. */
6114 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_NMI)
6115 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
6116
6117 /* Determine a vectoring #PF condition, see comment in hmR0SvmExitXcptPF(). */
6118 if (fRaiseInfo & (IEMXCPTRAISEINFO_EXT_INT_PF | IEMXCPTRAISEINFO_NMI_PF))
6119 {
6120 pSvmTransient->fVectoringPF = true;
6121 Log4Func(("IDT: Pending vectoring #PF due to delivery of Ext-Int/NMI. uCR2=%#RX64\n", pCtx->cr2));
6122 }
6123 else if ( pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXCEPTION
6124 && uIdtVector == X86_XCPT_PF)
6125 {
6126 /*
6127 * If the previous exception was a #PF, we need to recover the CR2 value.
6128 * This can't happen with shadow paging.
6129 */
6130 GCPtrFaultAddress = pCtx->cr2;
6131 }
6132
6133 /*
6134 * Without nested paging, when uExitVector is #PF, CR2 value will be updated from the VMCB's
6135 * exit info. fields, if it's a guest #PF, see hmR0SvmExitXcptPF().
6136 */
6137 Assert(pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT);
6138 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
6139 hmR0SvmSetPendingEvent(pVCpu, &pVmcb->ctrl.ExitIntInfo, GCPtrFaultAddress);
6140
6141 Log4Func(("IDT: Pending vectoring event %#RX64 ErrValid=%RTbool Err=%#RX32 GCPtrFaultAddress=%#RX64\n",
6142 pVmcb->ctrl.ExitIntInfo.u, RT_BOOL(pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid),
6143 pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode, GCPtrFaultAddress));
6144 }
6145 break;
6146 }
6147
6148 case IEMXCPTRAISE_REEXEC_INSTR:
6149 {
6150 Assert(rc == VINF_SUCCESS);
6151 break;
6152 }
6153
6154 case IEMXCPTRAISE_DOUBLE_FAULT:
6155 {
6156 /*
6157 * Determing a vectoring double #PF condition. Used later, when PGM evaluates
6158 * the second #PF as a guest #PF (and not a shadow #PF) and needs to be
6159 * converted into a #DF.
6160 */
6161 if (fRaiseInfo & IEMXCPTRAISEINFO_PF_PF)
6162 {
6163 Log4Func(("IDT: Pending vectoring double #PF uCR2=%#RX64\n", pCtx->cr2));
6164 pSvmTransient->fVectoringDoublePF = true;
6165 Assert(rc == VINF_SUCCESS);
6166 }
6167 else
6168 {
6169 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
6170 hmR0SvmSetPendingXcptDF(pVCpu);
6171 rc = VINF_HM_DOUBLE_FAULT;
6172 }
6173 break;
6174 }
6175
6176 case IEMXCPTRAISE_TRIPLE_FAULT:
6177 {
6178 rc = VINF_EM_RESET;
6179 break;
6180 }
6181
6182 case IEMXCPTRAISE_CPU_HANG:
6183 {
6184 rc = VERR_EM_GUEST_CPU_HANG;
6185 break;
6186 }
6187
6188 default:
6189 {
6190 AssertMsgFailed(("hmR0SvmExitCpuid: EMInterpretCpuId failed with %Rrc\n", rc));
6191 rc = VERR_SVM_IPE_2;
6192 break;
6193 }
6194 }
6195 }
6196 Assert(rc == VINF_SUCCESS || rc == VINF_HM_DOUBLE_FAULT || rc == VINF_EM_RESET || rc == VERR_EM_GUEST_CPU_HANG);
6197 NOREF(pCtx);
6198 return rc;
6199}
6200
6201
6202/**
6203 * Advances the guest RIP making use of the CPU's NRIP_SAVE feature if
6204 * supported, otherwise advances the RIP by the number of bytes specified in
6205 * @a cb.
6206 *
6207 * @param pVCpu The cross context virtual CPU structure.
6208 * @param pCtx Pointer to the guest-CPU context.
6209 * @param cb RIP increment value in bytes.
6210 *
6211 * @remarks Use this function only from \#VMEXIT's where the NRIP value is valid
6212 * when NRIP_SAVE is supported by the CPU, otherwise use
6213 * hmR0SvmAdvanceRipDumb!
6214 */
6215DECLINLINE(void) hmR0SvmAdvanceRipHwAssist(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t cb)
6216{
6217 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6218 if (fSupportsNextRipSave)
6219 {
6220 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6221 Assert(pVmcb);
6222 Assert(pVmcb->ctrl.u64NextRIP);
6223 Assert(!(pCtx->fExtrn & CPUMCTX_EXTRN_RIP));
6224 AssertRelease(pVmcb->ctrl.u64NextRIP - pCtx->rip == cb); /* temporary, remove later */
6225 pCtx->rip = pVmcb->ctrl.u64NextRIP;
6226 }
6227 else
6228 pCtx->rip += cb;
6229
6230 HMSVM_UPDATE_INTR_SHADOW(pVCpu, pCtx);
6231}
6232
6233
6234/**
6235 * Gets the length of the current instruction if the CPU supports the NRIP_SAVE
6236 * feature. Otherwise, returns the value in @a cbLikely.
6237 *
6238 * @param pVCpu The cross context virtual CPU structure.
6239 * @param pCtx Pointer to the guest-CPU context.
6240 * @param cbLikely The likely instruction length.
6241 */
6242DECLINLINE(uint8_t) hmR0SvmGetInstrLengthHwAssist(PVMCPU pVCpu, PCPUMCTX pCtx, uint8_t cbLikely)
6243{
6244 Assert(cbLikely <= 15); /* See Intel spec. 2.3.11 "AVX Instruction Length" */
6245 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6246 if (fSupportsNextRipSave)
6247 {
6248 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6249 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6250 Assert(cbInstr == cbLikely);
6251 return cbInstr;
6252 }
6253 return cbLikely;
6254}
6255
6256
6257/**
6258 * Advances the guest RIP by the number of bytes specified in @a cb. This does
6259 * not make use of any hardware features to determine the instruction length.
6260 *
6261 * @param pVCpu The cross context virtual CPU structure.
6262 * @param pCtx Pointer to the guest-CPU context.
6263 * @param cb RIP increment value in bytes.
6264 */
6265DECLINLINE(void) hmR0SvmAdvanceRipDumb(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t cb)
6266{
6267 pCtx->rip += cb;
6268 HMSVM_UPDATE_INTR_SHADOW(pVCpu, pCtx);
6269}
6270#undef HMSVM_UPDATE_INTR_SHADOW
6271
6272
6273/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
6274/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #VMEXIT handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
6275/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
6276
6277/** @name \#VMEXIT handlers.
6278 * @{
6279 */
6280
6281/**
6282 * \#VMEXIT handler for external interrupts, NMIs, FPU assertion freeze and INIT
6283 * signals (SVM_EXIT_INTR, SVM_EXIT_NMI, SVM_EXIT_FERR_FREEZE, SVM_EXIT_INIT).
6284 */
6285HMSVM_EXIT_DECL hmR0SvmExitIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6286{
6287 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6288
6289 if (pSvmTransient->u64ExitCode == SVM_EXIT_NMI)
6290 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGC);
6291 else if (pSvmTransient->u64ExitCode == SVM_EXIT_INTR)
6292 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
6293
6294 /*
6295 * AMD-V has no preemption timer and the generic periodic preemption timer has no way to
6296 * signal -before- the timer fires if the current interrupt is our own timer or a some
6297 * other host interrupt. We also cannot examine what interrupt it is until the host
6298 * actually take the interrupt.
6299 *
6300 * Going back to executing guest code here unconditionally causes random scheduling
6301 * problems (observed on an AMD Phenom 9850 Quad-Core on Windows 64-bit host).
6302 */
6303 return VINF_EM_RAW_INTERRUPT;
6304}
6305
6306
6307/**
6308 * \#VMEXIT handler for WBINVD (SVM_EXIT_WBINVD). Conditional \#VMEXIT.
6309 */
6310HMSVM_EXIT_DECL hmR0SvmExitWbinvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6311{
6312 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6313
6314 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6315 int rc = VINF_SUCCESS;
6316 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6317 return rc;
6318}
6319
6320
6321/**
6322 * \#VMEXIT handler for INVD (SVM_EXIT_INVD). Unconditional \#VMEXIT.
6323 */
6324HMSVM_EXIT_DECL hmR0SvmExitInvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6325{
6326 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6327
6328 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6329 int rc = VINF_SUCCESS;
6330 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6331 return rc;
6332}
6333
6334
6335/**
6336 * \#VMEXIT handler for INVD (SVM_EXIT_CPUID). Conditional \#VMEXIT.
6337 */
6338HMSVM_EXIT_DECL hmR0SvmExitCpuid(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6339{
6340 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6341
6342 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, CPUMCTX_EXTRN_RIP
6343 | CPUMCTX_EXTRN_CS);
6344 VBOXSTRICTRC rcStrict;
6345 PCEMEXITREC pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
6346 EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_CPUID),
6347 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
6348 if (!pExitRec)
6349 {
6350 PVM pVM = pVCpu->CTX_SUFF(pVM);
6351 rcStrict = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
6352 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
6353 {
6354 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6355 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6356 }
6357 else
6358 {
6359 AssertMsgFailed(("hmR0SvmExitCpuid: EMInterpretCpuId failed with %Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
6360 rcStrict = VERR_EM_INTERPRETER;
6361 }
6362 }
6363 else
6364 {
6365 /*
6366 * Frequent exit or something needing probing. Get state and call EMHistoryExec.
6367 */
6368 Assert(pCtx == &pVCpu->cpum.GstCtx);
6369 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, IEM_CPUMCTX_EXTRN_MUST_MASK);
6370
6371 Log4(("CpuIdExit/%u: %04x:%08RX64: %#x/%#x -> EMHistoryExec\n",
6372 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.eax, pVCpu->cpum.GstCtx.ecx));
6373
6374 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
6375
6376 Log4(("CpuIdExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
6377 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
6378 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
6379 }
6380 return VBOXSTRICTRC_TODO(rcStrict);
6381}
6382
6383
6384/**
6385 * \#VMEXIT handler for RDTSC (SVM_EXIT_RDTSC). Conditional \#VMEXIT.
6386 */
6387HMSVM_EXIT_DECL hmR0SvmExitRdtsc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6388{
6389 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6390 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, IEM_CPUMCTX_EXTRN_MUST_MASK);
6391 VBOXSTRICTRC rcStrict = IEMExecDecodedRdtsc(pVCpu, hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 2));
6392 if (rcStrict == VINF_SUCCESS)
6393 pSvmTransient->fUpdateTscOffsetting = true;
6394 else if (rcStrict == VINF_IEM_RAISED_XCPT)
6395 rcStrict = VINF_SUCCESS;
6396 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6397 return VBOXSTRICTRC_TODO(rcStrict);
6398}
6399
6400
6401/**
6402 * \#VMEXIT handler for RDTSCP (SVM_EXIT_RDTSCP). Conditional \#VMEXIT.
6403 */
6404HMSVM_EXIT_DECL hmR0SvmExitRdtscp(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6405{
6406 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6407 VBOXSTRICTRC rcStrict = IEMExecDecodedRdtscp(pVCpu, hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3));
6408 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, IEM_CPUMCTX_EXTRN_MUST_MASK);
6409 if (rcStrict == VINF_SUCCESS)
6410 pSvmTransient->fUpdateTscOffsetting = true;
6411 else if (rcStrict == VINF_IEM_RAISED_XCPT)
6412 rcStrict = VINF_SUCCESS;
6413 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6414 return VBOXSTRICTRC_TODO(rcStrict);
6415}
6416
6417
6418/**
6419 * \#VMEXIT handler for RDPMC (SVM_EXIT_RDPMC). Conditional \#VMEXIT.
6420 */
6421HMSVM_EXIT_DECL hmR0SvmExitRdpmc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6422{
6423 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6424 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, CPUMCTX_EXTRN_CR0
6425 | CPUMCTX_EXTRN_CR4
6426 | CPUMCTX_EXTRN_SS);
6427
6428 int rc = EMInterpretRdpmc(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
6429 if (RT_LIKELY(rc == VINF_SUCCESS))
6430 {
6431 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6432 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6433 }
6434 else
6435 {
6436 AssertMsgFailed(("hmR0SvmExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
6437 rc = VERR_EM_INTERPRETER;
6438 }
6439 return rc;
6440}
6441
6442
6443/**
6444 * \#VMEXIT handler for INVLPG (SVM_EXIT_INVLPG). Conditional \#VMEXIT.
6445 */
6446HMSVM_EXIT_DECL hmR0SvmExitInvlpg(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6447{
6448 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6449 PVM pVM = pVCpu->CTX_SUFF(pVM);
6450 Assert(!pVM->hm.s.fNestedPaging);
6451
6452 bool const fSupportsDecodeAssists = hmR0SvmSupportsDecodeAssists(pVCpu, pCtx);
6453 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6454 if ( fSupportsDecodeAssists
6455 && fSupportsNextRipSave)
6456 {
6457 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, IEM_CPUMCTX_EXTRN_MUST_MASK);
6458 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6459 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6460 RTGCPTR const GCPtrPage = pVmcb->ctrl.u64ExitInfo1;
6461 VBOXSTRICTRC rcStrict = IEMExecDecodedInvlpg(pVCpu, cbInstr, GCPtrPage);
6462 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6463 return VBOXSTRICTRC_VAL(rcStrict);
6464 }
6465
6466 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
6467 int rc = hmR0SvmInterpretInvlpg(pVM, pVCpu, pCtx); /* Updates RIP if successful. */
6468 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
6469 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6470 return rc;
6471}
6472
6473
6474/**
6475 * \#VMEXIT handler for HLT (SVM_EXIT_HLT). Conditional \#VMEXIT.
6476 */
6477HMSVM_EXIT_DECL hmR0SvmExitHlt(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6478{
6479 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6480
6481 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 1);
6482 int rc = EMShouldContinueAfterHalt(pVCpu, pCtx) ? VINF_SUCCESS : VINF_EM_HALT;
6483 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6484
6485 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
6486 if (rc != VINF_SUCCESS)
6487 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHltToR3);
6488 return rc;
6489}
6490
6491
6492/**
6493 * \#VMEXIT handler for MONITOR (SVM_EXIT_MONITOR). Conditional \#VMEXIT.
6494 */
6495HMSVM_EXIT_DECL hmR0SvmExitMonitor(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6496{
6497 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6498 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, CPUMCTX_EXTRN_CR0
6499 | CPUMCTX_EXTRN_SS);
6500
6501 int rc = EMInterpretMonitor(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
6502 if (RT_LIKELY(rc == VINF_SUCCESS))
6503 {
6504 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3);
6505 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6506 }
6507 else
6508 {
6509 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMonitor: EMInterpretMonitor failed with %Rrc\n", rc));
6510 rc = VERR_EM_INTERPRETER;
6511 }
6512 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMonitor);
6513 return rc;
6514}
6515
6516
6517/**
6518 * \#VMEXIT handler for MWAIT (SVM_EXIT_MWAIT). Conditional \#VMEXIT.
6519 */
6520HMSVM_EXIT_DECL hmR0SvmExitMwait(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6521{
6522 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6523 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, CPUMCTX_EXTRN_CR0
6524 | CPUMCTX_EXTRN_SS);
6525
6526 VBOXSTRICTRC rc2 = EMInterpretMWait(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
6527 int rc = VBOXSTRICTRC_VAL(rc2);
6528 if ( rc == VINF_EM_HALT
6529 || rc == VINF_SUCCESS)
6530 {
6531 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3);
6532
6533 if ( rc == VINF_EM_HALT
6534 && EMMonitorWaitShouldContinue(pVCpu, pCtx))
6535 {
6536 rc = VINF_SUCCESS;
6537 }
6538 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6539 }
6540 else
6541 {
6542 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMwait: EMInterpretMWait failed with %Rrc\n", rc));
6543 rc = VERR_EM_INTERPRETER;
6544 }
6545 AssertMsg(rc == VINF_SUCCESS || rc == VINF_EM_HALT || rc == VERR_EM_INTERPRETER,
6546 ("hmR0SvmExitMwait: EMInterpretMWait failed rc=%Rrc\n", rc));
6547 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMwait);
6548 return rc;
6549}
6550
6551
6552/**
6553 * \#VMEXIT handler for shutdown (triple-fault) (SVM_EXIT_SHUTDOWN). Conditional
6554 * \#VMEXIT.
6555 */
6556HMSVM_EXIT_DECL hmR0SvmExitShutdown(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6557{
6558 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6559 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
6560 return VINF_EM_RESET;
6561}
6562
6563
6564/**
6565 * \#VMEXIT handler for unexpected exits. Conditional \#VMEXIT.
6566 */
6567HMSVM_EXIT_DECL hmR0SvmExitUnexpected(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6568{
6569 RT_NOREF(pCtx);
6570 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6571 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
6572 AssertMsgFailed(("hmR0SvmExitUnexpected: ExitCode=%#RX64 uExitInfo1=%#RX64 uExitInfo2=%#RX64\n", pSvmTransient->u64ExitCode,
6573 pVmcb->ctrl.u64ExitInfo1, pVmcb->ctrl.u64ExitInfo2));
6574 RT_NOREF(pVmcb);
6575 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
6576 return VERR_SVM_UNEXPECTED_EXIT;
6577}
6578
6579
6580/**
6581 * \#VMEXIT handler for CRx reads (SVM_EXIT_READ_CR*). Conditional \#VMEXIT.
6582 */
6583HMSVM_EXIT_DECL hmR0SvmExitReadCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6584{
6585 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6586
6587 Log4Func(("CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
6588#ifdef VBOX_WITH_STATISTICS
6589 switch (pSvmTransient->u64ExitCode)
6590 {
6591 case SVM_EXIT_READ_CR0: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR0Read); break;
6592 case SVM_EXIT_READ_CR2: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR2Read); break;
6593 case SVM_EXIT_READ_CR3: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR3Read); break;
6594 case SVM_EXIT_READ_CR4: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR4Read); break;
6595 case SVM_EXIT_READ_CR8: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR8Read); break;
6596 }
6597#endif
6598
6599 bool const fSupportsDecodeAssists = hmR0SvmSupportsDecodeAssists(pVCpu, pCtx);
6600 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6601 if ( fSupportsDecodeAssists
6602 && fSupportsNextRipSave)
6603 {
6604 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6605 bool const fMovCRx = RT_BOOL(pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_MASK);
6606 if (fMovCRx)
6607 {
6608 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, IEM_CPUMCTX_EXTRN_MUST_MASK);
6609 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6610 uint8_t const iCrReg = pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0;
6611 uint8_t const iGReg = pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_GPR_NUMBER;
6612 VBOXSTRICTRC rcStrict = IEMExecDecodedMovCRxRead(pVCpu, cbInstr, iGReg, iCrReg);
6613 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6614 return VBOXSTRICTRC_VAL(rcStrict);
6615 }
6616 /* else: SMSW instruction, fall back below to IEM for this. */
6617 }
6618
6619 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
6620 VBOXSTRICTRC rc2 = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
6621 int rc = VBOXSTRICTRC_VAL(rc2);
6622 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3,
6623 ("hmR0SvmExitReadCRx: EMInterpretInstruction failed rc=%Rrc\n", rc));
6624 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0) <= 15);
6625 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6626 return rc;
6627}
6628
6629
6630/**
6631 * \#VMEXIT handler for CRx writes (SVM_EXIT_WRITE_CR*). Conditional \#VMEXIT.
6632 */
6633HMSVM_EXIT_DECL hmR0SvmExitWriteCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6634{
6635 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6636
6637 uint64_t const uExitCode = pSvmTransient->u64ExitCode;
6638 uint8_t const iCrReg = uExitCode == SVM_EXIT_CR0_SEL_WRITE ? 0 : (pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0);
6639 Assert(iCrReg <= 15);
6640
6641 VBOXSTRICTRC rcStrict = VERR_SVM_IPE_5;
6642 bool fDecodedInstr = false;
6643 bool const fSupportsDecodeAssists = hmR0SvmSupportsDecodeAssists(pVCpu, pCtx);
6644 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6645 if ( fSupportsDecodeAssists
6646 && fSupportsNextRipSave)
6647 {
6648 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6649 bool const fMovCRx = RT_BOOL(pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_MASK);
6650 if (fMovCRx)
6651 {
6652 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, IEM_CPUMCTX_EXTRN_MUST_MASK);
6653 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6654 uint8_t const iGReg = pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_GPR_NUMBER;
6655 Log4Func(("Mov CR%u w/ iGReg=%#x\n", iCrReg, iGReg));
6656 rcStrict = IEMExecDecodedMovCRxWrite(pVCpu, cbInstr, iCrReg, iGReg);
6657 fDecodedInstr = true;
6658 }
6659 /* else: LMSW or CLTS instruction, fall back below to IEM for this. */
6660 }
6661
6662 if (!fDecodedInstr)
6663 {
6664 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, IEM_CPUMCTX_EXTRN_MUST_MASK);
6665 Log4Func(("iCrReg=%#x\n", iCrReg));
6666 rcStrict = IEMExecOneBypassEx(pVCpu, CPUMCTX2CORE(pCtx), NULL);
6667 if (RT_UNLIKELY( rcStrict == VERR_IEM_ASPECT_NOT_IMPLEMENTED
6668 || rcStrict == VERR_IEM_INSTR_NOT_IMPLEMENTED))
6669 rcStrict = VERR_EM_INTERPRETER;
6670 }
6671
6672 if (rcStrict == VINF_SUCCESS)
6673 {
6674 switch (iCrReg)
6675 {
6676 case 0:
6677 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CR0);
6678 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR0Write);
6679 break;
6680
6681 case 2:
6682 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CR2);
6683 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR2Write);
6684 break;
6685
6686 case 3:
6687 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CR3);
6688 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR3Write);
6689 break;
6690
6691 case 4:
6692 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CR4);
6693 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR4Write);
6694 break;
6695
6696 case 8:
6697 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_APIC_TPR);
6698 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR8Write);
6699 break;
6700
6701 default:
6702 {
6703 AssertMsgFailed(("hmR0SvmExitWriteCRx: Invalid/Unexpected Write-CRx exit. u64ExitCode=%#RX64 %#x\n",
6704 pSvmTransient->u64ExitCode, iCrReg));
6705 break;
6706 }
6707 }
6708 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6709 }
6710 else
6711 Assert(rcStrict == VERR_EM_INTERPRETER || rcStrict == VINF_PGM_CHANGE_MODE || rcStrict == VINF_PGM_SYNC_CR3);
6712 return VBOXSTRICTRC_TODO(rcStrict);
6713}
6714
6715
6716/**
6717 * \#VMEXIT helper for read MSRs, see hmR0SvmExitMsr.
6718 *
6719 * @returns VBox status code.
6720 * @param pVCpu The cross context virtual CPU structure.
6721 * @param pVmcb Pointer to the VM control block.
6722 */
6723static int hmR0SvmExitReadMsr(PVMCPU pVCpu, PSVMVMCB pVmcb)
6724{
6725 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
6726 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, CPUMCTX_EXTRN_CR0
6727 | CPUMCTX_EXTRN_RFLAGS
6728 | CPUMCTX_EXTRN_SS
6729 | CPUMCTX_EXTRN_ALL_MSRS);
6730
6731 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
6732 Log4Func(("idMsr=%#RX32\n", pCtx->ecx));
6733
6734 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6735 if (fSupportsNextRipSave)
6736 {
6737 int rc = EMInterpretRdmsr(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
6738 if (RT_LIKELY(rc == VINF_SUCCESS))
6739 {
6740 pCtx->rip = pVmcb->ctrl.u64NextRIP;
6741 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6742 return VINF_SUCCESS;
6743 }
6744
6745 AssertMsg( rc == VERR_EM_INTERPRETER
6746 || rc == VINF_CPUM_R3_MSR_READ, ("EMInterpretRdmsr failed rc=%Rrc\n", rc));
6747 return rc;
6748 }
6749
6750 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
6751 int rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0));
6752 if (RT_UNLIKELY(rc != VINF_SUCCESS))
6753 {
6754 AssertMsg( rc == VERR_EM_INTERPRETER
6755 || rc == VINF_CPUM_R3_MSR_READ, ("EMInterpretInstruction failed rc=%Rrc\n", rc));
6756 }
6757 /* RIP updated by EMInterpretInstruction(). */
6758 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6759 return rc;
6760}
6761
6762
6763/**
6764 * \#VMEXIT helper for write MSRs, see hmR0SvmExitMsr.
6765 *
6766 * @returns VBox status code.
6767 * @param pVCpu The cross context virtual CPU structure.
6768 * @param pVmcb Pointer to the VM control block.
6769 * @param pSvmTransient Pointer to the SVM-transient structure.
6770 */
6771static int hmR0SvmExitWriteMsr(PVMCPU pVCpu, PSVMVMCB pVmcb, PSVMTRANSIENT pSvmTransient)
6772{
6773 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
6774 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, CPUMCTX_EXTRN_CR0
6775 | CPUMCTX_EXTRN_RFLAGS
6776 | CPUMCTX_EXTRN_SS
6777 | CPUMCTX_EXTRN_ALL_MSRS);
6778
6779 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
6780 Log4Func(("idMsr=%#RX32\n", pCtx->ecx));
6781
6782 /*
6783 * Handle TPR patching MSR writes.
6784 * We utilitize the LSTAR MSR for patching.
6785 */
6786 if ( pVCpu->CTX_SUFF(pVM)->hm.s.fTPRPatchingActive
6787 && pCtx->ecx == MSR_K8_LSTAR)
6788 {
6789 if ((pCtx->eax & 0xff) != pSvmTransient->u8GuestTpr)
6790 {
6791 /* Our patch code uses LSTAR for TPR caching for 32-bit guests. */
6792 int rc2 = APICSetTpr(pVCpu, pCtx->eax & 0xff);
6793 AssertRC(rc2);
6794 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_APIC_TPR);
6795 }
6796
6797 int rc = VINF_SUCCESS;
6798 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6799 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6800 return rc;
6801 }
6802
6803 /*
6804 * Handle regular MSR writes.
6805 */
6806 int rc;
6807 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6808 if (fSupportsNextRipSave)
6809 {
6810 rc = EMInterpretWrmsr(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
6811 if (RT_LIKELY(rc == VINF_SUCCESS))
6812 {
6813 pCtx->rip = pVmcb->ctrl.u64NextRIP;
6814 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6815 }
6816 else
6817 AssertMsg( rc == VERR_EM_INTERPRETER
6818 || rc == VINF_CPUM_R3_MSR_WRITE, ("hmR0SvmExitMsr: EMInterpretWrmsr failed rc=%Rrc\n", rc));
6819 }
6820 else
6821 {
6822 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
6823 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */));
6824 if (RT_LIKELY(rc == VINF_SUCCESS))
6825 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc); /* RIP updated by EMInterpretInstruction(). */
6826 else
6827 AssertMsg( rc == VERR_EM_INTERPRETER
6828 || rc == VINF_CPUM_R3_MSR_WRITE, ("hmR0SvmExitMsr: WrMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
6829 }
6830
6831 if (rc == VINF_SUCCESS)
6832 {
6833 /* If this is an X2APIC WRMSR access, update the APIC TPR state. */
6834 if ( pCtx->ecx >= MSR_IA32_X2APIC_START
6835 && pCtx->ecx <= MSR_IA32_X2APIC_END)
6836 {
6837 /*
6838 * We've already saved the APIC related guest-state (TPR) in hmR0SvmPostRunGuest().
6839 * When full APIC register virtualization is implemented we'll have to make sure
6840 * APIC state is saved from the VMCB before EMInterpretWrmsr() changes it.
6841 */
6842 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_APIC_TPR);
6843 }
6844 else
6845 {
6846 switch (pCtx->ecx)
6847 {
6848 case MSR_IA32_TSC: pSvmTransient->fUpdateTscOffsetting = true; break;
6849 case MSR_K6_EFER: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_EFER_MSR); break;
6850 case MSR_K8_FS_BASE: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_FS); break;
6851 case MSR_K8_GS_BASE: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_GS); break;
6852 case MSR_IA32_SYSENTER_CS: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_SYSENTER_CS_MSR); break;
6853 case MSR_IA32_SYSENTER_EIP: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_SYSENTER_EIP_MSR); break;
6854 case MSR_IA32_SYSENTER_ESP: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_SYSENTER_ESP_MSR); break;
6855 }
6856 }
6857 }
6858
6859 /* RIP has been updated by above after EMInterpretWrmsr() or by EMInterpretInstruction(). */
6860 return rc;
6861}
6862
6863
6864/**
6865 * \#VMEXIT handler for MSR read and writes (SVM_EXIT_MSR). Conditional
6866 * \#VMEXIT.
6867 */
6868HMSVM_EXIT_DECL hmR0SvmExitMsr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6869{
6870 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6871
6872 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6873 if (pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_READ)
6874 return hmR0SvmExitReadMsr(pVCpu, pVmcb);
6875
6876 Assert(pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_WRITE);
6877 return hmR0SvmExitWriteMsr(pVCpu, pVmcb, pSvmTransient);
6878}
6879
6880
6881/**
6882 * \#VMEXIT handler for DRx read (SVM_EXIT_READ_DRx). Conditional \#VMEXIT.
6883 */
6884HMSVM_EXIT_DECL hmR0SvmExitReadDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6885{
6886 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6887 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
6888
6889 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
6890
6891 /** @todo Stepping with nested-guest. */
6892 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
6893 {
6894 /* We should -not- get this #VMEXIT if the guest's debug registers were active. */
6895 if (pSvmTransient->fWasGuestDebugStateActive)
6896 {
6897 AssertMsgFailed(("hmR0SvmExitReadDRx: Unexpected exit %#RX32\n", (uint32_t)pSvmTransient->u64ExitCode));
6898 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
6899 return VERR_SVM_UNEXPECTED_EXIT;
6900 }
6901
6902 /*
6903 * Lazy DR0-3 loading.
6904 */
6905 if (!pSvmTransient->fWasHyperDebugStateActive)
6906 {
6907 Assert(!DBGFIsStepping(pVCpu)); Assert(!pVCpu->hm.s.fSingleInstruction);
6908 Log5(("hmR0SvmExitReadDRx: Lazy loading guest debug registers\n"));
6909
6910 /* Don't intercept DRx read and writes. */
6911 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
6912 pVmcb->ctrl.u16InterceptRdDRx = 0;
6913 pVmcb->ctrl.u16InterceptWrDRx = 0;
6914 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
6915
6916 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
6917 VMMRZCallRing3Disable(pVCpu);
6918 HM_DISABLE_PREEMPT();
6919
6920 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
6921 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
6922 Assert(CPUMIsGuestDebugStateActive(pVCpu) || HC_ARCH_BITS == 32);
6923
6924 HM_RESTORE_PREEMPT();
6925 VMMRZCallRing3Enable(pVCpu);
6926
6927 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
6928 return VINF_SUCCESS;
6929 }
6930 }
6931
6932 /*
6933 * Interpret the read/writing of DRx.
6934 */
6935 /** @todo Decode assist. */
6936 VBOXSTRICTRC rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
6937 Log5(("hmR0SvmExitReadDRx: Emulated DRx access: rc=%Rrc\n", VBOXSTRICTRC_VAL(rc)));
6938 if (RT_LIKELY(rc == VINF_SUCCESS))
6939 {
6940 /* Not necessary for read accesses but whatever doesn't hurt for now, will be fixed with decode assist. */
6941 /** @todo CPUM should set this flag! */
6942 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_DR_MASK);
6943 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6944 }
6945 else
6946 Assert(rc == VERR_EM_INTERPRETER);
6947 return VBOXSTRICTRC_TODO(rc);
6948}
6949
6950
6951/**
6952 * \#VMEXIT handler for DRx write (SVM_EXIT_WRITE_DRx). Conditional \#VMEXIT.
6953 */
6954HMSVM_EXIT_DECL hmR0SvmExitWriteDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6955{
6956 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6957 /* For now it's the same since we interpret the instruction anyway. Will change when using of Decode Assist is implemented. */
6958 int rc = hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
6959 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
6960 STAM_COUNTER_DEC(&pVCpu->hm.s.StatExitDRxRead);
6961 return rc;
6962}
6963
6964
6965/**
6966 * \#VMEXIT handler for XCRx write (SVM_EXIT_XSETBV). Conditional \#VMEXIT.
6967 */
6968HMSVM_EXIT_DECL hmR0SvmExitXsetbv(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6969{
6970 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6971 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, IEM_CPUMCTX_EXTRN_MUST_MASK);
6972
6973 /** @todo decode assists... */
6974 VBOXSTRICTRC rcStrict = IEMExecOne(pVCpu);
6975 if (rcStrict == VINF_IEM_RAISED_XCPT)
6976 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_XCPT_RAISED_MASK);
6977
6978 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pCtx->cr4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
6979 Log4Func(("New XCR0=%#RX64 fLoadSaveGuestXcr0=%d (cr4=%RX64) rcStrict=%Rrc\n", pCtx->aXcr[0], pVCpu->hm.s.fLoadSaveGuestXcr0,
6980 pCtx->cr4, VBOXSTRICTRC_VAL(rcStrict)));
6981
6982 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6983 return VBOXSTRICTRC_TODO(rcStrict);
6984}
6985
6986
6987/**
6988 * \#VMEXIT handler for I/O instructions (SVM_EXIT_IOIO). Conditional \#VMEXIT.
6989 */
6990HMSVM_EXIT_DECL hmR0SvmExitIOInstr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6991{
6992 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6993 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, IEM_CPUMCTX_EXTRN_MUST_MASK
6994 | CPUMCTX_EXTRN_SREG_MASK);
6995
6996 /* I/O operation lookup arrays. */
6997 static uint32_t const s_aIOSize[8] = { 0, 1, 2, 0, 4, 0, 0, 0 }; /* Size of the I/O accesses in bytes. */
6998 static uint32_t const s_aIOOpAnd[8] = { 0, 0xff, 0xffff, 0, 0xffffffff, 0, 0, 0 }; /* AND masks for saving
6999 the result (in AL/AX/EAX). */
7000 Log4Func(("CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
7001
7002 PVM pVM = pVCpu->CTX_SUFF(pVM);
7003 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7004
7005 /* Refer AMD spec. 15.10.2 "IN and OUT Behaviour" and Figure 15-2. "EXITINFO1 for IOIO Intercept" for the format. */
7006 SVMIOIOEXITINFO IoExitInfo;
7007 IoExitInfo.u = (uint32_t)pVmcb->ctrl.u64ExitInfo1;
7008 uint32_t uIOWidth = (IoExitInfo.u >> 4) & 0x7;
7009 uint32_t cbValue = s_aIOSize[uIOWidth];
7010 uint32_t uAndVal = s_aIOOpAnd[uIOWidth];
7011
7012 if (RT_UNLIKELY(!cbValue))
7013 {
7014 AssertMsgFailed(("hmR0SvmExitIOInstr: Invalid IO operation. uIOWidth=%u\n", uIOWidth));
7015 return VERR_EM_INTERPRETER;
7016 }
7017
7018 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, CPUMCTX_EXTRN_RIP
7019 | CPUMCTX_EXTRN_CS
7020 | CPUMCTX_EXTRN_RFLAGS);
7021 VBOXSTRICTRC rcStrict;
7022 PCEMEXITREC pExitRec = NULL;
7023 if ( !pVCpu->hm.s.fSingleInstruction
7024 && !pVCpu->cpum.GstCtx.eflags.Bits.u1TF)
7025 pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
7026 !IoExitInfo.n.u1Str
7027 ? IoExitInfo.n.u1Type == SVM_IOIO_READ
7028 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_READ)
7029 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_WRITE)
7030 : IoExitInfo.n.u1Type == SVM_IOIO_READ
7031 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_STR_READ)
7032 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_STR_WRITE),
7033 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
7034 if (!pExitRec)
7035 {
7036 bool fUpdateRipAlready = false;
7037 if (IoExitInfo.n.u1Str)
7038 {
7039 /* INS/OUTS - I/O String instruction. */
7040 /** @todo Huh? why can't we use the segment prefix information given by AMD-V
7041 * in EXITINFO1? Investigate once this thing is up and running. */
7042 Log4Func(("CS:RIP=%04x:%08RX64 %#06x/%u %c str\n", pCtx->cs.Sel, pCtx->rip, IoExitInfo.n.u16Port, cbValue,
7043 IoExitInfo.n.u1Type == SVM_IOIO_WRITE ? 'w' : 'r'));
7044 AssertReturn(pCtx->dx == IoExitInfo.n.u16Port, VERR_SVM_IPE_2);
7045 static IEMMODE const s_aenmAddrMode[8] =
7046 {
7047 (IEMMODE)-1, IEMMODE_16BIT, IEMMODE_32BIT, (IEMMODE)-1, IEMMODE_64BIT, (IEMMODE)-1, (IEMMODE)-1, (IEMMODE)-1
7048 };
7049 IEMMODE enmAddrMode = s_aenmAddrMode[(IoExitInfo.u >> 7) & 0x7];
7050 if (enmAddrMode != (IEMMODE)-1)
7051 {
7052 uint64_t cbInstr = pVmcb->ctrl.u64ExitInfo2 - pCtx->rip;
7053 if (cbInstr <= 15 && cbInstr >= 1)
7054 {
7055 Assert(cbInstr >= 1U + IoExitInfo.n.u1Rep);
7056 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
7057 {
7058 /* Don't know exactly how to detect whether u3Seg is valid, currently
7059 only enabling it for Bulldozer and later with NRIP. OS/2 broke on
7060 2384 Opterons when only checking NRIP. */
7061 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
7062 if ( fSupportsNextRipSave
7063 && pVM->cpum.ro.GuestFeatures.enmMicroarch >= kCpumMicroarch_AMD_15h_First)
7064 {
7065 AssertMsg(IoExitInfo.n.u3Seg == X86_SREG_DS || cbInstr > 1U + IoExitInfo.n.u1Rep,
7066 ("u32Seg=%d cbInstr=%d u1REP=%d", IoExitInfo.n.u3Seg, cbInstr, IoExitInfo.n.u1Rep));
7067 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1Rep, (uint8_t)cbInstr,
7068 IoExitInfo.n.u3Seg, true /*fIoChecked*/);
7069 }
7070 else if (cbInstr == 1U + IoExitInfo.n.u1Rep)
7071 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1Rep, (uint8_t)cbInstr,
7072 X86_SREG_DS, true /*fIoChecked*/);
7073 else
7074 rcStrict = IEMExecOne(pVCpu);
7075 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
7076 }
7077 else
7078 {
7079 AssertMsg(IoExitInfo.n.u3Seg == X86_SREG_ES /*=0*/, ("%#x\n", IoExitInfo.n.u3Seg));
7080 rcStrict = IEMExecStringIoRead(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1Rep, (uint8_t)cbInstr,
7081 true /*fIoChecked*/);
7082 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
7083 }
7084 }
7085 else
7086 {
7087 AssertMsgFailed(("rip=%RX64 nrip=%#RX64 cbInstr=%#RX64\n", pCtx->rip, pVmcb->ctrl.u64ExitInfo2, cbInstr));
7088 rcStrict = IEMExecOne(pVCpu);
7089 }
7090 }
7091 else
7092 {
7093 AssertMsgFailed(("IoExitInfo=%RX64\n", IoExitInfo.u));
7094 rcStrict = IEMExecOne(pVCpu);
7095 }
7096 fUpdateRipAlready = true;
7097 }
7098 else
7099 {
7100 /* IN/OUT - I/O instruction. */
7101 Assert(!IoExitInfo.n.u1Rep);
7102
7103 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
7104 {
7105 rcStrict = IOMIOPortWrite(pVM, pVCpu, IoExitInfo.n.u16Port, pCtx->eax & uAndVal, cbValue);
7106 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
7107 }
7108 else
7109 {
7110 uint32_t u32Val = 0;
7111 rcStrict = IOMIOPortRead(pVM, pVCpu, IoExitInfo.n.u16Port, &u32Val, cbValue);
7112 if (IOM_SUCCESS(rcStrict))
7113 {
7114 /* Save result of I/O IN instr. in AL/AX/EAX. */
7115 /** @todo r=bird: 32-bit op size should clear high bits of rax! */
7116 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
7117 }
7118 else if (rcStrict == VINF_IOM_R3_IOPORT_READ)
7119 HMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, cbValue);
7120
7121 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
7122 }
7123 }
7124
7125 if (IOM_SUCCESS(rcStrict))
7126 {
7127 /* AMD-V saves the RIP of the instruction following the IO instruction in EXITINFO2. */
7128 if (!fUpdateRipAlready)
7129 pCtx->rip = pVmcb->ctrl.u64ExitInfo2;
7130
7131 /*
7132 * If any I/O breakpoints are armed, we need to check if one triggered
7133 * and take appropriate action.
7134 * Note that the I/O breakpoint type is undefined if CR4.DE is 0.
7135 */
7136 /** @todo Optimize away the DBGFBpIsHwIoArmed call by having DBGF tell the
7137 * execution engines about whether hyper BPs and such are pending. */
7138 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, CPUMCTX_EXTRN_DR7);
7139 uint32_t const uDr7 = pCtx->dr[7];
7140 if (RT_UNLIKELY( ( (uDr7 & X86_DR7_ENABLED_MASK)
7141 && X86_DR7_ANY_RW_IO(uDr7)
7142 && (pCtx->cr4 & X86_CR4_DE))
7143 || DBGFBpIsHwIoArmed(pVM)))
7144 {
7145 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
7146 VMMRZCallRing3Disable(pVCpu);
7147 HM_DISABLE_PREEMPT();
7148
7149 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
7150 CPUMR0DebugStateMaybeSaveGuest(pVCpu, false /*fDr6*/);
7151
7152 VBOXSTRICTRC rcStrict2 = DBGFBpCheckIo(pVM, pVCpu, pCtx, IoExitInfo.n.u16Port, cbValue);
7153 if (rcStrict2 == VINF_EM_RAW_GUEST_TRAP)
7154 {
7155 /* Raise #DB. */
7156 pVmcb->guest.u64DR6 = pCtx->dr[6];
7157 pVmcb->guest.u64DR7 = pCtx->dr[7];
7158 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
7159 hmR0SvmSetPendingXcptDB(pVCpu);
7160 }
7161 /* rcStrict is VINF_SUCCESS, VINF_IOM_R3_IOPORT_COMMIT_WRITE, or in [VINF_EM_FIRST..VINF_EM_LAST],
7162 however we can ditch VINF_IOM_R3_IOPORT_COMMIT_WRITE as it has VMCPU_FF_IOM as backup. */
7163 else if ( rcStrict2 != VINF_SUCCESS
7164 && (rcStrict == VINF_SUCCESS || rcStrict2 < rcStrict))
7165 rcStrict = rcStrict2;
7166 AssertCompile(VINF_EM_LAST < VINF_IOM_R3_IOPORT_COMMIT_WRITE);
7167
7168 HM_RESTORE_PREEMPT();
7169 VMMRZCallRing3Enable(pVCpu);
7170 }
7171
7172 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
7173 }
7174
7175#ifdef VBOX_STRICT
7176 if (rcStrict == VINF_IOM_R3_IOPORT_READ)
7177 Assert(IoExitInfo.n.u1Type == SVM_IOIO_READ);
7178 else if (rcStrict == VINF_IOM_R3_IOPORT_WRITE || rcStrict == VINF_IOM_R3_IOPORT_COMMIT_WRITE)
7179 Assert(IoExitInfo.n.u1Type == SVM_IOIO_WRITE);
7180 else
7181 {
7182 /** @todo r=bird: This is missing a bunch of VINF_EM_FIRST..VINF_EM_LAST
7183 * statuses, that the VMM device and some others may return. See
7184 * IOM_SUCCESS() for guidance. */
7185 AssertMsg( RT_FAILURE(rcStrict)
7186 || rcStrict == VINF_SUCCESS
7187 || rcStrict == VINF_EM_RAW_EMULATE_INSTR
7188 || rcStrict == VINF_EM_DBG_BREAKPOINT
7189 || rcStrict == VINF_EM_RAW_GUEST_TRAP
7190 || rcStrict == VINF_EM_RAW_TO_R3
7191 || rcStrict == VINF_TRPM_XCPT_DISPATCHED
7192 || rcStrict == VINF_EM_TRIPLE_FAULT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
7193 }
7194#endif
7195 }
7196 else
7197 {
7198 /*
7199 * Frequent exit or something needing probing. Get state and call EMHistoryExec.
7200 */
7201 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
7202 STAM_COUNTER_INC(!IoExitInfo.n.u1Str
7203 ? IoExitInfo.n.u1Type == SVM_IOIO_WRITE ? &pVCpu->hm.s.StatExitIOWrite : &pVCpu->hm.s.StatExitIORead
7204 : IoExitInfo.n.u1Type == SVM_IOIO_WRITE ? &pVCpu->hm.s.StatExitIOStringWrite : &pVCpu->hm.s.StatExitIOStringRead);
7205 Log4(("IOExit/%u: %04x:%08RX64: %s%s%s %#x LB %u -> EMHistoryExec\n",
7206 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, IoExitInfo.n.u1Rep ? "REP " : "",
7207 IoExitInfo.n.u1Type == SVM_IOIO_WRITE ? "OUT" : "IN", IoExitInfo.n.u1Str ? "S" : "", IoExitInfo.n.u16Port, uIOWidth));
7208
7209 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
7210 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
7211
7212 Log4(("IOExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
7213 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
7214 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
7215 }
7216 return VBOXSTRICTRC_TODO(rcStrict);
7217}
7218
7219
7220/**
7221 * \#VMEXIT handler for Nested Page-faults (SVM_EXIT_NPF). Conditional \#VMEXIT.
7222 */
7223HMSVM_EXIT_DECL hmR0SvmExitNestedPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7224{
7225 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7226 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
7227 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7228
7229 PVM pVM = pVCpu->CTX_SUFF(pVM);
7230 Assert(pVM->hm.s.fNestedPaging);
7231
7232 /* See AMD spec. 15.25.6 "Nested versus Guest Page Faults, Fault Ordering" for VMCB details for #NPF. */
7233 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7234 RTGCPHYS GCPhysFaultAddr = pVmcb->ctrl.u64ExitInfo2;
7235 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1; /* Note! High bits in EXITINFO1 may contain additional info and are
7236 thus intentionally not copied into u32ErrCode. */
7237
7238 Log4Func(("#NPF at CS:RIP=%04x:%#RX64 GCPhysFaultAddr=%RGp ErrCode=%#x \n", pCtx->cs.Sel, pCtx->rip, GCPhysFaultAddr,
7239 u32ErrCode));
7240
7241 /*
7242 * TPR patching for 32-bit guests, using the reserved bit in the page tables for MMIO regions.
7243 */
7244 if ( pVM->hm.s.fTprPatchingAllowed
7245 && !CPUMIsGuestInSvmNestedHwVirtMode(pCtx)
7246 && (GCPhysFaultAddr & PAGE_OFFSET_MASK) == XAPIC_OFF_TPR
7247 && ( !(u32ErrCode & X86_TRAP_PF_P) /* Not present */
7248 || (u32ErrCode & (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) == (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) /* MMIO page. */
7249 && !CPUMIsGuestInLongModeEx(pCtx)
7250 && !CPUMGetGuestCPL(pVCpu)
7251 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
7252 {
7253 RTGCPHYS GCPhysApicBase = APICGetBaseMsrNoCheck(pVCpu);
7254 GCPhysApicBase &= PAGE_BASE_GC_MASK;
7255
7256 if (GCPhysFaultAddr == GCPhysApicBase + XAPIC_OFF_TPR)
7257 {
7258 /* Only attempt to patch the instruction once. */
7259 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
7260 if (!pPatch)
7261 return VINF_EM_HM_PATCH_TPR_INSTR;
7262 }
7263 }
7264
7265 /*
7266 * Determine the nested paging mode.
7267 */
7268 PGMMODE enmNestedPagingMode;
7269#if HC_ARCH_BITS == 32
7270 if (CPUMIsGuestInLongModeEx(pCtx))
7271 enmNestedPagingMode = PGMMODE_AMD64_NX;
7272 else
7273#endif
7274 enmNestedPagingMode = PGMGetHostMode(pVM);
7275
7276 /*
7277 * MMIO optimization using the reserved (RSVD) bit in the guest page tables for MMIO pages.
7278 */
7279 Assert((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) != X86_TRAP_PF_RSVD);
7280 if ((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) == (X86_TRAP_PF_RSVD | X86_TRAP_PF_P))
7281 {
7282 /*
7283 * If event delivery causes an MMIO #NPF, go back to instruction emulation as otherwise
7284 * injecting the original pending event would most likely cause the same MMIO #NPF.
7285 */
7286 if (pVCpu->hm.s.Event.fPending)
7287 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7288
7289 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, CPUMCTX_EXTRN_RIP
7290 | CPUMCTX_EXTRN_CS);
7291 VBOXSTRICTRC rcStrict;
7292 PCEMEXITREC pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
7293 EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_MMIO),
7294 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
7295 if (!pExitRec)
7296 {
7297
7298 rcStrict = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, enmNestedPagingMode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr,
7299 u32ErrCode);
7300
7301 /*
7302 * If we succeed, resume guest execution.
7303 *
7304 * If we fail in interpreting the instruction because we couldn't get the guest
7305 * physical address of the page containing the instruction via the guest's page
7306 * tables (we would invalidate the guest page in the host TLB), resume execution
7307 * which would cause a guest page fault to let the guest handle this weird case.
7308 *
7309 * See @bugref{6043}.
7310 */
7311 if ( rcStrict == VINF_SUCCESS
7312 || rcStrict == VERR_PAGE_TABLE_NOT_PRESENT
7313 || rcStrict == VERR_PAGE_NOT_PRESENT)
7314 {
7315 /* Successfully handled MMIO operation. */
7316 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_APIC_TPR);
7317 rcStrict = VINF_SUCCESS;
7318 }
7319 }
7320 else
7321 {
7322 /*
7323 * Frequent exit or something needing probing. Get state and call EMHistoryExec.
7324 */
7325 Assert(pCtx == &pVCpu->cpum.GstCtx);
7326 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
7327 Log4(("EptMisscfgExit/%u: %04x:%08RX64: %RGp -> EMHistoryExec\n",
7328 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, GCPhysFaultAddr));
7329
7330 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
7331 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
7332
7333 Log4(("EptMisscfgExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
7334 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
7335 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
7336 }
7337 return VBOXSTRICTRC_TODO(rcStrict);
7338 }
7339
7340 TRPMAssertXcptPF(pVCpu, GCPhysFaultAddr, u32ErrCode);
7341 int rc = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, enmNestedPagingMode, u32ErrCode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr);
7342 TRPMResetTrap(pVCpu);
7343
7344 Log4Func(("#NPF: PGMR0Trap0eHandlerNestedPaging returns %Rrc CS:RIP=%04x:%#RX64\n", rc, pCtx->cs.Sel, pCtx->rip));
7345
7346 /*
7347 * Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}.
7348 */
7349 if ( rc == VINF_SUCCESS
7350 || rc == VERR_PAGE_TABLE_NOT_PRESENT
7351 || rc == VERR_PAGE_NOT_PRESENT)
7352 {
7353 /* We've successfully synced our shadow page tables. */
7354 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
7355 rc = VINF_SUCCESS;
7356 }
7357
7358 return rc;
7359}
7360
7361
7362/**
7363 * \#VMEXIT handler for virtual interrupt (SVM_EXIT_VINTR). Conditional
7364 * \#VMEXIT.
7365 */
7366HMSVM_EXIT_DECL hmR0SvmExitVIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7367{
7368 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7369 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
7370
7371 /* Indicate that we no longer need to #VMEXIT when the guest is ready to receive NMIs, it is now ready. */
7372 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7373 hmR0SvmClearIntWindowExiting(pVCpu, pVmcb, pCtx);
7374
7375 /* Deliver the pending interrupt via hmR0SvmEvaluatePendingEvent() and resume guest execution. */
7376 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
7377 return VINF_SUCCESS;
7378}
7379
7380
7381/**
7382 * \#VMEXIT handler for task switches (SVM_EXIT_TASK_SWITCH). Conditional
7383 * \#VMEXIT.
7384 */
7385HMSVM_EXIT_DECL hmR0SvmExitTaskSwitch(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7386{
7387 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7388 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7389
7390#ifndef HMSVM_ALWAYS_TRAP_TASK_SWITCH
7391 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
7392#endif
7393
7394 /* Check if this task-switch occurred while delivering an event through the guest IDT. */
7395 if (pVCpu->hm.s.Event.fPending) /* Can happen with exceptions/NMI. See @bugref{8411}. */
7396 {
7397 /*
7398 * AMD-V provides us with the exception which caused the TS; we collect
7399 * the information in the call to hmR0SvmCheckExitDueToEventDelivery().
7400 */
7401 Log4Func(("TS occurred during event delivery\n"));
7402 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
7403 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7404 }
7405
7406 /** @todo Emulate task switch someday, currently just going back to ring-3 for
7407 * emulation. */
7408 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
7409 return VERR_EM_INTERPRETER;
7410}
7411
7412
7413/**
7414 * \#VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional \#VMEXIT.
7415 */
7416HMSVM_EXIT_DECL hmR0SvmExitVmmCall(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7417{
7418 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7419 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
7420
7421 if (pVCpu->CTX_SUFF(pVM)->hm.s.fTprPatchingAllowed)
7422 {
7423 int rc = hmSvmEmulateMovTpr(pVCpu, pCtx);
7424 if (rc != VERR_NOT_FOUND)
7425 {
7426 Log4Func(("hmSvmEmulateMovTpr returns %Rrc\n", rc));
7427 return rc;
7428 }
7429 }
7430
7431 if (EMAreHypercallInstructionsEnabled(pVCpu))
7432 {
7433 VBOXSTRICTRC rcStrict = GIMHypercall(pVCpu, pCtx);
7434 if (RT_SUCCESS(rcStrict))
7435 {
7436 /* Only update the RIP if we're continuing guest execution and not in the case
7437 of say VINF_GIM_R3_HYPERCALL. */
7438 if (rcStrict == VINF_SUCCESS)
7439 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3 /* cbInstr */);
7440
7441 return VBOXSTRICTRC_VAL(rcStrict);
7442 }
7443 else
7444 Log4Func(("GIMHypercall returns %Rrc -> #UD\n", VBOXSTRICTRC_VAL(rcStrict)));
7445 }
7446
7447 hmR0SvmSetPendingXcptUD(pVCpu);
7448 return VINF_SUCCESS;
7449}
7450
7451
7452/**
7453 * \#VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional \#VMEXIT.
7454 */
7455HMSVM_EXIT_DECL hmR0SvmExitPause(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7456{
7457 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7458 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
7459 /** @todo The guest has likely hit a contended spinlock. We might want to
7460 * poke a schedule different guest VCPU. */
7461 return VINF_EM_RAW_INTERRUPT;
7462}
7463
7464
7465/**
7466 * \#VMEXIT handler for FERR intercept (SVM_EXIT_FERR_FREEZE). Conditional
7467 * \#VMEXIT.
7468 */
7469HMSVM_EXIT_DECL hmR0SvmExitFerrFreeze(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7470{
7471 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7472 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, CPUMCTX_EXTRN_CR0);
7473 Assert(!(pCtx->cr0 & X86_CR0_NE));
7474
7475 Log4Func(("Raising IRQ 13 in response to #FERR\n"));
7476 return PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13 /* u8Irq */, 1 /* u8Level */, 0 /* uTagSrc */);
7477}
7478
7479
7480/**
7481 * \#VMEXIT handler for IRET (SVM_EXIT_IRET). Conditional \#VMEXIT.
7482 */
7483HMSVM_EXIT_DECL hmR0SvmExitIret(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7484{
7485 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7486
7487 /* Clear NMI blocking. */
7488 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
7489 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
7490
7491 /* Indicate that we no longer need to #VMEXIT when the guest is ready to receive NMIs, it is now ready. */
7492 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7493 hmR0SvmClearCtrlIntercept(pVCpu, pCtx, pVmcb, SVM_CTRL_INTERCEPT_IRET);
7494
7495 /* Deliver the pending NMI via hmR0SvmEvaluatePendingEvent() and resume guest execution. */
7496 return VINF_SUCCESS;
7497}
7498
7499
7500/**
7501 * \#VMEXIT handler for page-fault exceptions (SVM_EXIT_XCPT_14).
7502 * Conditional \#VMEXIT.
7503 */
7504HMSVM_EXIT_DECL hmR0SvmExitXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7505{
7506 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7507 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
7508 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7509
7510 /* See AMD spec. 15.12.15 "#PF (Page Fault)". */
7511 PVM pVM = pVCpu->CTX_SUFF(pVM);
7512 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7513 uint32_t uErrCode = pVmcb->ctrl.u64ExitInfo1;
7514 uint64_t const uFaultAddress = pVmcb->ctrl.u64ExitInfo2;
7515
7516#if defined(HMSVM_ALWAYS_TRAP_ALL_XCPTS) || defined(HMSVM_ALWAYS_TRAP_PF)
7517 if (pVM->hm.s.fNestedPaging)
7518 {
7519 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
7520 if ( !pSvmTransient->fVectoringDoublePF
7521 || CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
7522 {
7523 /* A genuine guest #PF, reflect it to the guest. */
7524 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, uErrCode, uFaultAddress);
7525 Log4Func(("#PF: Guest page fault at %04X:%RGv FaultAddr=%RX64 ErrCode=%#x\n", pCtx->cs.Sel, (RTGCPTR)pCtx->rip,
7526 uFaultAddress, uErrCode));
7527 }
7528 else
7529 {
7530 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
7531 hmR0SvmSetPendingXcptDF(pVCpu);
7532 Log4Func(("Pending #DF due to vectoring #PF. NP\n"));
7533 }
7534 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
7535 return VINF_SUCCESS;
7536 }
7537#endif
7538
7539 Assert(!pVM->hm.s.fNestedPaging);
7540
7541 /*
7542 * TPR patching shortcut for APIC TPR reads and writes; only applicable to 32-bit guests.
7543 */
7544 if ( pVM->hm.s.fTprPatchingAllowed
7545 && (uFaultAddress & 0xfff) == XAPIC_OFF_TPR
7546 && !(uErrCode & X86_TRAP_PF_P) /* Not present. */
7547 && !CPUMIsGuestInSvmNestedHwVirtMode(pCtx)
7548 && !CPUMIsGuestInLongModeEx(pCtx)
7549 && !CPUMGetGuestCPL(pVCpu)
7550 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
7551 {
7552 RTGCPHYS GCPhysApicBase;
7553 GCPhysApicBase = APICGetBaseMsrNoCheck(pVCpu);
7554 GCPhysApicBase &= PAGE_BASE_GC_MASK;
7555
7556 /* Check if the page at the fault-address is the APIC base. */
7557 RTGCPHYS GCPhysPage;
7558 int rc2 = PGMGstGetPage(pVCpu, (RTGCPTR)uFaultAddress, NULL /* pfFlags */, &GCPhysPage);
7559 if ( rc2 == VINF_SUCCESS
7560 && GCPhysPage == GCPhysApicBase)
7561 {
7562 /* Only attempt to patch the instruction once. */
7563 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
7564 if (!pPatch)
7565 return VINF_EM_HM_PATCH_TPR_INSTR;
7566 }
7567 }
7568
7569 Log4Func(("#PF: uFaultAddress=%#RX64 CS:RIP=%#04x:%#RX64 uErrCode %#RX32 cr3=%#RX64\n", uFaultAddress, pCtx->cs.Sel,
7570 pCtx->rip, uErrCode, pCtx->cr3));
7571
7572 /*
7573 * If it's a vectoring #PF, emulate injecting the original event injection as
7574 * PGMTrap0eHandler() is incapable of differentiating between instruction emulation and
7575 * event injection that caused a #PF. See @bugref{6607}.
7576 */
7577 if (pSvmTransient->fVectoringPF)
7578 {
7579 Assert(pVCpu->hm.s.Event.fPending);
7580 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7581 }
7582
7583 TRPMAssertXcptPF(pVCpu, uFaultAddress, uErrCode);
7584 int rc = PGMTrap0eHandler(pVCpu, uErrCode, CPUMCTX2CORE(pCtx), (RTGCPTR)uFaultAddress);
7585
7586 Log4Func(("#PF: rc=%Rrc\n", rc));
7587
7588 if (rc == VINF_SUCCESS)
7589 {
7590 /* Successfully synced shadow pages tables or emulated an MMIO instruction. */
7591 TRPMResetTrap(pVCpu);
7592 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
7593 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
7594 return rc;
7595 }
7596
7597 if (rc == VINF_EM_RAW_GUEST_TRAP)
7598 {
7599 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
7600
7601 /*
7602 * If a nested-guest delivers a #PF and that causes a #PF which is -not- a shadow #PF,
7603 * we should simply forward the #PF to the guest and is up to the nested-hypervisor to
7604 * determine whether it is a nested-shadow #PF or a #DF, see @bugref{7243#c121}.
7605 */
7606 if ( !pSvmTransient->fVectoringDoublePF
7607 || CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
7608 {
7609 /* It's a guest (or nested-guest) page fault and needs to be reflected. */
7610 uErrCode = TRPMGetErrorCode(pVCpu); /* The error code might have been changed. */
7611 TRPMResetTrap(pVCpu);
7612
7613#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
7614 /* If the nested-guest is intercepting #PFs, cause a #PF #VMEXIT. */
7615 if ( CPUMIsGuestInSvmNestedHwVirtMode(pCtx)
7616 && HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_PF))
7617 return VBOXSTRICTRC_TODO(IEMExecSvmVmexit(pVCpu, SVM_EXIT_XCPT_PF, uErrCode, uFaultAddress));
7618#endif
7619
7620 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, uErrCode, uFaultAddress);
7621 }
7622 else
7623 {
7624 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
7625 TRPMResetTrap(pVCpu);
7626 hmR0SvmSetPendingXcptDF(pVCpu);
7627 Log4Func(("#PF: Pending #DF due to vectoring #PF\n"));
7628 }
7629
7630 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
7631 return VINF_SUCCESS;
7632 }
7633
7634 TRPMResetTrap(pVCpu);
7635 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
7636 return rc;
7637}
7638
7639
7640/**
7641 * \#VMEXIT handler for undefined opcode (SVM_EXIT_XCPT_6).
7642 * Conditional \#VMEXIT.
7643 */
7644HMSVM_EXIT_DECL hmR0SvmExitXcptUD(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7645{
7646 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7647 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
7648
7649 /* Paranoia; Ensure we cannot be called as a result of event delivery. */
7650 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
7651 Assert(!pVmcb->ctrl.ExitIntInfo.n.u1Valid); NOREF(pVmcb);
7652
7653 int rc = VERR_SVM_UNEXPECTED_XCPT_EXIT;
7654 if (pVCpu->hm.s.fGIMTrapXcptUD)
7655 {
7656 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
7657 uint8_t cbInstr = 0;
7658 VBOXSTRICTRC rcStrict = GIMXcptUD(pVCpu, pCtx, NULL /* pDis */, &cbInstr);
7659 if (rcStrict == VINF_SUCCESS)
7660 {
7661 /* #UD #VMEXIT does not have valid NRIP information, manually advance RIP. See @bugref{7270#c170}. */
7662 hmR0SvmAdvanceRipDumb(pVCpu, pCtx, cbInstr);
7663 rc = VINF_SUCCESS;
7664 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
7665 }
7666 else if (rcStrict == VINF_GIM_HYPERCALL_CONTINUING)
7667 rc = VINF_SUCCESS;
7668 else if (rcStrict == VINF_GIM_R3_HYPERCALL)
7669 rc = VINF_GIM_R3_HYPERCALL;
7670 else
7671 Assert(RT_FAILURE(VBOXSTRICTRC_VAL(rcStrict)));
7672 }
7673
7674 /* If the GIM #UD exception handler didn't succeed for some reason or wasn't needed, raise #UD. */
7675 if (RT_FAILURE(rc))
7676 {
7677 hmR0SvmSetPendingXcptUD(pVCpu);
7678 rc = VINF_SUCCESS;
7679 }
7680
7681 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD);
7682 return rc;
7683}
7684
7685
7686/**
7687 * \#VMEXIT handler for math-fault exceptions (SVM_EXIT_XCPT_16).
7688 * Conditional \#VMEXIT.
7689 */
7690HMSVM_EXIT_DECL hmR0SvmExitXcptMF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7691{
7692 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7693 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
7694
7695 /* Paranoia; Ensure we cannot be called as a result of event delivery. */
7696 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7697 Assert(!pVmcb->ctrl.ExitIntInfo.n.u1Valid); NOREF(pVmcb);
7698
7699 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
7700
7701 if (!(pCtx->cr0 & X86_CR0_NE))
7702 {
7703 PVM pVM = pVCpu->CTX_SUFF(pVM);
7704 PDISSTATE pDis = &pVCpu->hm.s.DisState;
7705 unsigned cbOp;
7706 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
7707 if (RT_SUCCESS(rc))
7708 {
7709 /* Convert a #MF into a FERR -> IRQ 13. See @bugref{6117}. */
7710 rc = PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13 /* u8Irq */, 1 /* u8Level */, 0 /* uTagSrc */);
7711 if (RT_SUCCESS(rc))
7712 pCtx->rip += cbOp;
7713 }
7714 else
7715 Log4Func(("EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
7716 return rc;
7717 }
7718
7719 hmR0SvmSetPendingXcptMF(pVCpu);
7720 return VINF_SUCCESS;
7721}
7722
7723
7724/**
7725 * \#VMEXIT handler for debug exceptions (SVM_EXIT_XCPT_1). Conditional
7726 * \#VMEXIT.
7727 */
7728HMSVM_EXIT_DECL hmR0SvmExitXcptDB(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7729{
7730 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7731 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
7732 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7733
7734 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
7735 {
7736 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingInterpret);
7737 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7738 }
7739
7740 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
7741
7742 /*
7743 * This can be a fault-type #DB (instruction breakpoint) or a trap-type #DB (data
7744 * breakpoint). However, for both cases DR6 and DR7 are updated to what the exception
7745 * handler expects. See AMD spec. 15.12.2 "#DB (Debug)".
7746 */
7747 PVM pVM = pVCpu->CTX_SUFF(pVM);
7748 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
7749 int rc = DBGFRZTrap01Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx), pVmcb->guest.u64DR6, pVCpu->hm.s.fSingleInstruction);
7750 if (rc == VINF_EM_RAW_GUEST_TRAP)
7751 {
7752 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> guest trap\n", pVmcb->guest.u64DR6));
7753 if (CPUMIsHyperDebugStateActive(pVCpu))
7754 CPUMSetGuestDR6(pVCpu, CPUMGetGuestDR6(pVCpu) | pVmcb->guest.u64DR6);
7755
7756 /* Reflect the exception back to the guest. */
7757 hmR0SvmSetPendingXcptDB(pVCpu);
7758 rc = VINF_SUCCESS;
7759 }
7760
7761 /*
7762 * Update DR6.
7763 */
7764 if (CPUMIsHyperDebugStateActive(pVCpu))
7765 {
7766 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> %Rrc\n", pVmcb->guest.u64DR6, rc));
7767 pVmcb->guest.u64DR6 = X86_DR6_INIT_VAL;
7768 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
7769 }
7770 else
7771 {
7772 AssertMsg(rc == VINF_SUCCESS, ("rc=%Rrc\n", rc));
7773 Assert(!pVCpu->hm.s.fSingleInstruction && !DBGFIsStepping(pVCpu));
7774 }
7775
7776 return rc;
7777}
7778
7779
7780/**
7781 * \#VMEXIT handler for alignment check exceptions (SVM_EXIT_XCPT_17).
7782 * Conditional \#VMEXIT.
7783 */
7784HMSVM_EXIT_DECL hmR0SvmExitXcptAC(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7785{
7786 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7787 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7788
7789 SVMEVENT Event;
7790 Event.u = 0;
7791 Event.n.u1Valid = 1;
7792 Event.n.u3Type = SVM_EVENT_EXCEPTION;
7793 Event.n.u8Vector = X86_XCPT_AC;
7794 Event.n.u1ErrorCodeValid = 1;
7795 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
7796 return VINF_SUCCESS;
7797}
7798
7799
7800/**
7801 * \#VMEXIT handler for breakpoint exceptions (SVM_EXIT_XCPT_3).
7802 * Conditional \#VMEXIT.
7803 */
7804HMSVM_EXIT_DECL hmR0SvmExitXcptBP(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7805{
7806 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7807 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, HMSVM_CPUMCTX_EXTRN_ALL);
7808 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7809
7810 int rc = DBGFRZTrap03Handler(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
7811 if (rc == VINF_EM_RAW_GUEST_TRAP)
7812 {
7813 SVMEVENT Event;
7814 Event.u = 0;
7815 Event.n.u1Valid = 1;
7816 Event.n.u3Type = SVM_EVENT_EXCEPTION;
7817 Event.n.u8Vector = X86_XCPT_BP;
7818 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
7819 }
7820
7821 Assert(rc == VINF_SUCCESS || rc == VINF_EM_RAW_GUEST_TRAP || rc == VINF_EM_DBG_BREAKPOINT);
7822 return rc;
7823}
7824
7825
7826#if defined(HMSVM_ALWAYS_TRAP_ALL_XCPTS) || defined(VBOX_WITH_NESTED_HWVIRT_SVM)
7827/**
7828 * \#VMEXIT handler for generic exceptions. Conditional \#VMEXIT.
7829 */
7830HMSVM_EXIT_DECL hmR0SvmExitXcptGeneric(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7831{
7832 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7833 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7834
7835 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7836 uint8_t const uVector = pVmcb->ctrl.u64ExitCode - SVM_EXIT_XCPT_0;
7837 uint32_t const uErrCode = pVmcb->ctrl.u64ExitInfo1;
7838 Assert(pSvmTransient->u64ExitCode == pVmcb->ctrl.u64ExitCode);
7839 Assert(uVector <= X86_XCPT_LAST);
7840 Log4Func(("uVector=%#x uErrCode=%u\n", uVector, uErrCode));
7841
7842 SVMEVENT Event;
7843 Event.u = 0;
7844 Event.n.u1Valid = 1;
7845 Event.n.u3Type = SVM_EVENT_EXCEPTION;
7846 Event.n.u8Vector = uVector;
7847 switch (uVector)
7848 {
7849 /* Shouldn't be here for reflecting #PFs (among other things, the fault address isn't passed along). */
7850 case X86_XCPT_PF: AssertMsgFailed(("hmR0SvmExitXcptGeneric: Unexpected exception")); return VERR_SVM_IPE_5;
7851 case X86_XCPT_DF:
7852 case X86_XCPT_TS:
7853 case X86_XCPT_NP:
7854 case X86_XCPT_SS:
7855 case X86_XCPT_GP:
7856 case X86_XCPT_AC:
7857 {
7858 Event.n.u1ErrorCodeValid = 1;
7859 Event.n.u32ErrorCode = uErrCode;
7860 break;
7861 }
7862 }
7863
7864 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
7865 return VINF_SUCCESS;
7866}
7867#endif
7868
7869#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
7870/**
7871 * \#VMEXIT handler for CLGI (SVM_EXIT_CLGI). Conditional \#VMEXIT.
7872 */
7873HMSVM_EXIT_DECL hmR0SvmExitClgi(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7874{
7875 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7876 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, IEM_CPUMCTX_EXTRN_MUST_MASK
7877 | CPUMCTX_EXTRN_HWVIRT);
7878
7879#ifdef VBOX_STRICT
7880 PCSVMVMCB pVmcbTmp = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7881 Assert(pVmcbTmp);
7882 Assert(!pVmcbTmp->ctrl.IntCtrl.n.u1VGifEnable);
7883 RT_NOREF(pVmcbTmp);
7884#endif
7885
7886 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7887 VBOXSTRICTRC rcStrict = IEMExecDecodedClgi(pVCpu, cbInstr);
7888 if (rcStrict == VINF_SUCCESS)
7889 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_HWVIRT);
7890 return VBOXSTRICTRC_VAL(rcStrict);
7891}
7892
7893
7894/**
7895 * \#VMEXIT handler for STGI (SVM_EXIT_STGI). Conditional \#VMEXIT.
7896 */
7897HMSVM_EXIT_DECL hmR0SvmExitStgi(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7898{
7899 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7900 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, IEM_CPUMCTX_EXTRN_MUST_MASK
7901 | CPUMCTX_EXTRN_HWVIRT);
7902
7903 /*
7904 * When VGIF is not used we always intercept STGI instructions. When VGIF is used,
7905 * we only intercept STGI when events are pending for GIF to become 1.
7906 */
7907 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7908 if (pVmcb->ctrl.IntCtrl.n.u1VGifEnable)
7909 hmR0SvmClearCtrlIntercept(pVCpu, pCtx, pVmcb, SVM_CTRL_INTERCEPT_STGI);
7910
7911 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7912 VBOXSTRICTRC rcStrict = IEMExecDecodedStgi(pVCpu, cbInstr);
7913 if (rcStrict == VINF_SUCCESS)
7914 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_HWVIRT);
7915 return VBOXSTRICTRC_VAL(rcStrict);
7916}
7917
7918
7919/**
7920 * \#VMEXIT handler for VMLOAD (SVM_EXIT_VMLOAD). Conditional \#VMEXIT.
7921 */
7922HMSVM_EXIT_DECL hmR0SvmExitVmload(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7923{
7924 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7925 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, IEM_CPUMCTX_EXTRN_MUST_MASK
7926 | CPUMCTX_EXTRN_FS
7927 | CPUMCTX_EXTRN_GS
7928 | CPUMCTX_EXTRN_TR
7929 | CPUMCTX_EXTRN_LDTR
7930 | CPUMCTX_EXTRN_KERNEL_GS_BASE
7931 | CPUMCTX_EXTRN_SYSCALL_MSRS
7932 | CPUMCTX_EXTRN_SYSENTER_MSRS);
7933
7934#ifdef VBOX_STRICT
7935 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7936 Assert(pVmcb);
7937 Assert(!pVmcb->ctrl.LbrVirt.n.u1VirtVmsaveVmload);
7938 RT_NOREF(pVmcb);
7939#endif
7940
7941 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7942 VBOXSTRICTRC rcStrict = IEMExecDecodedVmload(pVCpu, cbInstr);
7943 if (rcStrict == VINF_SUCCESS)
7944 {
7945 /* We skip flagging changes made to LSTAR, STAR, SFMASK and other MSRs as they are always re-loaded. */
7946 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_FS
7947 | HM_CHANGED_GUEST_GS
7948 | HM_CHANGED_GUEST_TR
7949 | HM_CHANGED_GUEST_LDTR
7950 | HM_CHANGED_GUEST_SYSENTER_CS_MSR
7951 | HM_CHANGED_GUEST_SYSENTER_EIP_MSR
7952 | HM_CHANGED_GUEST_SYSENTER_ESP_MSR);
7953 }
7954 return VBOXSTRICTRC_VAL(rcStrict);
7955}
7956
7957
7958/**
7959 * \#VMEXIT handler for VMSAVE (SVM_EXIT_VMSAVE). Conditional \#VMEXIT.
7960 */
7961HMSVM_EXIT_DECL hmR0SvmExitVmsave(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7962{
7963 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7964 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, IEM_CPUMCTX_EXTRN_MUST_MASK);
7965
7966#ifdef VBOX_STRICT
7967 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7968 Assert(pVmcb);
7969 Assert(!pVmcb->ctrl.LbrVirt.n.u1VirtVmsaveVmload);
7970 RT_NOREF(pVmcb);
7971#endif
7972
7973 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7974 VBOXSTRICTRC rcStrict = IEMExecDecodedVmsave(pVCpu, cbInstr);
7975 return VBOXSTRICTRC_VAL(rcStrict);
7976}
7977
7978
7979/**
7980 * \#VMEXIT handler for INVLPGA (SVM_EXIT_INVLPGA). Conditional \#VMEXIT.
7981 */
7982HMSVM_EXIT_DECL hmR0SvmExitInvlpga(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7983{
7984 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7985 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, IEM_CPUMCTX_EXTRN_MUST_MASK);
7986
7987 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7988 VBOXSTRICTRC rcStrict = IEMExecDecodedInvlpga(pVCpu, cbInstr);
7989 return VBOXSTRICTRC_VAL(rcStrict);
7990}
7991
7992
7993/**
7994 * \#VMEXIT handler for STGI (SVM_EXIT_VMRUN). Conditional \#VMEXIT.
7995 */
7996HMSVM_EXIT_DECL hmR0SvmExitVmrun(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7997{
7998 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7999 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, IEM_CPUMCTX_EXTRN_MUST_MASK
8000 | IEM_CPUMCTX_EXTRN_SVM_VMRUN_MASK);
8001 VBOXSTRICTRC rcStrict;
8002 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
8003 rcStrict = IEMExecDecodedVmrun(pVCpu, cbInstr);
8004 Log4Func(("IEMExecDecodedVmrun returns %Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
8005 if (rcStrict == VINF_SUCCESS)
8006 {
8007 rcStrict = VINF_SVM_VMRUN;
8008 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_SVM_VMRUN_MASK);
8009 }
8010 return VBOXSTRICTRC_VAL(rcStrict);
8011}
8012
8013
8014/**
8015 * Nested-guest \#VMEXIT handler for debug exceptions (SVM_EXIT_XCPT_1).
8016 * Unconditional \#VMEXIT.
8017 */
8018HMSVM_EXIT_DECL hmR0SvmNestedExitXcptDB(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
8019{
8020 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
8021 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
8022
8023 if (pVCpu->hm.s.Event.fPending)
8024 {
8025 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingInterpret);
8026 return VINF_EM_RAW_INJECT_TRPM_EVENT;
8027 }
8028
8029 hmR0SvmSetPendingXcptDB(pVCpu);
8030 return VINF_SUCCESS;
8031}
8032
8033
8034/**
8035 * Nested-guest \#VMEXIT handler for breakpoint exceptions (SVM_EXIT_XCPT_3).
8036 * Conditional \#VMEXIT.
8037 */
8038HMSVM_EXIT_DECL hmR0SvmNestedExitXcptBP(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
8039{
8040 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
8041 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
8042
8043 SVMEVENT Event;
8044 Event.u = 0;
8045 Event.n.u1Valid = 1;
8046 Event.n.u3Type = SVM_EVENT_EXCEPTION;
8047 Event.n.u8Vector = X86_XCPT_BP;
8048 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
8049 return VINF_SUCCESS;
8050}
8051
8052#endif /* VBOX_WITH_NESTED_HWVIRT_SVM */
8053
8054
8055/** @} */
8056
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette