VirtualBox

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

Last change on this file since 71504 was 71504, checked in by vboxsync, 7 years ago

VMM/HMSVMR0: Avoid intercepting CR4 reads when possible. Added todo about updating nested-guest TSC offsetting.

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

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