VirtualBox

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

最後變更 在這個檔案從80334是 80333,由 vboxsync 提交於 6 年 前

VMM: Eliminating the VBOX_BUGREF_9217_PART_I preprocessor macro. bugref:9217

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

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