VirtualBox

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

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

VMM/HM: Clean up and also fix HMR0EnsureCompleteBasicContext for AMD-V which also selectively re-loads guest state back into the VMCB.

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