VirtualBox

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

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

VMM/HMSVMR0: Doxygen build fix.

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

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