VirtualBox

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

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

VMM: Nested hw.virt: Implemented saved-states for nested SVM. Bumps the CPUM and HM SSM versions.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 305.3 KB
Line 
1/* $Id: HMSVMR0.cpp 72178 2018-05-09 16:18:56Z 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 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
4121
4122#ifdef VBOX_WITH_NESTED_HWVIRT_ONLY_IN_IEM
4123 Log2(("hmR0SvmPreRunGuest: Rescheduling to IEM due to nested-hwvirt or forced IEM exec -> VINF_EM_RESCHEDULE_REM\n"));
4124 return VINF_EM_RESCHEDULE_REM;
4125#endif
4126
4127 /* Check force flag actions that might require us to go back to ring-3. */
4128 int rc = hmR0SvmCheckForceFlags(pVM, pVCpu, pCtx);
4129 if (rc != VINF_SUCCESS)
4130 return rc;
4131
4132 if (TRPMHasTrap(pVCpu))
4133 hmR0SvmTrpmTrapToPendingEvent(pVCpu);
4134 else if (!pVCpu->hm.s.Event.fPending)
4135 {
4136 VBOXSTRICTRC rcStrict = hmR0SvmEvaluatePendingEventNested(pVCpu, pCtx);
4137 if ( rcStrict != VINF_SUCCESS
4138 || !CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
4139 return VBOXSTRICTRC_VAL(rcStrict);
4140 }
4141
4142 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
4143
4144 /*
4145 * On the oldest AMD-V systems, we may not get enough information to reinject an NMI.
4146 * Just do it in software, see @bugref{8411}.
4147 * NB: If we could continue a task switch exit we wouldn't need to do this.
4148 */
4149 if (RT_UNLIKELY( !pVM->hm.s.svm.u32Features
4150 && pVCpu->hm.s.Event.fPending
4151 && SVM_EVENT_GET_TYPE(pVCpu->hm.s.Event.u64IntInfo) == SVM_EVENT_NMI))
4152 {
4153 return VINF_EM_RAW_INJECT_TRPM_EVENT;
4154 }
4155
4156#ifdef HMSVM_SYNC_FULL_NESTED_GUEST_STATE
4157 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
4158#endif
4159
4160 /*
4161 * Load the nested-guest state.
4162 */
4163 rc = hmR0SvmLoadGuestStateNested(pVCpu, pCtx);
4164 AssertRCReturn(rc, rc);
4165 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadFull); /** @todo Get new STAM counter for this? */
4166
4167 /* Ensure we've cached (and hopefully modified) the VMCB for execution using hardware-assisted SVM. */
4168 Assert(pCtx->hwvirt.svm.fHMCachedVmcb);
4169
4170 /*
4171 * No longjmps to ring-3 from this point on!!!
4172 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
4173 * This also disables flushing of the R0-logger instance (if any).
4174 */
4175 VMMRZCallRing3Disable(pVCpu);
4176
4177 /*
4178 * We disable interrupts so that we don't miss any interrupts that would flag preemption (IPI/timers etc.)
4179 * when thread-context hooks aren't used and we've been running with preemption disabled for a while.
4180 *
4181 * We need to check for force-flags that could've possible been altered since we last checked them (e.g.
4182 * by PDMGetInterrupt() leaving the PDM critical section, see @bugref{6398}).
4183 *
4184 * We also check a couple of other force-flags as a last opportunity to get the EMT back to ring-3 before
4185 * executing guest code.
4186 */
4187 pSvmTransient->fEFlags = ASMIntDisableFlags();
4188 if ( VM_FF_IS_PENDING(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
4189 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
4190 {
4191 ASMSetFlags(pSvmTransient->fEFlags);
4192 VMMRZCallRing3Enable(pVCpu);
4193 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
4194 return VINF_EM_RAW_TO_R3;
4195 }
4196 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
4197 {
4198 ASMSetFlags(pSvmTransient->fEFlags);
4199 VMMRZCallRing3Enable(pVCpu);
4200 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
4201 return VINF_EM_RAW_INTERRUPT;
4202 }
4203 return VINF_SUCCESS;
4204}
4205#endif
4206
4207
4208/**
4209 * Does the preparations before executing guest code in AMD-V.
4210 *
4211 * This may cause longjmps to ring-3 and may even result in rescheduling to the
4212 * recompiler. We must be cautious what we do here regarding committing
4213 * guest-state information into the VMCB assuming we assuredly execute the guest
4214 * in AMD-V. If we fall back to the recompiler after updating the VMCB and
4215 * clearing the common-state (TRPM/forceflags), we must undo those changes so
4216 * that the recompiler can (and should) use them when it resumes guest
4217 * execution. Otherwise such operations must be done when we can no longer
4218 * exit to ring-3.
4219 *
4220 * @returns VBox status code (informational status codes included).
4221 * @retval VINF_SUCCESS if we can proceed with running the guest.
4222 * @retval VINF_* scheduling changes, we have to go back to ring-3.
4223 *
4224 * @param pVM The cross context VM structure.
4225 * @param pVCpu The cross context virtual CPU structure.
4226 * @param pCtx Pointer to the guest-CPU context.
4227 * @param pSvmTransient Pointer to the SVM transient structure.
4228 */
4229static int hmR0SvmPreRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4230{
4231 HMSVM_ASSERT_PREEMPT_SAFE();
4232 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
4233
4234 /* Check force flag actions that might require us to go back to ring-3. */
4235 int rc = hmR0SvmCheckForceFlags(pVM, pVCpu, pCtx);
4236 if (rc != VINF_SUCCESS)
4237 return rc;
4238
4239 if (TRPMHasTrap(pVCpu))
4240 hmR0SvmTrpmTrapToPendingEvent(pVCpu);
4241 else if (!pVCpu->hm.s.Event.fPending)
4242 hmR0SvmEvaluatePendingEvent(pVCpu, pCtx);
4243
4244 /*
4245 * On the oldest AMD-V systems, we may not get enough information to reinject an NMI.
4246 * Just do it in software, see @bugref{8411}.
4247 * NB: If we could continue a task switch exit we wouldn't need to do this.
4248 */
4249 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending && (((pVCpu->hm.s.Event.u64IntInfo >> 8) & 7) == SVM_EVENT_NMI)))
4250 if (RT_UNLIKELY(!pVM->hm.s.svm.u32Features))
4251 return VINF_EM_RAW_INJECT_TRPM_EVENT;
4252
4253#ifdef HMSVM_SYNC_FULL_GUEST_STATE
4254 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
4255#endif
4256
4257 /* Load the guest bits that are not shared with the host in any way since we can longjmp or get preempted. */
4258 rc = hmR0SvmLoadGuestState(pVM, pVCpu, pCtx);
4259 AssertRCReturn(rc, rc);
4260 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadFull);
4261
4262 /*
4263 * If we're not intercepting TPR changes in the guest, save the guest TPR before the world-switch
4264 * so we can update it on the way back if the guest changed the TPR.
4265 */
4266 if (pVCpu->hm.s.svm.fSyncVTpr)
4267 {
4268 if (pVM->hm.s.fTPRPatchingActive)
4269 pSvmTransient->u8GuestTpr = pCtx->msrLSTAR;
4270 else
4271 {
4272 PCSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
4273 pSvmTransient->u8GuestTpr = pVmcb->ctrl.IntCtrl.n.u8VTPR;
4274 }
4275 }
4276
4277 /*
4278 * No longjmps to ring-3 from this point on!!!
4279 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
4280 * This also disables flushing of the R0-logger instance (if any).
4281 */
4282 VMMRZCallRing3Disable(pVCpu);
4283
4284 /*
4285 * We disable interrupts so that we don't miss any interrupts that would flag preemption (IPI/timers etc.)
4286 * when thread-context hooks aren't used and we've been running with preemption disabled for a while.
4287 *
4288 * We need to check for force-flags that could've possible been altered since we last checked them (e.g.
4289 * by PDMGetInterrupt() leaving the PDM critical section, see @bugref{6398}).
4290 *
4291 * We also check a couple of other force-flags as a last opportunity to get the EMT back to ring-3 before
4292 * executing guest code.
4293 */
4294 pSvmTransient->fEFlags = ASMIntDisableFlags();
4295 if ( VM_FF_IS_PENDING(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
4296 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
4297 {
4298 ASMSetFlags(pSvmTransient->fEFlags);
4299 VMMRZCallRing3Enable(pVCpu);
4300 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
4301 return VINF_EM_RAW_TO_R3;
4302 }
4303 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
4304 {
4305 ASMSetFlags(pSvmTransient->fEFlags);
4306 VMMRZCallRing3Enable(pVCpu);
4307 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
4308 return VINF_EM_RAW_INTERRUPT;
4309 }
4310
4311 return VINF_SUCCESS;
4312}
4313
4314
4315/**
4316 * Prepares to run guest (or nested-guest) code in AMD-V and we've committed to
4317 * doing so.
4318 *
4319 * This means there is no backing out to ring-3 or anywhere else at this point.
4320 *
4321 * @param pVCpu The cross context virtual CPU structure.
4322 * @param pCtx Pointer to the guest-CPU context.
4323 * @param pSvmTransient Pointer to the SVM transient structure.
4324 *
4325 * @remarks Called with preemption disabled.
4326 * @remarks No-long-jump zone!!!
4327 */
4328static void hmR0SvmPreRunGuestCommitted(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4329{
4330 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
4331 Assert(VMMR0IsLogFlushDisabled(pVCpu));
4332 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4333
4334 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
4335 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC); /* Indicate the start of guest execution. */
4336
4337 PVM pVM = pVCpu->CTX_SUFF(pVM);
4338 PSVMVMCB pVmcb = pSvmTransient->pVmcb;
4339
4340 hmR0SvmInjectPendingEvent(pVCpu, pCtx, pVmcb);
4341
4342 if (!CPUMIsGuestFPUStateActive(pVCpu))
4343 {
4344 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestFpuState, x);
4345 CPUMR0LoadGuestFPU(pVM, pVCpu); /* (Ignore rc, no need to set HM_CHANGED_HOST_CONTEXT for SVM.) */
4346 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestFpuState, x);
4347 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadGuestFpu);
4348 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
4349 }
4350
4351 /* Load the state shared between host and guest (FPU, debug). */
4352 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_GUEST_SHARED_STATE))
4353 hmR0SvmLoadSharedState(pVCpu, pVmcb, pCtx);
4354
4355 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_HOST_CONTEXT); /* Preemption might set this, nothing to do on AMD-V. */
4356 AssertMsg(!HMCPU_CF_VALUE(pVCpu), ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
4357
4358 PHMGLOBALCPUINFO pHostCpu = hmR0GetCurrentCpu();
4359 RTCPUID const idHostCpu = pHostCpu->idCpu;
4360 bool const fMigratedHostCpu = idHostCpu != pVCpu->hm.s.idLastCpu;
4361
4362 /* Setup TSC offsetting. */
4363 if ( pSvmTransient->fUpdateTscOffsetting
4364 || fMigratedHostCpu)
4365 {
4366 hmR0SvmUpdateTscOffsetting(pVM, pVCpu, pCtx, pVmcb);
4367 pSvmTransient->fUpdateTscOffsetting = false;
4368 }
4369
4370 /* If we've migrating CPUs, mark the VMCB Clean bits as dirty. */
4371 if (fMigratedHostCpu)
4372 pVmcb->ctrl.u32VmcbCleanBits = 0;
4373
4374 /* Store status of the shared guest-host state at the time of VMRUN. */
4375#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
4376 if (CPUMIsGuestInLongModeEx(pCtx))
4377 {
4378 pSvmTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActivePending(pVCpu);
4379 pSvmTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActivePending(pVCpu);
4380 }
4381 else
4382#endif
4383 {
4384 pSvmTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActive(pVCpu);
4385 pSvmTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActive(pVCpu);
4386 }
4387
4388 uint8_t *pbMsrBitmap;
4389 if (!pSvmTransient->fIsNestedGuest)
4390 pbMsrBitmap = (uint8_t *)pVCpu->hm.s.svm.pvMsrBitmap;
4391 else
4392 {
4393 hmR0SvmMergeMsrpmNested(pHostCpu, pVCpu, pCtx);
4394
4395 /* Update the nested-guest VMCB with the newly merged MSRPM (clean bits updated below). */
4396 pVmcb->ctrl.u64MSRPMPhysAddr = pHostCpu->n.svm.HCPhysNstGstMsrpm;
4397 pbMsrBitmap = (uint8_t *)pHostCpu->n.svm.pvNstGstMsrpm;
4398 }
4399
4400 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB flushing, set this across the world switch. */
4401 /* Flush the appropriate tagged-TLB entries. */
4402 hmR0SvmFlushTaggedTlb(pVCpu, pCtx, pVmcb, pHostCpu);
4403 Assert(pVCpu->hm.s.idLastCpu == idHostCpu);
4404
4405 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
4406
4407 TMNotifyStartOfExecution(pVCpu); /* Finally, notify TM to resume its clocks as we're about
4408 to start executing. */
4409
4410 /*
4411 * Save the current Host TSC_AUX and write the guest TSC_AUX to the host, so that
4412 * RDTSCPs (that don't cause exits) reads the guest MSR. See @bugref{3324}.
4413 *
4414 * This should be done -after- any RDTSCPs for obtaining the host timestamp (TM, STAM etc).
4415 */
4416 if ( (pVM->hm.s.cpuid.u32AMDFeatureEDX & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
4417 && !(pVmcb->ctrl.u64InterceptCtrl & SVM_CTRL_INTERCEPT_RDTSCP))
4418 {
4419 uint64_t const uGuestTscAux = CPUMR0GetGuestTscAux(pVCpu);
4420 pVCpu->hm.s.u64HostTscAux = ASMRdMsr(MSR_K8_TSC_AUX);
4421 if (uGuestTscAux != pVCpu->hm.s.u64HostTscAux)
4422 ASMWrMsr(MSR_K8_TSC_AUX, uGuestTscAux);
4423 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_TSC_AUX, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
4424 pSvmTransient->fRestoreTscAuxMsr = true;
4425 }
4426 else
4427 {
4428 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_TSC_AUX, SVMMSREXIT_INTERCEPT_READ, SVMMSREXIT_INTERCEPT_WRITE);
4429 pSvmTransient->fRestoreTscAuxMsr = false;
4430 }
4431 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_IOPM_MSRPM;
4432
4433 /*
4434 * If VMCB Clean bits isn't supported by the CPU or exposed to the guest in the
4435 * nested virtualization case, mark all state-bits as dirty indicating to the
4436 * CPU to re-load from VMCB.
4437 */
4438 bool const fSupportsVmcbCleanBits = hmR0SvmSupportsVmcbCleanBits(pVCpu, pCtx);
4439 if (!fSupportsVmcbCleanBits)
4440 pVmcb->ctrl.u32VmcbCleanBits = 0;
4441}
4442
4443
4444/**
4445 * Wrapper for running the guest code in AMD-V.
4446 *
4447 * @returns VBox strict status code.
4448 * @param pVM The cross context VM structure.
4449 * @param pVCpu The cross context virtual CPU structure.
4450 * @param pCtx Pointer to the guest-CPU context.
4451 *
4452 * @remarks No-long-jump zone!!!
4453 */
4454DECLINLINE(int) hmR0SvmRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4455{
4456 /*
4457 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses floating-point operations
4458 * using SSE instructions. Some XMM registers (XMM6-XMM15) are callee-saved and thus the need for this XMM wrapper.
4459 * Refer MSDN docs. "Configuring Programs for 64-bit / x64 Software Conventions / Register Usage" for details.
4460 */
4461#ifdef VBOX_WITH_KERNEL_USING_XMM
4462 return hmR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
4463 pVCpu->hm.s.svm.pfnVMRun);
4464#else
4465 return pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
4466#endif
4467}
4468
4469
4470#ifdef VBOX_WITH_NESTED_HWVIRT
4471/**
4472 * Undoes the TSC offset applied for an SVM nested-guest and returns the TSC
4473 * value for the guest.
4474 *
4475 * @returns The TSC offset after undoing any nested-guest TSC offset.
4476 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
4477 * @param uTicks The nested-guest TSC.
4478 *
4479 * @note If you make any changes to this function, please check if
4480 * hmR0SvmNstGstUndoTscOffset() needs adjusting.
4481 *
4482 * @sa HMSvmNstGstApplyTscOffset().
4483 */
4484DECLINLINE(uint64_t) hmR0SvmNstGstUndoTscOffset(PVMCPU pVCpu, PCPUMCTX pCtx, uint64_t uTicks)
4485{
4486 Assert(pCtx->hwvirt.svm.fHMCachedVmcb); RT_NOREF(pCtx);
4487 PCSVMNESTEDVMCBCACHE pVmcbNstGstCache = &pVCpu->hm.s.svm.NstGstVmcbCache;
4488 return uTicks - pVmcbNstGstCache->u64TSCOffset;
4489}
4490
4491
4492/**
4493 * Wrapper for running the nested-guest code in AMD-V.
4494 *
4495 * @returns VBox strict status code.
4496 * @param pVM The cross context VM structure.
4497 * @param pVCpu The cross context virtual CPU structure.
4498 * @param pCtx Pointer to the guest-CPU context.
4499 *
4500 * @remarks No-long-jump zone!!!
4501 */
4502DECLINLINE(int) hmR0SvmRunGuestNested(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4503{
4504 /*
4505 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses floating-point operations
4506 * using SSE instructions. Some XMM registers (XMM6-XMM15) are callee-saved and thus the need for this XMM wrapper.
4507 * Refer MSDN docs. "Configuring Programs for 64-bit / x64 Software Conventions / Register Usage" for details.
4508 */
4509#ifdef VBOX_WITH_KERNEL_USING_XMM
4510 return hmR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pCtx->hwvirt.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
4511 pVCpu->hm.s.svm.pfnVMRun);
4512#else
4513 return pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pCtx->hwvirt.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
4514#endif
4515}
4516#endif
4517
4518/**
4519 * Performs some essential restoration of state after running guest (or
4520 * nested-guest) code in AMD-V.
4521 *
4522 * @param pVCpu The cross context virtual CPU structure.
4523 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
4524 * out-of-sync. Make sure to update the required fields
4525 * before using them.
4526 * @param pSvmTransient Pointer to the SVM transient structure.
4527 * @param rcVMRun Return code of VMRUN.
4528 *
4529 * @remarks Called with interrupts disabled.
4530 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
4531 * unconditionally when it is safe to do so.
4532 */
4533static void hmR0SvmPostRunGuest(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PSVMTRANSIENT pSvmTransient, int rcVMRun)
4534{
4535 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
4536
4537 uint64_t const uHostTsc = ASMReadTSC(); /* Read the TSC as soon as possible. */
4538 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB flushing. */
4539 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for EMT poking. */
4540
4541 PSVMVMCB pVmcb = pSvmTransient->pVmcb;
4542 PSVMVMCBCTRL pVmcbCtrl = &pVmcb->ctrl;
4543
4544 /* TSC read must be done early for maximum accuracy. */
4545 if (!(pVmcbCtrl->u64InterceptCtrl & SVM_CTRL_INTERCEPT_RDTSC))
4546 {
4547 if (!pSvmTransient->fIsNestedGuest)
4548 TMCpuTickSetLastSeen(pVCpu, uHostTsc + pVmcbCtrl->u64TSCOffset);
4549 else
4550 {
4551 /* The nested-guest VMCB TSC offset shall eventually be restored on #VMEXIT via HMSvmNstGstVmExitNotify(). */
4552 uint64_t const uGstTsc = hmR0SvmNstGstUndoTscOffset(pVCpu, pMixedCtx, uHostTsc + pVmcbCtrl->u64TSCOffset);
4553 TMCpuTickSetLastSeen(pVCpu, uGstTsc);
4554 }
4555 }
4556
4557 if (pSvmTransient->fRestoreTscAuxMsr)
4558 {
4559 uint64_t u64GuestTscAuxMsr = ASMRdMsr(MSR_K8_TSC_AUX);
4560 CPUMR0SetGuestTscAux(pVCpu, u64GuestTscAuxMsr);
4561 if (u64GuestTscAuxMsr != pVCpu->hm.s.u64HostTscAux)
4562 ASMWrMsr(MSR_K8_TSC_AUX, pVCpu->hm.s.u64HostTscAux);
4563 }
4564
4565 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatExit1, x);
4566 TMNotifyEndOfExecution(pVCpu); /* Notify TM that the guest is no longer running. */
4567 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
4568
4569 Assert(!(ASMGetFlags() & X86_EFL_IF));
4570 ASMSetFlags(pSvmTransient->fEFlags); /* Enable interrupts. */
4571 VMMRZCallRing3Enable(pVCpu); /* It is now safe to do longjmps to ring-3!!! */
4572
4573 /* If VMRUN failed, we can bail out early. This does -not- cover SVM_EXIT_INVALID. */
4574 if (RT_UNLIKELY(rcVMRun != VINF_SUCCESS))
4575 {
4576 Log4(("VMRUN failure: rcVMRun=%Rrc\n", rcVMRun));
4577 return;
4578 }
4579
4580 pSvmTransient->u64ExitCode = pVmcbCtrl->u64ExitCode; /* Save the #VMEXIT reason. */
4581 HMCPU_EXIT_HISTORY_ADD(pVCpu, pVmcbCtrl->u64ExitCode); /* Update the #VMEXIT history array. */
4582 pVmcbCtrl->u32VmcbCleanBits = HMSVM_VMCB_CLEAN_ALL; /* Mark the VMCB-state cache as unmodified by VMM. */
4583 pSvmTransient->fVectoringDoublePF = false; /* Vectoring double page-fault needs to be determined later. */
4584 pSvmTransient->fVectoringPF = false; /* Vectoring page-fault needs to be determined later. */
4585
4586 hmR0SvmSaveGuestState(pVCpu, pMixedCtx, pVmcb); /* Save the guest state from the VMCB to the guest-CPU context. */
4587
4588 if ( pSvmTransient->u64ExitCode != SVM_EXIT_INVALID
4589 && pVCpu->hm.s.svm.fSyncVTpr)
4590 {
4591 Assert(!pSvmTransient->fIsNestedGuest);
4592 /* TPR patching (for 32-bit guests) uses LSTAR MSR for holding the TPR value, otherwise uses the VTPR. */
4593 if ( pVCpu->CTX_SUFF(pVM)->hm.s.fTPRPatchingActive
4594 && (pMixedCtx->msrLSTAR & 0xff) != pSvmTransient->u8GuestTpr)
4595 {
4596 int rc = APICSetTpr(pVCpu, pMixedCtx->msrLSTAR & 0xff);
4597 AssertRC(rc);
4598 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
4599 }
4600 /* Sync TPR when we aren't intercepting CR8 writes. */
4601 else if (pSvmTransient->u8GuestTpr != pVmcbCtrl->IntCtrl.n.u8VTPR)
4602 {
4603 int rc = APICSetTpr(pVCpu, pVmcbCtrl->IntCtrl.n.u8VTPR << 4);
4604 AssertRC(rc);
4605 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
4606 }
4607 }
4608}
4609
4610
4611/**
4612 * Runs the guest code using AMD-V.
4613 *
4614 * @returns VBox status code.
4615 * @param pVM The cross context VM structure.
4616 * @param pVCpu The cross context virtual CPU structure.
4617 * @param pCtx Pointer to the guest-CPU context.
4618 * @param pcLoops Pointer to the number of executed loops.
4619 */
4620static int hmR0SvmRunGuestCodeNormal(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t *pcLoops)
4621{
4622 uint32_t const cMaxResumeLoops = pVM->hm.s.cMaxResumeLoops;
4623 Assert(pcLoops);
4624 Assert(*pcLoops <= cMaxResumeLoops);
4625
4626 SVMTRANSIENT SvmTransient;
4627 RT_ZERO(SvmTransient);
4628 SvmTransient.fUpdateTscOffsetting = true;
4629 SvmTransient.pVmcb = pVCpu->hm.s.svm.pVmcb;
4630
4631 int rc = VERR_INTERNAL_ERROR_5;
4632 for (;;)
4633 {
4634 Assert(!HMR0SuspendPending());
4635 HMSVM_ASSERT_CPU_SAFE();
4636
4637 /* Preparatory work for running guest code, this may force us to return
4638 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
4639 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
4640 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
4641 if (rc != VINF_SUCCESS)
4642 break;
4643
4644 /*
4645 * No longjmps to ring-3 from this point on!!!
4646 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
4647 * This also disables flushing of the R0-logger instance (if any).
4648 */
4649 hmR0SvmPreRunGuestCommitted(pVCpu, pCtx, &SvmTransient);
4650 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
4651
4652 /* Restore any residual host-state and save any bits shared between host
4653 and guest into the guest-CPU state. Re-enables interrupts! */
4654 hmR0SvmPostRunGuest(pVCpu, pCtx, &SvmTransient, rc);
4655
4656 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
4657 || SvmTransient.u64ExitCode == SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
4658 {
4659 if (rc == VINF_SUCCESS)
4660 rc = VERR_SVM_INVALID_GUEST_STATE;
4661 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
4662 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
4663 break;
4664 }
4665
4666 /* Handle the #VMEXIT. */
4667 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
4668 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
4669 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, pVCpu->hm.s.svm.pVmcb);
4670 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
4671 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
4672 if (rc != VINF_SUCCESS)
4673 break;
4674 if (++(*pcLoops) >= cMaxResumeLoops)
4675 {
4676 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
4677 rc = VINF_EM_RAW_INTERRUPT;
4678 break;
4679 }
4680 }
4681
4682 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
4683 return rc;
4684}
4685
4686
4687/**
4688 * Runs the guest code using AMD-V in single step mode.
4689 *
4690 * @returns VBox status code.
4691 * @param pVM The cross context VM structure.
4692 * @param pVCpu The cross context virtual CPU structure.
4693 * @param pCtx Pointer to the guest-CPU context.
4694 * @param pcLoops Pointer to the number of executed loops.
4695 */
4696static int hmR0SvmRunGuestCodeStep(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t *pcLoops)
4697{
4698 uint32_t const cMaxResumeLoops = pVM->hm.s.cMaxResumeLoops;
4699 Assert(pcLoops);
4700 Assert(*pcLoops <= cMaxResumeLoops);
4701
4702 SVMTRANSIENT SvmTransient;
4703 RT_ZERO(SvmTransient);
4704 SvmTransient.fUpdateTscOffsetting = true;
4705 SvmTransient.pVmcb = pVCpu->hm.s.svm.pVmcb;
4706
4707 uint16_t uCsStart = pCtx->cs.Sel;
4708 uint64_t uRipStart = pCtx->rip;
4709
4710 int rc = VERR_INTERNAL_ERROR_5;
4711 for (;;)
4712 {
4713 Assert(!HMR0SuspendPending());
4714 AssertMsg(pVCpu->hm.s.idEnteredCpu == RTMpCpuId(),
4715 ("Illegal migration! Entered on CPU %u Current %u cLoops=%u\n", (unsigned)pVCpu->hm.s.idEnteredCpu,
4716 (unsigned)RTMpCpuId(), *pcLoops));
4717
4718 /* Preparatory work for running guest code, this may force us to return
4719 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
4720 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
4721 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
4722 if (rc != VINF_SUCCESS)
4723 break;
4724
4725 /*
4726 * No longjmps to ring-3 from this point on!!!
4727 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
4728 * This also disables flushing of the R0-logger instance (if any).
4729 */
4730 VMMRZCallRing3Disable(pVCpu);
4731 VMMRZCallRing3RemoveNotification(pVCpu);
4732 hmR0SvmPreRunGuestCommitted(pVCpu, pCtx, &SvmTransient);
4733
4734 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
4735
4736 /*
4737 * Restore any residual host-state and save any bits shared between host and guest into the guest-CPU state.
4738 * This will also re-enable longjmps to ring-3 when it has reached a safe point!!!
4739 */
4740 hmR0SvmPostRunGuest(pVCpu, pCtx, &SvmTransient, rc);
4741 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
4742 || SvmTransient.u64ExitCode == SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
4743 {
4744 if (rc == VINF_SUCCESS)
4745 rc = VERR_SVM_INVALID_GUEST_STATE;
4746 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
4747 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
4748 return rc;
4749 }
4750
4751 /* Handle the #VMEXIT. */
4752 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
4753 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
4754 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, pVCpu->hm.s.svm.pVmcb);
4755 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
4756 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
4757 if (rc != VINF_SUCCESS)
4758 break;
4759 if (++(*pcLoops) >= cMaxResumeLoops)
4760 {
4761 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
4762 rc = VINF_EM_RAW_INTERRUPT;
4763 break;
4764 }
4765
4766 /*
4767 * Did the RIP change, if so, consider it a single step.
4768 * Otherwise, make sure one of the TFs gets set.
4769 */
4770 if ( pCtx->rip != uRipStart
4771 || pCtx->cs.Sel != uCsStart)
4772 {
4773 rc = VINF_EM_DBG_STEPPED;
4774 break;
4775 }
4776 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
4777 }
4778
4779 /*
4780 * Clear the X86_EFL_TF if necessary.
4781 */
4782 if (pVCpu->hm.s.fClearTrapFlag)
4783 {
4784 pVCpu->hm.s.fClearTrapFlag = false;
4785 pCtx->eflags.Bits.u1TF = 0;
4786 }
4787
4788 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
4789 return rc;
4790}
4791
4792#ifdef VBOX_WITH_NESTED_HWVIRT
4793/**
4794 * Runs the nested-guest code using AMD-V.
4795 *
4796 * @returns VBox status code.
4797 * @param pVM The cross context VM structure.
4798 * @param pVCpu The cross context virtual CPU structure.
4799 * @param pCtx Pointer to the guest-CPU context.
4800 * @param pcLoops Pointer to the number of executed loops. If we're switching
4801 * from the guest-code execution loop to this nested-guest
4802 * execution loop pass the remainder value, else pass 0.
4803 */
4804static int hmR0SvmRunGuestCodeNested(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t *pcLoops)
4805{
4806 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
4807 Assert(pcLoops);
4808 Assert(*pcLoops <= pVM->hm.s.cMaxResumeLoops);
4809
4810 SVMTRANSIENT SvmTransient;
4811 RT_ZERO(SvmTransient);
4812 SvmTransient.fUpdateTscOffsetting = true;
4813 SvmTransient.pVmcb = pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
4814 SvmTransient.fIsNestedGuest = true;
4815
4816 int rc = VERR_INTERNAL_ERROR_4;
4817 for (;;)
4818 {
4819 Assert(!HMR0SuspendPending());
4820 HMSVM_ASSERT_CPU_SAFE();
4821
4822 /* Preparatory work for running nested-guest code, this may force us to return
4823 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
4824 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
4825 rc = hmR0SvmPreRunGuestNested(pVM, pVCpu, pCtx, &SvmTransient);
4826 if ( rc != VINF_SUCCESS
4827 || !CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
4828 {
4829 break;
4830 }
4831
4832 /*
4833 * No longjmps to ring-3 from this point on!!!
4834 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
4835 * This also disables flushing of the R0-logger instance (if any).
4836 */
4837 hmR0SvmPreRunGuestCommitted(pVCpu, pCtx, &SvmTransient);
4838
4839 rc = hmR0SvmRunGuestNested(pVM, pVCpu, pCtx);
4840
4841 /* Restore any residual host-state and save any bits shared between host
4842 and guest into the guest-CPU state. Re-enables interrupts! */
4843 hmR0SvmPostRunGuest(pVCpu, pCtx, &SvmTransient, rc);
4844
4845 if (RT_LIKELY( rc == VINF_SUCCESS
4846 && SvmTransient.u64ExitCode != SVM_EXIT_INVALID))
4847 { /* extremely likely */ }
4848 else
4849 {
4850 /* VMRUN failed, shouldn't really happen, Guru. */
4851 if (rc != VINF_SUCCESS)
4852 break;
4853
4854 /* Invalid nested-guest state. Cause a #VMEXIT but assert on strict builds. */
4855 AssertMsgFailed(("Invalid nested-guest state. rc=%Rrc u64ExitCode=%#RX64\n", rc, SvmTransient.u64ExitCode));
4856 rc = VBOXSTRICTRC_TODO(IEMExecSvmVmexit(pVCpu, SVM_EXIT_INVALID, 0, 0));
4857 break;
4858 }
4859
4860 /* Handle the #VMEXIT. */
4861 HMSVM_NESTED_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
4862 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
4863 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, pCtx->hwvirt.svm.CTX_SUFF(pVmcb));
4864 rc = hmR0SvmHandleExitNested(pVCpu, pCtx, &SvmTransient);
4865 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
4866 if ( rc != VINF_SUCCESS
4867 || !CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
4868 break;
4869 if (++(*pcLoops) >= pVM->hm.s.cMaxResumeLoops)
4870 {
4871 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
4872 rc = VINF_EM_RAW_INTERRUPT;
4873 break;
4874 }
4875
4876 /** @todo handle single-stepping */
4877 }
4878
4879 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
4880 return rc;
4881}
4882#endif
4883
4884
4885/**
4886 * Runs the guest code using AMD-V.
4887 *
4888 * @returns Strict VBox status code.
4889 * @param pVM The cross context VM structure.
4890 * @param pVCpu The cross context virtual CPU structure.
4891 * @param pCtx Pointer to the guest-CPU context.
4892 */
4893VMMR0DECL(VBOXSTRICTRC) SVMR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4894{
4895 Assert(VMMRZCallRing3IsEnabled(pVCpu));
4896 HMSVM_ASSERT_PREEMPT_SAFE();
4897 VMMRZCallRing3SetNotification(pVCpu, hmR0SvmCallRing3Callback, pCtx);
4898
4899 uint32_t cLoops = 0;
4900 int rc;
4901#ifdef VBOX_WITH_NESTED_HWVIRT
4902 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
4903#endif
4904 {
4905 if (!pVCpu->hm.s.fSingleInstruction)
4906 rc = hmR0SvmRunGuestCodeNormal(pVM, pVCpu, pCtx, &cLoops);
4907 else
4908 rc = hmR0SvmRunGuestCodeStep(pVM, pVCpu, pCtx, &cLoops);
4909 }
4910#ifdef VBOX_WITH_NESTED_HWVIRT
4911 else
4912 {
4913 rc = VINF_SVM_VMRUN;
4914 }
4915
4916 /* Re-check the nested-guest condition here as we may be transitioning from the normal
4917 execution loop into the nested-guest, hence this is not placed in the 'else' part above. */
4918 if (rc == VINF_SVM_VMRUN)
4919 {
4920 rc = hmR0SvmRunGuestCodeNested(pVM, pVCpu, pCtx, &cLoops);
4921 if (rc == VINF_SVM_VMEXIT)
4922 rc = VINF_SUCCESS;
4923 }
4924#endif
4925
4926 /* Fixup error codes. */
4927 if (rc == VERR_EM_INTERPRETER)
4928 rc = VINF_EM_RAW_EMULATE_INSTR;
4929 else if (rc == VINF_EM_RESET)
4930 rc = VINF_EM_TRIPLE_FAULT;
4931
4932 /* Prepare to return to ring-3. This will remove longjmp notifications. */
4933 rc = hmR0SvmExitToRing3(pVM, pVCpu, pCtx, rc);
4934 Assert(!VMMRZCallRing3IsNotificationSet(pVCpu));
4935 return rc;
4936}
4937
4938
4939#ifdef VBOX_WITH_NESTED_HWVIRT
4940/**
4941 * Determines whether an IOIO intercept is active for the nested-guest or not.
4942 *
4943 * @param pvIoBitmap Pointer to the nested-guest IO bitmap.
4944 * @param pIoExitInfo Pointer to the SVMIOIOEXITINFO.
4945 */
4946static bool hmR0SvmIsIoInterceptActive(void *pvIoBitmap, PSVMIOIOEXITINFO pIoExitInfo)
4947{
4948 const uint16_t u16Port = pIoExitInfo->n.u16Port;
4949 const SVMIOIOTYPE enmIoType = (SVMIOIOTYPE)pIoExitInfo->n.u1Type;
4950 const uint8_t cbReg = (pIoExitInfo->u >> SVM_IOIO_OP_SIZE_SHIFT) & 7;
4951 const uint8_t cAddrSizeBits = ((pIoExitInfo->u >> SVM_IOIO_ADDR_SIZE_SHIFT) & 7) << 4;
4952 const uint8_t iEffSeg = pIoExitInfo->n.u3Seg;
4953 const bool fRep = pIoExitInfo->n.u1Rep;
4954 const bool fStrIo = pIoExitInfo->n.u1Str;
4955
4956 return HMSvmIsIOInterceptActive(pvIoBitmap, u16Port, enmIoType, cbReg, cAddrSizeBits, iEffSeg, fRep, fStrIo,
4957 NULL /* pIoExitInfo */);
4958}
4959
4960
4961/**
4962 * Handles a nested-guest \#VMEXIT (for all EXITCODE values except
4963 * SVM_EXIT_INVALID).
4964 *
4965 * @returns VBox status code (informational status codes included).
4966 * @param pVCpu The cross context virtual CPU structure.
4967 * @param pCtx Pointer to the guest-CPU context.
4968 * @param pSvmTransient Pointer to the SVM transient structure.
4969 */
4970static int hmR0SvmHandleExitNested(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4971{
4972 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
4973 Assert(pSvmTransient->u64ExitCode != SVM_EXIT_INVALID);
4974 Assert(pSvmTransient->u64ExitCode <= SVM_EXIT_MAX);
4975
4976#define HM_SVM_VMEXIT_NESTED(a_pVCpu, a_uExitCode, a_uExitInfo1, a_uExitInfo2) \
4977 VBOXSTRICTRC_TODO(IEMExecSvmVmexit(a_pVCpu, a_uExitCode, a_uExitInfo1, a_uExitInfo2))
4978
4979 /*
4980 * For all the #VMEXITs here we primarily figure out if the #VMEXIT is expected
4981 * by the nested-guest. If it isn't, it should be handled by the (outer) guest.
4982 */
4983 PSVMVMCB pVmcbNstGst = pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
4984 PSVMVMCBCTRL pVmcbNstGstCtrl = &pVmcbNstGst->ctrl;
4985 uint64_t const uExitCode = pVmcbNstGstCtrl->u64ExitCode;
4986 uint64_t const uExitInfo1 = pVmcbNstGstCtrl->u64ExitInfo1;
4987 uint64_t const uExitInfo2 = pVmcbNstGstCtrl->u64ExitInfo2;
4988
4989 Assert(uExitCode == pVmcbNstGstCtrl->u64ExitCode);
4990 switch (uExitCode)
4991 {
4992 case SVM_EXIT_CPUID:
4993 {
4994 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_CPUID))
4995 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
4996 return hmR0SvmExitCpuid(pVCpu, pCtx, pSvmTransient);
4997 }
4998
4999 case SVM_EXIT_RDTSC:
5000 {
5001 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_RDTSC))
5002 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5003 return hmR0SvmExitRdtsc(pVCpu, pCtx, pSvmTransient);
5004 }
5005
5006 case SVM_EXIT_RDTSCP:
5007 {
5008 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_RDTSCP))
5009 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5010 return hmR0SvmExitRdtscp(pVCpu, pCtx, pSvmTransient);
5011 }
5012
5013 case SVM_EXIT_MONITOR:
5014 {
5015 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_MONITOR))
5016 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5017 return hmR0SvmExitMonitor(pVCpu, pCtx, pSvmTransient);
5018 }
5019
5020 case SVM_EXIT_MWAIT:
5021 {
5022 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_MWAIT))
5023 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5024 return hmR0SvmExitMwait(pVCpu, pCtx, pSvmTransient);
5025 }
5026
5027 case SVM_EXIT_HLT:
5028 {
5029 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_HLT))
5030 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5031 return hmR0SvmExitHlt(pVCpu, pCtx, pSvmTransient);
5032 }
5033
5034 case SVM_EXIT_MSR:
5035 {
5036 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_MSR_PROT))
5037 {
5038 uint32_t const idMsr = pCtx->ecx;
5039 uint16_t offMsrpm;
5040 uint8_t uMsrpmBit;
5041 int rc = HMSvmGetMsrpmOffsetAndBit(idMsr, &offMsrpm, &uMsrpmBit);
5042 if (RT_SUCCESS(rc))
5043 {
5044 Assert(uMsrpmBit == 0 || uMsrpmBit == 2 || uMsrpmBit == 4 || uMsrpmBit == 6);
5045 Assert(offMsrpm < SVM_MSRPM_PAGES << X86_PAGE_4K_SHIFT);
5046
5047 uint8_t const *pbMsrBitmap = (uint8_t const *)pCtx->hwvirt.svm.CTX_SUFF(pvMsrBitmap);
5048 pbMsrBitmap += offMsrpm;
5049 bool const fInterceptRead = RT_BOOL(*pbMsrBitmap & RT_BIT(uMsrpmBit));
5050 bool const fInterceptWrite = RT_BOOL(*pbMsrBitmap & RT_BIT(uMsrpmBit + 1));
5051
5052 if ( (fInterceptWrite && pVmcbNstGstCtrl->u64ExitInfo1 == SVM_EXIT1_MSR_WRITE)
5053 || (fInterceptRead && pVmcbNstGstCtrl->u64ExitInfo1 == SVM_EXIT1_MSR_READ))
5054 {
5055 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5056 }
5057 }
5058 else
5059 {
5060 /*
5061 * MSRs not covered by the MSRPM automatically cause an #VMEXIT.
5062 * See AMD-V spec. "15.11 MSR Intercepts".
5063 */
5064 Assert(rc == VERR_OUT_OF_RANGE);
5065 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5066 }
5067 }
5068 return hmR0SvmExitMsr(pVCpu, pCtx, pSvmTransient);
5069 }
5070
5071 case SVM_EXIT_IOIO:
5072 {
5073 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_IOIO_PROT))
5074 {
5075 void *pvIoBitmap = pCtx->hwvirt.svm.CTX_SUFF(pvIoBitmap);
5076 SVMIOIOEXITINFO IoExitInfo;
5077 IoExitInfo.u = pVmcbNstGst->ctrl.u64ExitInfo1;
5078 bool const fIntercept = hmR0SvmIsIoInterceptActive(pvIoBitmap, &IoExitInfo);
5079 if (fIntercept)
5080 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5081 }
5082 return hmR0SvmExitIOInstr(pVCpu, pCtx, pSvmTransient);
5083 }
5084
5085 case SVM_EXIT_XCPT_PF:
5086 {
5087 PVM pVM = pVCpu->CTX_SUFF(pVM);
5088 if (pVM->hm.s.fNestedPaging)
5089 {
5090 uint32_t const u32ErrCode = pVmcbNstGstCtrl->u64ExitInfo1;
5091 uint64_t const uFaultAddress = pVmcbNstGstCtrl->u64ExitInfo2;
5092
5093 /* If the nested-guest is intercepting #PFs, cause a #PF #VMEXIT. */
5094 if (HMIsGuestSvmXcptInterceptSet(pVCpu, pCtx, X86_XCPT_PF))
5095 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, u32ErrCode, uFaultAddress);
5096
5097 /* If the nested-guest is not intercepting #PFs, forward the #PF to the nested-guest. */
5098 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
5099 return VINF_SUCCESS;
5100 }
5101 return hmR0SvmExitXcptPFNested(pVCpu, pCtx,pSvmTransient);
5102 }
5103
5104 case SVM_EXIT_XCPT_UD:
5105 {
5106 if (HMIsGuestSvmXcptInterceptSet(pVCpu, pCtx, X86_XCPT_UD))
5107 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5108 hmR0SvmSetPendingXcptUD(pVCpu);
5109 return VINF_SUCCESS;
5110 }
5111
5112 case SVM_EXIT_XCPT_MF:
5113 {
5114 if (HMIsGuestSvmXcptInterceptSet(pVCpu, pCtx, X86_XCPT_MF))
5115 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5116 return hmR0SvmExitXcptMF(pVCpu, pCtx, pSvmTransient);
5117 }
5118
5119 case SVM_EXIT_XCPT_DB:
5120 {
5121 if (HMIsGuestSvmXcptInterceptSet(pVCpu, pCtx, X86_XCPT_DB))
5122 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5123 return hmR0SvmNestedExitXcptDB(pVCpu, pCtx, pSvmTransient);
5124 }
5125
5126 case SVM_EXIT_XCPT_AC:
5127 {
5128 if (HMIsGuestSvmXcptInterceptSet(pVCpu, pCtx, X86_XCPT_AC))
5129 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5130 return hmR0SvmExitXcptAC(pVCpu, pCtx, pSvmTransient);
5131 }
5132
5133 case SVM_EXIT_XCPT_BP:
5134 {
5135 if (HMIsGuestSvmXcptInterceptSet(pVCpu, pCtx, X86_XCPT_BP))
5136 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5137 return hmR0SvmNestedExitXcptBP(pVCpu, pCtx, pSvmTransient);
5138 }
5139
5140 case SVM_EXIT_READ_CR0:
5141 case SVM_EXIT_READ_CR3:
5142 case SVM_EXIT_READ_CR4:
5143 {
5144 uint8_t const uCr = uExitCode - SVM_EXIT_READ_CR0;
5145 if (HMIsGuestSvmReadCRxInterceptSet(pVCpu, pCtx, uCr))
5146 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5147 return hmR0SvmExitReadCRx(pVCpu, pCtx, pSvmTransient);
5148 }
5149
5150 case SVM_EXIT_CR0_SEL_WRITE:
5151 {
5152 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_CR0_SEL_WRITE))
5153 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5154 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
5155 }
5156
5157 case SVM_EXIT_WRITE_CR0:
5158 case SVM_EXIT_WRITE_CR3:
5159 case SVM_EXIT_WRITE_CR4:
5160 case SVM_EXIT_WRITE_CR8: /** @todo Shouldn't writes to CR8 go to V_TPR instead since we run with V_INTR_MASKING set? */
5161 {
5162 uint8_t const uCr = uExitCode - SVM_EXIT_WRITE_CR0;
5163 Log4(("hmR0SvmHandleExitNested: Write CR%u: uExitInfo1=%#RX64 uExitInfo2=%#RX64\n", uCr, uExitInfo1, uExitInfo2));
5164
5165 if (HMIsGuestSvmWriteCRxInterceptSet(pVCpu, pCtx, uCr))
5166 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5167 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
5168 }
5169
5170 case SVM_EXIT_PAUSE:
5171 {
5172 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_PAUSE))
5173 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5174 return hmR0SvmExitPause(pVCpu, pCtx, pSvmTransient);
5175 }
5176
5177 case SVM_EXIT_VINTR:
5178 {
5179 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_VINTR))
5180 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5181 return hmR0SvmExitUnexpected(pVCpu, pCtx, pSvmTransient);
5182 }
5183
5184 case SVM_EXIT_INTR:
5185 case SVM_EXIT_NMI:
5186 case SVM_EXIT_XCPT_NMI: /* Shouldn't ever happen, SVM_EXIT_NMI is used instead. */
5187 case SVM_EXIT_SMI:
5188 {
5189 /*
5190 * We shouldn't direct physical interrupts, NMIs, SMIs to the nested-guest.
5191 *
5192 * Although we don't intercept SMIs, the nested-guest might. Therefore, we
5193 * might get an SMI #VMEXIT here so simply ignore rather than causing a
5194 * corresponding nested-guest #VMEXIT.
5195 */
5196 return hmR0SvmExitIntr(pVCpu, pCtx, pSvmTransient);
5197 }
5198
5199 case SVM_EXIT_FERR_FREEZE:
5200 {
5201 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_FERR_FREEZE))
5202 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5203 return hmR0SvmExitFerrFreeze(pVCpu, pCtx, pSvmTransient);
5204 }
5205
5206 case SVM_EXIT_INVLPG:
5207 {
5208 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_INVLPG))
5209 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5210 return hmR0SvmExitInvlpg(pVCpu, pCtx, pSvmTransient);
5211 }
5212
5213 case SVM_EXIT_WBINVD:
5214 {
5215 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_WBINVD))
5216 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5217 return hmR0SvmExitWbinvd(pVCpu, pCtx, pSvmTransient);
5218 }
5219
5220 case SVM_EXIT_INVD:
5221 {
5222 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_INVD))
5223 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5224 return hmR0SvmExitInvd(pVCpu, pCtx, pSvmTransient);
5225 }
5226
5227 case SVM_EXIT_RDPMC:
5228 {
5229 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_RDPMC))
5230 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5231 return hmR0SvmExitRdpmc(pVCpu, pCtx, pSvmTransient);
5232 }
5233
5234 default:
5235 {
5236 switch (uExitCode)
5237 {
5238 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
5239 case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7: case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9:
5240 case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11: case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13:
5241 case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
5242 {
5243 uint8_t const uDr = uExitCode - SVM_EXIT_READ_DR0;
5244 if (HMIsGuestSvmReadDRxInterceptSet(pVCpu, pCtx, uDr))
5245 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5246 return hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
5247 }
5248
5249 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
5250 case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7: case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9:
5251 case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11: case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13:
5252 case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
5253 {
5254 uint8_t const uDr = uExitCode - SVM_EXIT_WRITE_DR0;
5255 if (HMIsGuestSvmWriteDRxInterceptSet(pVCpu, pCtx, uDr))
5256 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5257 return hmR0SvmExitWriteDRx(pVCpu, pCtx, pSvmTransient);
5258 }
5259
5260 case SVM_EXIT_XCPT_0: /* #DE */
5261 /* SVM_EXIT_XCPT_1: */ /* #DB - Handled above. */
5262 /* SVM_EXIT_XCPT_2: */ /* #NMI - Handled above. */
5263 /* SVM_EXIT_XCPT_3: */ /* #BP - Handled above. */
5264 case SVM_EXIT_XCPT_4: /* #OF */
5265 case SVM_EXIT_XCPT_5: /* #BR */
5266 /* SVM_EXIT_XCPT_6: */ /* #UD - Handled above. */
5267 case SVM_EXIT_XCPT_7: /* #NM */
5268 case SVM_EXIT_XCPT_8: /* #DF */
5269 case SVM_EXIT_XCPT_9: /* #CO_SEG_OVERRUN */
5270 case SVM_EXIT_XCPT_10: /* #TS */
5271 case SVM_EXIT_XCPT_11: /* #NP */
5272 case SVM_EXIT_XCPT_12: /* #SS */
5273 case SVM_EXIT_XCPT_13: /* #GP */
5274 /* SVM_EXIT_XCPT_14: */ /* #PF - Handled above. */
5275 case SVM_EXIT_XCPT_15: /* Reserved. */
5276 /* SVM_EXIT_XCPT_16: */ /* #MF - Handled above. */
5277 /* SVM_EXIT_XCPT_17: */ /* #AC - Handled above. */
5278 case SVM_EXIT_XCPT_18: /* #MC */
5279 case SVM_EXIT_XCPT_19: /* #XF */
5280 case SVM_EXIT_XCPT_20: case SVM_EXIT_XCPT_21: case SVM_EXIT_XCPT_22: case SVM_EXIT_XCPT_23:
5281 case SVM_EXIT_XCPT_24: case SVM_EXIT_XCPT_25: case SVM_EXIT_XCPT_26: case SVM_EXIT_XCPT_27:
5282 case SVM_EXIT_XCPT_28: case SVM_EXIT_XCPT_29: case SVM_EXIT_XCPT_30: case SVM_EXIT_XCPT_31:
5283 {
5284 uint8_t const uVector = uExitCode - SVM_EXIT_XCPT_0;
5285 if (HMIsGuestSvmXcptInterceptSet(pVCpu, pCtx, uVector))
5286 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5287 return hmR0SvmExitXcptGeneric(pVCpu, pCtx, pSvmTransient);
5288 }
5289
5290 case SVM_EXIT_XSETBV:
5291 {
5292 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_XSETBV))
5293 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5294 return hmR0SvmExitXsetbv(pVCpu, pCtx, pSvmTransient);
5295 }
5296
5297 case SVM_EXIT_TASK_SWITCH:
5298 {
5299 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_TASK_SWITCH))
5300 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5301 return hmR0SvmExitTaskSwitch(pVCpu, pCtx, pSvmTransient);
5302 }
5303
5304 case SVM_EXIT_IRET:
5305 {
5306 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_IRET))
5307 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5308 return hmR0SvmExitIret(pVCpu, pCtx, pSvmTransient);
5309 }
5310
5311 case SVM_EXIT_SHUTDOWN:
5312 {
5313 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_SHUTDOWN))
5314 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5315 return hmR0SvmExitShutdown(pVCpu, pCtx, pSvmTransient);
5316 }
5317
5318 case SVM_EXIT_VMMCALL:
5319 {
5320 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_VMMCALL))
5321 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5322 return hmR0SvmExitVmmCall(pVCpu, pCtx, pSvmTransient);
5323 }
5324
5325 case SVM_EXIT_CLGI:
5326 {
5327 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_CLGI))
5328 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5329 return hmR0SvmExitClgi(pVCpu, pCtx, pSvmTransient);
5330 }
5331
5332 case SVM_EXIT_STGI:
5333 {
5334 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_STGI))
5335 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5336 return hmR0SvmExitStgi(pVCpu, pCtx, pSvmTransient);
5337 }
5338
5339 case SVM_EXIT_VMLOAD:
5340 {
5341 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_VMLOAD))
5342 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5343 return hmR0SvmExitVmload(pVCpu, pCtx, pSvmTransient);
5344 }
5345
5346 case SVM_EXIT_VMSAVE:
5347 {
5348 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_VMSAVE))
5349 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5350 return hmR0SvmExitVmsave(pVCpu, pCtx, pSvmTransient);
5351 }
5352
5353 case SVM_EXIT_INVLPGA:
5354 {
5355 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_INVLPGA))
5356 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5357 return hmR0SvmExitInvlpga(pVCpu, pCtx, pSvmTransient);
5358 }
5359
5360 case SVM_EXIT_VMRUN:
5361 {
5362 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_VMRUN))
5363 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5364 return hmR0SvmExitVmrun(pVCpu, pCtx, pSvmTransient);
5365 }
5366
5367 case SVM_EXIT_RSM:
5368 {
5369 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_RSM))
5370 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5371 hmR0SvmSetPendingXcptUD(pVCpu);
5372 return VINF_SUCCESS;
5373 }
5374
5375 case SVM_EXIT_SKINIT:
5376 {
5377 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_SKINIT))
5378 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5379 hmR0SvmSetPendingXcptUD(pVCpu);
5380 return VINF_SUCCESS;
5381 }
5382
5383 case SVM_EXIT_NPF:
5384 {
5385 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
5386 return hmR0SvmExitNestedPF(pVCpu, pCtx, pSvmTransient);
5387 }
5388
5389 case SVM_EXIT_INIT: /* We shouldn't get INIT signals while executing a nested-guest. */
5390 return hmR0SvmExitUnexpected(pVCpu, pCtx, pSvmTransient);
5391
5392 default:
5393 {
5394 AssertMsgFailed(("hmR0SvmHandleExitNested: Unknown exit code %#x\n", pSvmTransient->u64ExitCode));
5395 pVCpu->hm.s.u32HMError = pSvmTransient->u64ExitCode;
5396 return VERR_SVM_UNKNOWN_EXIT;
5397 }
5398 }
5399 }
5400 }
5401 /* not reached */
5402
5403#undef HM_SVM_VMEXIT_NESTED
5404}
5405#endif
5406
5407
5408/**
5409 * Handles a guest \#VMEXIT (for all EXITCODE values except SVM_EXIT_INVALID).
5410 *
5411 * @returns VBox status code (informational status codes included).
5412 * @param pVCpu The cross context virtual CPU structure.
5413 * @param pCtx Pointer to the guest-CPU context.
5414 * @param pSvmTransient Pointer to the SVM transient structure.
5415 */
5416static int hmR0SvmHandleExit(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5417{
5418 Assert(pSvmTransient->u64ExitCode != SVM_EXIT_INVALID);
5419 Assert(pSvmTransient->u64ExitCode <= SVM_EXIT_MAX);
5420
5421 /*
5422 * The ordering of the case labels is based on most-frequently-occurring #VMEXITs for most guests under
5423 * normal workloads (for some definition of "normal").
5424 */
5425 uint64_t const uExitCode = pSvmTransient->u64ExitCode;
5426 switch (uExitCode)
5427 {
5428 case SVM_EXIT_NPF:
5429 return hmR0SvmExitNestedPF(pVCpu, pCtx, pSvmTransient);
5430
5431 case SVM_EXIT_IOIO:
5432 return hmR0SvmExitIOInstr(pVCpu, pCtx, pSvmTransient);
5433
5434 case SVM_EXIT_RDTSC:
5435 return hmR0SvmExitRdtsc(pVCpu, pCtx, pSvmTransient);
5436
5437 case SVM_EXIT_RDTSCP:
5438 return hmR0SvmExitRdtscp(pVCpu, pCtx, pSvmTransient);
5439
5440 case SVM_EXIT_CPUID:
5441 return hmR0SvmExitCpuid(pVCpu, pCtx, pSvmTransient);
5442
5443 case SVM_EXIT_XCPT_14: /* X86_XCPT_PF */
5444 return hmR0SvmExitXcptPF(pVCpu, pCtx, pSvmTransient);
5445
5446 case SVM_EXIT_XCPT_6: /* X86_XCPT_UD */
5447 return hmR0SvmExitXcptUD(pVCpu, pCtx, pSvmTransient);
5448
5449 case SVM_EXIT_XCPT_16: /* X86_XCPT_MF */
5450 return hmR0SvmExitXcptMF(pVCpu, pCtx, pSvmTransient);
5451
5452 case SVM_EXIT_XCPT_1: /* X86_XCPT_DB */
5453 return hmR0SvmExitXcptDB(pVCpu, pCtx, pSvmTransient);
5454
5455 case SVM_EXIT_XCPT_17: /* X86_XCPT_AC */
5456 return hmR0SvmExitXcptAC(pVCpu, pCtx, pSvmTransient);
5457
5458 case SVM_EXIT_XCPT_3: /* X86_XCPT_BP */
5459 return hmR0SvmExitXcptBP(pVCpu, pCtx, pSvmTransient);
5460
5461 case SVM_EXIT_MONITOR:
5462 return hmR0SvmExitMonitor(pVCpu, pCtx, pSvmTransient);
5463
5464 case SVM_EXIT_MWAIT:
5465 return hmR0SvmExitMwait(pVCpu, pCtx, pSvmTransient);
5466
5467 case SVM_EXIT_HLT:
5468 return hmR0SvmExitHlt(pVCpu, pCtx, pSvmTransient);
5469
5470 case SVM_EXIT_READ_CR0:
5471 case SVM_EXIT_READ_CR3:
5472 case SVM_EXIT_READ_CR4:
5473 return hmR0SvmExitReadCRx(pVCpu, pCtx, pSvmTransient);
5474
5475 case SVM_EXIT_CR0_SEL_WRITE:
5476 case SVM_EXIT_WRITE_CR0:
5477 case SVM_EXIT_WRITE_CR3:
5478 case SVM_EXIT_WRITE_CR4:
5479 case SVM_EXIT_WRITE_CR8:
5480 {
5481 uint8_t const uCr = uExitCode == SVM_EXIT_CR0_SEL_WRITE ? 0 : uExitCode - SVM_EXIT_WRITE_CR0;
5482 Log4(("hmR0SvmHandleExit: Write CR%u\n", uCr)); NOREF(uCr);
5483 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
5484 }
5485
5486 case SVM_EXIT_PAUSE:
5487 return hmR0SvmExitPause(pVCpu, pCtx, pSvmTransient);
5488
5489 case SVM_EXIT_VMMCALL:
5490 return hmR0SvmExitVmmCall(pVCpu, pCtx, pSvmTransient);
5491
5492 case SVM_EXIT_VINTR:
5493 return hmR0SvmExitVIntr(pVCpu, pCtx, pSvmTransient);
5494
5495 case SVM_EXIT_FERR_FREEZE:
5496 return hmR0SvmExitFerrFreeze(pVCpu, pCtx, pSvmTransient);
5497
5498 case SVM_EXIT_INTR:
5499 case SVM_EXIT_NMI:
5500 case SVM_EXIT_XCPT_NMI: /* Shouldn't ever happen, SVM_EXIT_NMI is used instead. */
5501 return hmR0SvmExitIntr(pVCpu, pCtx, pSvmTransient);
5502
5503 case SVM_EXIT_MSR:
5504 return hmR0SvmExitMsr(pVCpu, pCtx, pSvmTransient);
5505
5506 case SVM_EXIT_INVLPG:
5507 return hmR0SvmExitInvlpg(pVCpu, pCtx, pSvmTransient);
5508
5509 case SVM_EXIT_WBINVD:
5510 return hmR0SvmExitWbinvd(pVCpu, pCtx, pSvmTransient);
5511
5512 case SVM_EXIT_INVD:
5513 return hmR0SvmExitInvd(pVCpu, pCtx, pSvmTransient);
5514
5515 case SVM_EXIT_RDPMC:
5516 return hmR0SvmExitRdpmc(pVCpu, pCtx, pSvmTransient);
5517
5518 default:
5519 {
5520 switch (pSvmTransient->u64ExitCode)
5521 {
5522 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
5523 case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7: case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9:
5524 case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11: case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13:
5525 case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
5526 return hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
5527
5528 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
5529 case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7: case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9:
5530 case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11: case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13:
5531 case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
5532 return hmR0SvmExitWriteDRx(pVCpu, pCtx, pSvmTransient);
5533
5534 case SVM_EXIT_XSETBV:
5535 return hmR0SvmExitXsetbv(pVCpu, pCtx, pSvmTransient);
5536
5537 case SVM_EXIT_TASK_SWITCH:
5538 return hmR0SvmExitTaskSwitch(pVCpu, pCtx, pSvmTransient);
5539
5540 case SVM_EXIT_IRET:
5541 return hmR0SvmExitIret(pVCpu, pCtx, pSvmTransient);
5542
5543 case SVM_EXIT_SHUTDOWN:
5544 return hmR0SvmExitShutdown(pVCpu, pCtx, pSvmTransient);
5545
5546 case SVM_EXIT_SMI:
5547 case SVM_EXIT_INIT:
5548 {
5549 /*
5550 * We don't intercept SMIs. As for INIT signals, it really shouldn't ever happen here.
5551 * If it ever does, we want to know about it so log the exit code and bail.
5552 */
5553 return hmR0SvmExitUnexpected(pVCpu, pCtx, pSvmTransient);
5554 }
5555
5556#ifdef VBOX_WITH_NESTED_HWVIRT
5557 case SVM_EXIT_CLGI: return hmR0SvmExitClgi(pVCpu, pCtx, pSvmTransient);
5558 case SVM_EXIT_STGI: return hmR0SvmExitStgi(pVCpu, pCtx, pSvmTransient);
5559 case SVM_EXIT_VMLOAD: return hmR0SvmExitVmload(pVCpu, pCtx, pSvmTransient);
5560 case SVM_EXIT_VMSAVE: return hmR0SvmExitVmsave(pVCpu, pCtx, pSvmTransient);
5561 case SVM_EXIT_INVLPGA: return hmR0SvmExitInvlpga(pVCpu, pCtx, pSvmTransient);
5562 case SVM_EXIT_VMRUN: return hmR0SvmExitVmrun(pVCpu, pCtx, pSvmTransient);
5563#else
5564 case SVM_EXIT_CLGI:
5565 case SVM_EXIT_STGI:
5566 case SVM_EXIT_VMLOAD:
5567 case SVM_EXIT_VMSAVE:
5568 case SVM_EXIT_INVLPGA:
5569 case SVM_EXIT_VMRUN:
5570#endif
5571 case SVM_EXIT_RSM:
5572 case SVM_EXIT_SKINIT:
5573 {
5574 hmR0SvmSetPendingXcptUD(pVCpu);
5575 return VINF_SUCCESS;
5576 }
5577
5578#ifdef HMSVM_ALWAYS_TRAP_ALL_XCPTS
5579 case SVM_EXIT_XCPT_0: /* #DE */
5580 /* SVM_EXIT_XCPT_1: */ /* #DB - Handled above. */
5581 /* SVM_EXIT_XCPT_2: */ /* #NMI - Handled above. */
5582 /* SVM_EXIT_XCPT_3: */ /* #BP - Handled above. */
5583 case SVM_EXIT_XCPT_4: /* #OF */
5584 case SVM_EXIT_XCPT_5: /* #BR */
5585 /* SVM_EXIT_XCPT_6: */ /* #UD - Handled above. */
5586 case SVM_EXIT_XCPT_7: /* #NM */
5587 case SVM_EXIT_XCPT_8: /* #DF */
5588 case SVM_EXIT_XCPT_9: /* #CO_SEG_OVERRUN */
5589 case SVM_EXIT_XCPT_10: /* #TS */
5590 case SVM_EXIT_XCPT_11: /* #NP */
5591 case SVM_EXIT_XCPT_12: /* #SS */
5592 case SVM_EXIT_XCPT_13: /* #GP */
5593 /* SVM_EXIT_XCPT_14: */ /* #PF - Handled above. */
5594 case SVM_EXIT_XCPT_15: /* Reserved. */
5595 /* SVM_EXIT_XCPT_16: */ /* #MF - Handled above. */
5596 /* SVM_EXIT_XCPT_17: */ /* #AC - Handled above. */
5597 case SVM_EXIT_XCPT_18: /* #MC */
5598 case SVM_EXIT_XCPT_19: /* #XF */
5599 case SVM_EXIT_XCPT_20: case SVM_EXIT_XCPT_21: case SVM_EXIT_XCPT_22: case SVM_EXIT_XCPT_23:
5600 case SVM_EXIT_XCPT_24: case SVM_EXIT_XCPT_25: case SVM_EXIT_XCPT_26: case SVM_EXIT_XCPT_27:
5601 case SVM_EXIT_XCPT_28: case SVM_EXIT_XCPT_29: case SVM_EXIT_XCPT_30: case SVM_EXIT_XCPT_31:
5602 return hmR0SvmExitXcptGeneric(pVCpu, pCtx, pSvmTransient);
5603#endif /* HMSVM_ALWAYS_TRAP_ALL_XCPTS */
5604
5605 default:
5606 {
5607 AssertMsgFailed(("hmR0SvmHandleExit: Unknown exit code %#RX64\n", uExitCode));
5608 pVCpu->hm.s.u32HMError = uExitCode;
5609 return VERR_SVM_UNKNOWN_EXIT;
5610 }
5611 }
5612 }
5613 }
5614 /* not reached */
5615}
5616
5617
5618#ifdef DEBUG
5619/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
5620# define HMSVM_ASSERT_PREEMPT_CPUID_VAR() \
5621 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
5622
5623# define HMSVM_ASSERT_PREEMPT_CPUID() \
5624 do \
5625 { \
5626 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
5627 AssertMsg(idAssertCpu == idAssertCpuNow, ("SVM %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
5628 } while (0)
5629
5630# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() \
5631 do { \
5632 AssertPtr(pVCpu); \
5633 AssertPtr(pCtx); \
5634 AssertPtr(pSvmTransient); \
5635 Assert(ASMIntAreEnabled()); \
5636 HMSVM_ASSERT_PREEMPT_SAFE(); \
5637 HMSVM_ASSERT_PREEMPT_CPUID_VAR(); \
5638 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)); \
5639 HMSVM_ASSERT_PREEMPT_SAFE(); \
5640 if (VMMR0IsLogFlushDisabled(pVCpu)) \
5641 HMSVM_ASSERT_PREEMPT_CPUID(); \
5642 } while (0)
5643#else /* Release builds */
5644# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() do { NOREF(pVCpu); NOREF(pCtx); NOREF(pSvmTransient); } while (0)
5645#endif
5646
5647
5648/**
5649 * Worker for hmR0SvmInterpretInvlpg().
5650 *
5651 * @return VBox status code.
5652 * @param pVCpu The cross context virtual CPU structure.
5653 * @param pCpu Pointer to the disassembler state.
5654 * @param pCtx The guest CPU context.
5655 */
5656static int hmR0SvmInterpretInvlPgEx(PVMCPU pVCpu, PDISCPUSTATE pCpu, PCPUMCTX pCtx)
5657{
5658 DISQPVPARAMVAL Param1;
5659 RTGCPTR GCPtrPage;
5660
5661 int rc = DISQueryParamVal(CPUMCTX2CORE(pCtx), pCpu, &pCpu->Param1, &Param1, DISQPVWHICH_SRC);
5662 if (RT_FAILURE(rc))
5663 return VERR_EM_INTERPRETER;
5664
5665 if ( Param1.type == DISQPV_TYPE_IMMEDIATE
5666 || Param1.type == DISQPV_TYPE_ADDRESS)
5667 {
5668 if (!(Param1.flags & (DISQPV_FLAG_32 | DISQPV_FLAG_64)))
5669 return VERR_EM_INTERPRETER;
5670
5671 GCPtrPage = Param1.val.val64;
5672 VBOXSTRICTRC rc2 = EMInterpretInvlpg(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx), GCPtrPage);
5673 rc = VBOXSTRICTRC_VAL(rc2);
5674 }
5675 else
5676 {
5677 Log4(("hmR0SvmInterpretInvlPgEx invalid parameter type %#x\n", Param1.type));
5678 rc = VERR_EM_INTERPRETER;
5679 }
5680
5681 return rc;
5682}
5683
5684
5685/**
5686 * Interprets INVLPG.
5687 *
5688 * @returns VBox status code.
5689 * @retval VINF_* Scheduling instructions.
5690 * @retval VERR_EM_INTERPRETER Something we can't cope with.
5691 * @retval VERR_* Fatal errors.
5692 *
5693 * @param pVM The cross context VM structure.
5694 * @param pVCpu The cross context virtual CPU structure.
5695 * @param pCtx The guest CPU context.
5696 *
5697 * @remarks Updates the RIP if the instruction was executed successfully.
5698 */
5699static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
5700{
5701 /* Only allow 32 & 64 bit code. */
5702 if (CPUMGetGuestCodeBits(pVCpu) != 16)
5703 {
5704 PDISSTATE pDis = &pVCpu->hm.s.DisState;
5705 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL /* pcbInstr */);
5706 if ( RT_SUCCESS(rc)
5707 && pDis->pCurInstr->uOpcode == OP_INVLPG)
5708 {
5709 rc = hmR0SvmInterpretInvlPgEx(pVCpu, pDis, pCtx);
5710 if (RT_SUCCESS(rc))
5711 pCtx->rip += pDis->cbInstr;
5712 return rc;
5713 }
5714 else
5715 Log4(("hmR0SvmInterpretInvlpg: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
5716 }
5717 return VERR_EM_INTERPRETER;
5718}
5719
5720
5721#ifdef HMSVM_USE_IEM_EVENT_REFLECTION
5722/**
5723 * Gets the IEM exception flags for the specified SVM event.
5724 *
5725 * @returns The IEM exception flags.
5726 * @param pEvent Pointer to the SVM event.
5727 *
5728 * @remarks This function currently only constructs flags required for
5729 * IEMEvaluateRecursiveXcpt and not the complete flags (e.g. error-code
5730 * and CR2 aspects of an exception are not included).
5731 */
5732static uint32_t hmR0SvmGetIemXcptFlags(PCSVMEVENT pEvent)
5733{
5734 uint8_t const uEventType = pEvent->n.u3Type;
5735 uint32_t fIemXcptFlags;
5736 switch (uEventType)
5737 {
5738 case SVM_EVENT_EXCEPTION:
5739 /*
5740 * Only INT3 and INTO instructions can raise #BP and #OF exceptions.
5741 * See AMD spec. Table 8-1. "Interrupt Vector Source and Cause".
5742 */
5743 if (pEvent->n.u8Vector == X86_XCPT_BP)
5744 {
5745 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT | IEM_XCPT_FLAGS_BP_INSTR;
5746 break;
5747 }
5748 if (pEvent->n.u8Vector == X86_XCPT_OF)
5749 {
5750 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT | IEM_XCPT_FLAGS_OF_INSTR;
5751 break;
5752 }
5753 /** @todo How do we distinguish ICEBP \#DB from the regular one? */
5754 RT_FALL_THRU();
5755 case SVM_EVENT_NMI:
5756 fIemXcptFlags = IEM_XCPT_FLAGS_T_CPU_XCPT;
5757 break;
5758
5759 case SVM_EVENT_EXTERNAL_IRQ:
5760 fIemXcptFlags = IEM_XCPT_FLAGS_T_EXT_INT;
5761 break;
5762
5763 case SVM_EVENT_SOFTWARE_INT:
5764 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT;
5765 break;
5766
5767 default:
5768 fIemXcptFlags = 0;
5769 AssertMsgFailed(("Unexpected event type! uEventType=%#x uVector=%#x", uEventType, pEvent->n.u8Vector));
5770 break;
5771 }
5772 return fIemXcptFlags;
5773}
5774
5775#else
5776/**
5777 * Determines if an exception is a contributory exception.
5778 *
5779 * Contributory exceptions are ones which can cause double-faults unless the
5780 * original exception was a benign exception. Page-fault is intentionally not
5781 * included here as it's a conditional contributory exception.
5782 *
5783 * @returns @c true if the exception is contributory, @c false otherwise.
5784 * @param uVector The exception vector.
5785 */
5786DECLINLINE(bool) hmR0SvmIsContributoryXcpt(const uint32_t uVector)
5787{
5788 switch (uVector)
5789 {
5790 case X86_XCPT_GP:
5791 case X86_XCPT_SS:
5792 case X86_XCPT_NP:
5793 case X86_XCPT_TS:
5794 case X86_XCPT_DE:
5795 return true;
5796 default:
5797 break;
5798 }
5799 return false;
5800}
5801#endif /* HMSVM_USE_IEM_EVENT_REFLECTION */
5802
5803
5804/**
5805 * Handle a condition that occurred while delivering an event through the guest
5806 * IDT.
5807 *
5808 * @returns VBox status code (informational error codes included).
5809 * @retval VINF_SUCCESS if we should continue handling the \#VMEXIT.
5810 * @retval VINF_HM_DOUBLE_FAULT if a \#DF condition was detected and we ought to
5811 * continue execution of the guest which will delivery the \#DF.
5812 * @retval VINF_EM_RESET if we detected a triple-fault condition.
5813 * @retval VERR_EM_GUEST_CPU_HANG if we detected a guest CPU hang.
5814 *
5815 * @param pVCpu The cross context virtual CPU structure.
5816 * @param pCtx Pointer to the guest-CPU context.
5817 * @param pSvmTransient Pointer to the SVM transient structure.
5818 *
5819 * @remarks No-long-jump zone!!!
5820 */
5821static int hmR0SvmCheckExitDueToEventDelivery(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5822{
5823 int rc = VINF_SUCCESS;
5824 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
5825
5826 Log4(("EXITINTINFO: Pending vectoring event %#RX64 Valid=%RTbool ErrValid=%RTbool Err=%#RX32 Type=%u Vector=%u\n",
5827 pVmcb->ctrl.ExitIntInfo.u, !!pVmcb->ctrl.ExitIntInfo.n.u1Valid, !!pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid,
5828 pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode, pVmcb->ctrl.ExitIntInfo.n.u3Type, pVmcb->ctrl.ExitIntInfo.n.u8Vector));
5829
5830 /* See AMD spec. 15.7.3 "EXITINFO Pseudo-Code". The EXITINTINFO (if valid) contains the prior exception (IDT vector)
5831 * that was trying to be delivered to the guest which caused a #VMEXIT which was intercepted (Exit vector). */
5832 if (pVmcb->ctrl.ExitIntInfo.n.u1Valid)
5833 {
5834#ifdef HMSVM_USE_IEM_EVENT_REFLECTION
5835 IEMXCPTRAISE enmRaise;
5836 IEMXCPTRAISEINFO fRaiseInfo;
5837 bool const fExitIsHwXcpt = pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0 <= SVM_EXIT_XCPT_31;
5838 uint8_t const uIdtVector = pVmcb->ctrl.ExitIntInfo.n.u8Vector;
5839 if (fExitIsHwXcpt)
5840 {
5841 uint8_t const uExitVector = pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0;
5842 uint32_t const fIdtVectorFlags = hmR0SvmGetIemXcptFlags(&pVmcb->ctrl.ExitIntInfo);
5843 uint32_t const fExitVectorFlags = IEM_XCPT_FLAGS_T_CPU_XCPT;
5844 enmRaise = IEMEvaluateRecursiveXcpt(pVCpu, fIdtVectorFlags, uIdtVector, fExitVectorFlags, uExitVector, &fRaiseInfo);
5845 }
5846 else
5847 {
5848 /*
5849 * If delivery of an event caused a #VMEXIT that is not an exception (e.g. #NPF) then we
5850 * end up here.
5851 *
5852 * If the event was:
5853 * - a software interrupt, we can re-execute the instruction which will regenerate
5854 * the event.
5855 * - an NMI, we need to clear NMI blocking and re-inject the NMI.
5856 * - a hardware exception or external interrupt, we re-inject it.
5857 */
5858 fRaiseInfo = IEMXCPTRAISEINFO_NONE;
5859 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_SOFTWARE_INT)
5860 enmRaise = IEMXCPTRAISE_REEXEC_INSTR;
5861 else
5862 enmRaise = IEMXCPTRAISE_PREV_EVENT;
5863 }
5864
5865 switch (enmRaise)
5866 {
5867 case IEMXCPTRAISE_CURRENT_XCPT:
5868 case IEMXCPTRAISE_PREV_EVENT:
5869 {
5870 /* For software interrupts, we shall re-execute the instruction. */
5871 if (!(fRaiseInfo & IEMXCPTRAISEINFO_SOFT_INT_XCPT))
5872 {
5873 RTGCUINTPTR GCPtrFaultAddress = 0;
5874
5875 /* If we are re-injecting an NMI, clear NMI blocking. */
5876 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_NMI)
5877 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
5878
5879 /* Determine a vectoring #PF condition, see comment in hmR0SvmExitXcptPF(). */
5880 if (fRaiseInfo & (IEMXCPTRAISEINFO_EXT_INT_PF | IEMXCPTRAISEINFO_NMI_PF))
5881 pSvmTransient->fVectoringPF = true;
5882 else if ( pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXCEPTION
5883 && uIdtVector == X86_XCPT_PF)
5884 {
5885 /*
5886 * If the previous exception was a #PF, we need to recover the CR2 value.
5887 * This can't happen with shadow paging.
5888 */
5889 GCPtrFaultAddress = pCtx->cr2;
5890 }
5891
5892 /*
5893 * Without nested paging, when uExitVector is #PF, CR2 value will be updated from the VMCB's
5894 * exit info. fields, if it's a guest #PF, see hmR0SvmExitXcptPF().
5895 */
5896 Assert(pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT);
5897 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
5898 hmR0SvmSetPendingEvent(pVCpu, &pVmcb->ctrl.ExitIntInfo, GCPtrFaultAddress);
5899
5900 Log4(("IDT: Pending vectoring event %#RX64 ErrValid=%RTbool Err=%#RX32 GCPtrFaultAddress=%#RX64\n",
5901 pVmcb->ctrl.ExitIntInfo.u, RT_BOOL(pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid),
5902 pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode, GCPtrFaultAddress));
5903 }
5904 break;
5905 }
5906
5907 case IEMXCPTRAISE_REEXEC_INSTR:
5908 {
5909 Assert(rc == VINF_SUCCESS);
5910 break;
5911 }
5912
5913 case IEMXCPTRAISE_DOUBLE_FAULT:
5914 {
5915 /*
5916 * Determing a vectoring double #PF condition. Used later, when PGM evaluates the
5917 * second #PF as a guest #PF (and not a shadow #PF) and needs to be converted into a #DF.
5918 */
5919 if (fRaiseInfo & IEMXCPTRAISEINFO_PF_PF)
5920 {
5921 pSvmTransient->fVectoringDoublePF = true;
5922 Assert(rc == VINF_SUCCESS);
5923 }
5924 else
5925 {
5926 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
5927 hmR0SvmSetPendingXcptDF(pVCpu);
5928 rc = VINF_HM_DOUBLE_FAULT;
5929 }
5930 break;
5931 }
5932
5933 case IEMXCPTRAISE_TRIPLE_FAULT:
5934 {
5935 rc = VINF_EM_RESET;
5936 break;
5937 }
5938
5939 case IEMXCPTRAISE_CPU_HANG:
5940 {
5941 rc = VERR_EM_GUEST_CPU_HANG;
5942 break;
5943 }
5944
5945 default:
5946 {
5947 AssertMsgFailed(("hmR0SvmExitCpuid: EMInterpretCpuId failed with %Rrc\n", rc));
5948 rc = VERR_SVM_IPE_2;
5949 break;
5950 }
5951 }
5952#else
5953 uint8_t uIdtVector = pVmcb->ctrl.ExitIntInfo.n.u8Vector;
5954
5955 typedef enum
5956 {
5957 SVMREFLECTXCPT_XCPT, /* Reflect the exception to the guest or for further evaluation by VMM. */
5958 SVMREFLECTXCPT_DF, /* Reflect the exception as a double-fault to the guest. */
5959 SVMREFLECTXCPT_TF, /* Indicate a triple faulted state to the VMM. */
5960 SVMREFLECTXCPT_HANG, /* Indicate bad VM trying to deadlock the CPU. */
5961 SVMREFLECTXCPT_NONE /* Nothing to reflect. */
5962 } SVMREFLECTXCPT;
5963
5964 SVMREFLECTXCPT enmReflect = SVMREFLECTXCPT_NONE;
5965 bool fReflectingNmi = false;
5966 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXCEPTION)
5967 {
5968 if (pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0 <= SVM_EXIT_XCPT_31)
5969 {
5970 uint8_t uExitVector = (uint8_t)(pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0);
5971
5972#ifdef VBOX_STRICT
5973 if ( hmR0SvmIsContributoryXcpt(uIdtVector)
5974 && uExitVector == X86_XCPT_PF)
5975 {
5976 Log4(("IDT: Contributory #PF idCpu=%u uCR2=%#RX64\n", pVCpu->idCpu, pCtx->cr2));
5977 }
5978#endif
5979
5980 if ( uIdtVector == X86_XCPT_BP
5981 || uIdtVector == X86_XCPT_OF)
5982 {
5983 /* Ignore INT3/INTO, just re-execute. See @bugref{8357}. */
5984 }
5985 else if ( uExitVector == X86_XCPT_PF
5986 && uIdtVector == X86_XCPT_PF)
5987 {
5988 pSvmTransient->fVectoringDoublePF = true;
5989 Log4(("IDT: Vectoring double #PF uCR2=%#RX64\n", pCtx->cr2));
5990 }
5991 else if ( uExitVector == X86_XCPT_AC
5992 && uIdtVector == X86_XCPT_AC)
5993 {
5994 enmReflect = SVMREFLECTXCPT_HANG;
5995 Log4(("IDT: Nested #AC - Bad guest\n"));
5996 }
5997 else if ( (pVmcb->ctrl.u32InterceptXcpt & HMSVM_CONTRIBUTORY_XCPT_MASK)
5998 && hmR0SvmIsContributoryXcpt(uExitVector)
5999 && ( hmR0SvmIsContributoryXcpt(uIdtVector)
6000 || uIdtVector == X86_XCPT_PF))
6001 {
6002 enmReflect = SVMREFLECTXCPT_DF;
6003 Log4(("IDT: Pending vectoring #DF %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->hm.s.Event.u64IntInfo,
6004 uIdtVector, uExitVector));
6005 }
6006 else if (uIdtVector == X86_XCPT_DF)
6007 {
6008 enmReflect = SVMREFLECTXCPT_TF;
6009 Log4(("IDT: Pending vectoring triple-fault %#RX64 uIdtVector=%#x uExitVector=%#x\n",
6010 pVCpu->hm.s.Event.u64IntInfo, uIdtVector, uExitVector));
6011 }
6012 else
6013 enmReflect = SVMREFLECTXCPT_XCPT;
6014 }
6015 else
6016 {
6017 /*
6018 * If event delivery caused an #VMEXIT that is not an exception (e.g. #NPF) then reflect the original
6019 * exception to the guest after handling the #VMEXIT.
6020 */
6021 enmReflect = SVMREFLECTXCPT_XCPT;
6022 }
6023 }
6024 else if ( pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXTERNAL_IRQ
6025 || pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_NMI)
6026 {
6027 enmReflect = SVMREFLECTXCPT_XCPT;
6028 fReflectingNmi = RT_BOOL(pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_NMI);
6029
6030 if (pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0 <= SVM_EXIT_XCPT_31)
6031 {
6032 uint8_t uExitVector = (uint8_t)(pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0);
6033 if (uExitVector == X86_XCPT_PF)
6034 {
6035 pSvmTransient->fVectoringPF = true;
6036 Log4(("IDT: Vectoring #PF due to Ext-Int/NMI. uCR2=%#RX64\n", pCtx->cr2));
6037 }
6038 }
6039 }
6040 /* else: Ignore software interrupts (INT n) as they reoccur when restarting the instruction. */
6041
6042 switch (enmReflect)
6043 {
6044 case SVMREFLECTXCPT_XCPT:
6045 {
6046 /* If we are re-injecting the NMI, clear NMI blocking. */
6047 if (fReflectingNmi)
6048 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
6049
6050 Assert(pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT);
6051 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
6052 hmR0SvmSetPendingEvent(pVCpu, &pVmcb->ctrl.ExitIntInfo, 0 /* GCPtrFaultAddress */);
6053
6054 /* If uExitVector is #PF, CR2 value will be updated from the VMCB if it's a guest #PF. See hmR0SvmExitXcptPF(). */
6055 Log4(("IDT: Pending vectoring event %#RX64 ErrValid=%RTbool Err=%#RX32\n", pVmcb->ctrl.ExitIntInfo.u,
6056 !!pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid, pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
6057 break;
6058 }
6059
6060 case SVMREFLECTXCPT_DF:
6061 {
6062 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
6063 hmR0SvmSetPendingXcptDF(pVCpu);
6064 rc = VINF_HM_DOUBLE_FAULT;
6065 break;
6066 }
6067
6068 case SVMREFLECTXCPT_TF:
6069 {
6070 rc = VINF_EM_RESET;
6071 break;
6072 }
6073
6074 case SVMREFLECTXCPT_HANG:
6075 {
6076 rc = VERR_EM_GUEST_CPU_HANG;
6077 break;
6078 }
6079
6080 default:
6081 Assert(rc == VINF_SUCCESS);
6082 break;
6083 }
6084#endif /* HMSVM_USE_IEM_EVENT_REFLECTION */
6085 }
6086 Assert(rc == VINF_SUCCESS || rc == VINF_HM_DOUBLE_FAULT || rc == VINF_EM_RESET || rc == VERR_EM_GUEST_CPU_HANG);
6087 NOREF(pCtx);
6088 return rc;
6089}
6090
6091
6092/**
6093 * Advances the guest RIP making use of the CPU's NRIP_SAVE feature if
6094 * supported, otherwise advances the RIP by the number of bytes specified in
6095 * @a cb.
6096 *
6097 * @param pVCpu The cross context virtual CPU structure.
6098 * @param pCtx Pointer to the guest-CPU context.
6099 * @param cb RIP increment value in bytes.
6100 *
6101 * @remarks Use this function only from \#VMEXIT's where the NRIP value is valid
6102 * when NRIP_SAVE is supported by the CPU, otherwise use
6103 * hmR0SvmAdvanceRipDumb!
6104 */
6105DECLINLINE(void) hmR0SvmAdvanceRipHwAssist(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t cb)
6106{
6107 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6108 if (fSupportsNextRipSave)
6109 {
6110 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6111 Assert(pVmcb);
6112 Assert(pVmcb->ctrl.u64NextRIP);
6113 AssertRelease(pVmcb->ctrl.u64NextRIP - pCtx->rip == cb); /* temporary, remove later */
6114 pCtx->rip = pVmcb->ctrl.u64NextRIP;
6115 }
6116 else
6117 pCtx->rip += cb;
6118
6119 HMSVM_UPDATE_INTR_SHADOW(pVCpu, pCtx);
6120}
6121
6122
6123#ifdef VBOX_WITH_NESTED_HWVIRT
6124/**
6125 * Gets the length of the current instruction if the CPU supports the NRIP_SAVE
6126 * feature. Otherwise, returns the value in @a cbLikely.
6127 *
6128 * @param pVCpu The cross context virtual CPU structure.
6129 * @param pCtx Pointer to the guest-CPU context.
6130 * @param cbLikely The likely instruction length.
6131 */
6132DECLINLINE(uint8_t) hmR0SvmGetInstrLengthHwAssist(PVMCPU pVCpu, PCPUMCTX pCtx, uint8_t cbLikely)
6133{
6134 Assert(cbLikely <= 15); /* See Intel spec. 2.3.11 "AVX Instruction Length" */
6135 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6136 if (fSupportsNextRipSave)
6137 {
6138 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6139 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6140 Assert(cbInstr == cbLikely);
6141 return cbInstr;
6142 }
6143 return cbLikely;
6144}
6145#endif
6146
6147
6148/**
6149 * Advances the guest RIP by the number of bytes specified in @a cb. This does
6150 * not make use of any hardware features to determine the instruction length.
6151 *
6152 * @param pVCpu The cross context virtual CPU structure.
6153 * @param pCtx Pointer to the guest-CPU context.
6154 * @param cb RIP increment value in bytes.
6155 */
6156DECLINLINE(void) hmR0SvmAdvanceRipDumb(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t cb)
6157{
6158 pCtx->rip += cb;
6159 HMSVM_UPDATE_INTR_SHADOW(pVCpu, pCtx);
6160}
6161#undef HMSVM_UPDATE_INTR_SHADOW
6162
6163
6164/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
6165/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #VMEXIT handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
6166/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
6167
6168/** @name \#VMEXIT handlers.
6169 * @{
6170 */
6171
6172/**
6173 * \#VMEXIT handler for external interrupts, NMIs, FPU assertion freeze and INIT
6174 * signals (SVM_EXIT_INTR, SVM_EXIT_NMI, SVM_EXIT_FERR_FREEZE, SVM_EXIT_INIT).
6175 */
6176HMSVM_EXIT_DECL hmR0SvmExitIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6177{
6178 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6179
6180 if (pSvmTransient->u64ExitCode == SVM_EXIT_NMI)
6181 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGC);
6182 else if (pSvmTransient->u64ExitCode == SVM_EXIT_INTR)
6183 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
6184
6185 /*
6186 * AMD-V has no preemption timer and the generic periodic preemption timer has no way to signal -before- the timer
6187 * fires if the current interrupt is our own timer or a some other host interrupt. We also cannot examine what
6188 * interrupt it is until the host actually take the interrupt.
6189 *
6190 * Going back to executing guest code here unconditionally causes random scheduling problems (observed on an
6191 * AMD Phenom 9850 Quad-Core on Windows 64-bit host).
6192 */
6193 return VINF_EM_RAW_INTERRUPT;
6194}
6195
6196
6197/**
6198 * \#VMEXIT handler for WBINVD (SVM_EXIT_WBINVD). Conditional \#VMEXIT.
6199 */
6200HMSVM_EXIT_DECL hmR0SvmExitWbinvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6201{
6202 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6203
6204 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6205 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWbinvd);
6206 int rc = VINF_SUCCESS;
6207 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6208 return rc;
6209}
6210
6211
6212/**
6213 * \#VMEXIT handler for INVD (SVM_EXIT_INVD). Unconditional \#VMEXIT.
6214 */
6215HMSVM_EXIT_DECL hmR0SvmExitInvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6216{
6217 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6218
6219 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6220 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvd);
6221 int rc = VINF_SUCCESS;
6222 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6223 return rc;
6224}
6225
6226
6227/**
6228 * \#VMEXIT handler for INVD (SVM_EXIT_CPUID). Conditional \#VMEXIT.
6229 */
6230HMSVM_EXIT_DECL hmR0SvmExitCpuid(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6231{
6232 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6233 PVM pVM = pVCpu->CTX_SUFF(pVM);
6234 int rc = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
6235 if (RT_LIKELY(rc == VINF_SUCCESS))
6236 {
6237 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6238 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6239 }
6240 else
6241 {
6242 AssertMsgFailed(("hmR0SvmExitCpuid: EMInterpretCpuId failed with %Rrc\n", rc));
6243 rc = VERR_EM_INTERPRETER;
6244 }
6245 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCpuid);
6246 return rc;
6247}
6248
6249
6250/**
6251 * \#VMEXIT handler for RDTSC (SVM_EXIT_RDTSC). Conditional \#VMEXIT.
6252 */
6253HMSVM_EXIT_DECL hmR0SvmExitRdtsc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6254{
6255 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6256 PVM pVM = pVCpu->CTX_SUFF(pVM);
6257 int rc = EMInterpretRdtsc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
6258 if (RT_LIKELY(rc == VINF_SUCCESS))
6259 {
6260 pSvmTransient->fUpdateTscOffsetting = true;
6261 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6262 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6263 }
6264 else
6265 {
6266 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtsc failed with %Rrc\n", rc));
6267 rc = VERR_EM_INTERPRETER;
6268 }
6269 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtsc);
6270 return rc;
6271}
6272
6273
6274/**
6275 * \#VMEXIT handler for RDTSCP (SVM_EXIT_RDTSCP). Conditional \#VMEXIT.
6276 */
6277HMSVM_EXIT_DECL hmR0SvmExitRdtscp(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6278{
6279 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6280 int rc = EMInterpretRdtscp(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
6281 if (RT_LIKELY(rc == VINF_SUCCESS))
6282 {
6283 pSvmTransient->fUpdateTscOffsetting = true;
6284 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3);
6285 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6286 }
6287 else
6288 {
6289 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtscp failed with %Rrc\n", rc));
6290 rc = VERR_EM_INTERPRETER;
6291 }
6292 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtscp);
6293 return rc;
6294}
6295
6296
6297/**
6298 * \#VMEXIT handler for RDPMC (SVM_EXIT_RDPMC). Conditional \#VMEXIT.
6299 */
6300HMSVM_EXIT_DECL hmR0SvmExitRdpmc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6301{
6302 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6303 int rc = EMInterpretRdpmc(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
6304 if (RT_LIKELY(rc == VINF_SUCCESS))
6305 {
6306 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6307 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6308 }
6309 else
6310 {
6311 AssertMsgFailed(("hmR0SvmExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
6312 rc = VERR_EM_INTERPRETER;
6313 }
6314 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdpmc);
6315 return rc;
6316}
6317
6318
6319/**
6320 * \#VMEXIT handler for INVLPG (SVM_EXIT_INVLPG). Conditional \#VMEXIT.
6321 */
6322HMSVM_EXIT_DECL hmR0SvmExitInvlpg(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6323{
6324 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6325 PVM pVM = pVCpu->CTX_SUFF(pVM);
6326 Assert(!pVM->hm.s.fNestedPaging);
6327 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpg);
6328
6329 bool const fSupportsDecodeAssists = hmR0SvmSupportsDecodeAssists(pVCpu, pCtx);
6330 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6331 if ( fSupportsDecodeAssists
6332 && fSupportsNextRipSave)
6333 {
6334 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6335 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6336 RTGCPTR const GCPtrPage = pVmcb->ctrl.u64ExitInfo1;
6337 VBOXSTRICTRC rcStrict = IEMExecDecodedInvlpg(pVCpu, cbInstr, GCPtrPage);
6338 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6339 return VBOXSTRICTRC_VAL(rcStrict);
6340 }
6341
6342 int rc = hmR0SvmInterpretInvlpg(pVM, pVCpu, pCtx); /* Updates RIP if successful. */
6343 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
6344 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6345 return rc;
6346}
6347
6348
6349/**
6350 * \#VMEXIT handler for HLT (SVM_EXIT_HLT). Conditional \#VMEXIT.
6351 */
6352HMSVM_EXIT_DECL hmR0SvmExitHlt(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6353{
6354 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6355
6356 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 1);
6357 int rc = EMShouldContinueAfterHalt(pVCpu, pCtx) ? VINF_SUCCESS : VINF_EM_HALT;
6358 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6359 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
6360 if (rc != VINF_SUCCESS)
6361 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHltToR3);
6362 return rc;
6363}
6364
6365
6366/**
6367 * \#VMEXIT handler for MONITOR (SVM_EXIT_MONITOR). Conditional \#VMEXIT.
6368 */
6369HMSVM_EXIT_DECL hmR0SvmExitMonitor(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6370{
6371 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6372 int rc = EMInterpretMonitor(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
6373 if (RT_LIKELY(rc == VINF_SUCCESS))
6374 {
6375 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3);
6376 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6377 }
6378 else
6379 {
6380 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMonitor: EMInterpretMonitor failed with %Rrc\n", rc));
6381 rc = VERR_EM_INTERPRETER;
6382 }
6383 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMonitor);
6384 return rc;
6385}
6386
6387
6388/**
6389 * \#VMEXIT handler for MWAIT (SVM_EXIT_MWAIT). Conditional \#VMEXIT.
6390 */
6391HMSVM_EXIT_DECL hmR0SvmExitMwait(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6392{
6393 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6394 VBOXSTRICTRC rc2 = EMInterpretMWait(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
6395 int rc = VBOXSTRICTRC_VAL(rc2);
6396 if ( rc == VINF_EM_HALT
6397 || rc == VINF_SUCCESS)
6398 {
6399 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3);
6400
6401 if ( rc == VINF_EM_HALT
6402 && EMMonitorWaitShouldContinue(pVCpu, pCtx))
6403 {
6404 rc = VINF_SUCCESS;
6405 }
6406 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6407 }
6408 else
6409 {
6410 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMwait: EMInterpretMWait failed with %Rrc\n", rc));
6411 rc = VERR_EM_INTERPRETER;
6412 }
6413 AssertMsg(rc == VINF_SUCCESS || rc == VINF_EM_HALT || rc == VERR_EM_INTERPRETER,
6414 ("hmR0SvmExitMwait: EMInterpretMWait failed rc=%Rrc\n", rc));
6415 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMwait);
6416 return rc;
6417}
6418
6419
6420/**
6421 * \#VMEXIT handler for shutdown (triple-fault) (SVM_EXIT_SHUTDOWN). Conditional
6422 * \#VMEXIT.
6423 */
6424HMSVM_EXIT_DECL hmR0SvmExitShutdown(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6425{
6426 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6427 return VINF_EM_RESET;
6428}
6429
6430
6431/**
6432 * \#VMEXIT handler for unexpected exits. Conditional \#VMEXIT.
6433 */
6434HMSVM_EXIT_DECL hmR0SvmExitUnexpected(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6435{
6436 RT_NOREF(pCtx);
6437 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6438 AssertMsgFailed(("hmR0SvmExitUnexpected: ExitCode=%#RX64 uExitInfo1=%#RX64 uExitInfo2=%#RX64\n", pSvmTransient->u64ExitCode,
6439 pVmcb->ctrl.u64ExitInfo1, pVmcb->ctrl.u64ExitInfo2));
6440 RT_NOREF(pVmcb);
6441 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
6442 return VERR_SVM_UNEXPECTED_EXIT;
6443}
6444
6445
6446/**
6447 * \#VMEXIT handler for CRx reads (SVM_EXIT_READ_CR*). Conditional \#VMEXIT.
6448 */
6449HMSVM_EXIT_DECL hmR0SvmExitReadCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6450{
6451 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6452
6453 Log4(("hmR0SvmExitReadCRx: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
6454 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxRead[pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0]);
6455
6456 bool const fSupportsDecodeAssists = hmR0SvmSupportsDecodeAssists(pVCpu, pCtx);
6457 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6458 if ( fSupportsDecodeAssists
6459 && fSupportsNextRipSave)
6460 {
6461 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6462 bool const fMovCRx = RT_BOOL(pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_MASK);
6463 if (fMovCRx)
6464 {
6465 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6466 uint8_t const iCrReg = pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0;
6467 uint8_t const iGReg = pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_GPR_NUMBER;
6468 VBOXSTRICTRC rcStrict = IEMExecDecodedMovCRxRead(pVCpu, cbInstr, iGReg, iCrReg);
6469 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6470 return VBOXSTRICTRC_VAL(rcStrict);
6471 }
6472 /* else: SMSW instruction, fall back below to IEM for this. */
6473 }
6474
6475 VBOXSTRICTRC rc2 = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
6476 int rc = VBOXSTRICTRC_VAL(rc2);
6477 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3,
6478 ("hmR0SvmExitReadCRx: EMInterpretInstruction failed rc=%Rrc\n", rc));
6479 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0) <= 15);
6480 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6481 return rc;
6482}
6483
6484
6485/**
6486 * \#VMEXIT handler for CRx writes (SVM_EXIT_WRITE_CR*). Conditional \#VMEXIT.
6487 */
6488HMSVM_EXIT_DECL hmR0SvmExitWriteCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6489{
6490 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6491
6492 uint64_t const uExitCode = pSvmTransient->u64ExitCode;
6493 uint8_t const iCrReg = uExitCode == SVM_EXIT_CR0_SEL_WRITE ? 0 : (pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0);
6494 Assert(iCrReg <= 15);
6495
6496 VBOXSTRICTRC rcStrict = VERR_SVM_IPE_5;
6497 bool fDecodedInstr = false;
6498 bool const fSupportsDecodeAssists = hmR0SvmSupportsDecodeAssists(pVCpu, pCtx);
6499 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6500 if ( fSupportsDecodeAssists
6501 && fSupportsNextRipSave)
6502 {
6503 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6504 bool const fMovCRx = RT_BOOL(pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_MASK);
6505 if (fMovCRx)
6506 {
6507 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6508 uint8_t const iGReg = pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_GPR_NUMBER;
6509 Log4(("hmR0SvmExitWriteCRx: Mov CR%u w/ iGReg=%#x\n", iCrReg, iGReg));
6510 rcStrict = IEMExecDecodedMovCRxWrite(pVCpu, cbInstr, iCrReg, iGReg);
6511 fDecodedInstr = true;
6512 }
6513 /* else: LMSW or CLTS instruction, fall back below to IEM for this. */
6514 }
6515
6516 if (!fDecodedInstr)
6517 {
6518 Log4(("hmR0SvmExitWriteCRx: iCrReg=%#x\n", iCrReg));
6519 rcStrict = IEMExecOneBypassEx(pVCpu, CPUMCTX2CORE(pCtx), NULL);
6520 if (RT_UNLIKELY( rcStrict == VERR_IEM_ASPECT_NOT_IMPLEMENTED
6521 || rcStrict == VERR_IEM_INSTR_NOT_IMPLEMENTED))
6522 rcStrict = VERR_EM_INTERPRETER;
6523 }
6524
6525 if (rcStrict == VINF_SUCCESS)
6526 {
6527 switch (iCrReg)
6528 {
6529 case 0: /* CR0. */
6530 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
6531 break;
6532
6533 case 3: /* CR3. */
6534 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR3);
6535 break;
6536
6537 case 4: /* CR4. */
6538 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR4);
6539 break;
6540
6541 case 8: /* CR8 (TPR). */
6542 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
6543 break;
6544
6545 default:
6546 AssertMsgFailed(("hmR0SvmExitWriteCRx: Invalid/Unexpected Write-CRx exit. u64ExitCode=%#RX64 %#x\n",
6547 pSvmTransient->u64ExitCode, iCrReg));
6548 break;
6549 }
6550 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6551 }
6552 else
6553 Assert(rcStrict == VERR_EM_INTERPRETER || rcStrict == VINF_PGM_CHANGE_MODE || rcStrict == VINF_PGM_SYNC_CR3);
6554 return VBOXSTRICTRC_TODO(rcStrict);
6555}
6556
6557
6558/**
6559 * \#VMEXIT handler for MSR read and writes (SVM_EXIT_MSR). Conditional
6560 * \#VMEXIT.
6561 */
6562HMSVM_EXIT_DECL hmR0SvmExitMsr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6563{
6564 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6565 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6566 PVM pVM = pVCpu->CTX_SUFF(pVM);
6567
6568 int rc;
6569 if (pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_WRITE)
6570 {
6571 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
6572 Log4(("MSR Write: idMsr=%#RX32\n", pCtx->ecx));
6573
6574 /* Handle TPR patching; intercepted LSTAR write. */
6575 if ( pVM->hm.s.fTPRPatchingActive
6576 && pCtx->ecx == MSR_K8_LSTAR)
6577 {
6578 if ((pCtx->eax & 0xff) != pSvmTransient->u8GuestTpr)
6579 {
6580 /* Our patch code uses LSTAR for TPR caching for 32-bit guests. */
6581 int rc2 = APICSetTpr(pVCpu, pCtx->eax & 0xff);
6582 AssertRC(rc2);
6583 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
6584 }
6585 rc = VINF_SUCCESS;
6586 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6587 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6588 return rc;
6589 }
6590
6591 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6592 if (fSupportsNextRipSave)
6593 {
6594 rc = EMInterpretWrmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
6595 if (RT_LIKELY(rc == VINF_SUCCESS))
6596 {
6597 pCtx->rip = pVmcb->ctrl.u64NextRIP;
6598 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6599 }
6600 else
6601 AssertMsg( rc == VERR_EM_INTERPRETER
6602 || rc == VINF_CPUM_R3_MSR_WRITE, ("hmR0SvmExitMsr: EMInterpretWrmsr failed rc=%Rrc\n", rc));
6603 }
6604 else
6605 {
6606 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */));
6607 if (RT_LIKELY(rc == VINF_SUCCESS))
6608 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc); /* RIP updated by EMInterpretInstruction(). */
6609 else
6610 AssertMsg( rc == VERR_EM_INTERPRETER
6611 || rc == VINF_CPUM_R3_MSR_WRITE, ("hmR0SvmExitMsr: WrMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
6612 }
6613
6614 if (rc == VINF_SUCCESS)
6615 {
6616 /* If this is an X2APIC WRMSR access, update the APIC state as well. */
6617 if ( pCtx->ecx >= MSR_IA32_X2APIC_START
6618 && pCtx->ecx <= MSR_IA32_X2APIC_END)
6619 {
6620 /*
6621 * We've already saved the APIC related guest-state (TPR) in hmR0SvmPostRunGuest(). When full APIC register
6622 * virtualization is implemented we'll have to make sure APIC state is saved from the VMCB before
6623 * EMInterpretWrmsr() changes it.
6624 */
6625 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
6626 }
6627 else
6628 {
6629 switch (pCtx->ecx)
6630 {
6631 case MSR_K6_EFER: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_EFER_MSR); break;
6632 case MSR_IA32_TSC: pSvmTransient->fUpdateTscOffsetting = true; break;
6633 case MSR_K8_FS_BASE:
6634 case MSR_K8_GS_BASE: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS); break;
6635 case MSR_IA32_SYSENTER_CS: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_CS_MSR); break;
6636 case MSR_IA32_SYSENTER_EIP: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_EIP_MSR); break;
6637 case MSR_IA32_SYSENTER_ESP: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_ESP_MSR); break;
6638 }
6639 }
6640 }
6641 }
6642 else
6643 {
6644 /* MSR Read access. */
6645 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
6646 Assert(pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_READ);
6647 Log4(("MSR Read: idMsr=%#RX32\n", pCtx->ecx));
6648
6649 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6650 if (fSupportsNextRipSave)
6651 {
6652 rc = EMInterpretRdmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
6653 if (RT_LIKELY(rc == VINF_SUCCESS))
6654 {
6655 pCtx->rip = pVmcb->ctrl.u64NextRIP;
6656 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6657 }
6658 else
6659 AssertMsg( rc == VERR_EM_INTERPRETER
6660 || rc == VINF_CPUM_R3_MSR_READ, ("hmR0SvmExitMsr: EMInterpretRdmsr failed rc=%Rrc\n", rc));
6661 }
6662 else
6663 {
6664 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0));
6665 if (RT_UNLIKELY(rc != VINF_SUCCESS))
6666 {
6667 AssertMsg( rc == VERR_EM_INTERPRETER
6668 || rc == VINF_CPUM_R3_MSR_READ, ("hmR0SvmExitMsr: RdMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
6669 }
6670 /* RIP updated by EMInterpretInstruction(). */
6671 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6672 }
6673 }
6674
6675 /* RIP has been updated by EMInterpret[Rd|Wr]msr() or EMInterpretInstruction(). */
6676 return rc;
6677}
6678
6679
6680/**
6681 * \#VMEXIT handler for DRx read (SVM_EXIT_READ_DRx). Conditional \#VMEXIT.
6682 */
6683HMSVM_EXIT_DECL hmR0SvmExitReadDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6684{
6685 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6686 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
6687
6688 /** @todo Stepping with nested-guest. */
6689 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
6690 {
6691 /* We should -not- get this #VMEXIT if the guest's debug registers were active. */
6692 if (pSvmTransient->fWasGuestDebugStateActive)
6693 {
6694 AssertMsgFailed(("hmR0SvmExitReadDRx: Unexpected exit %#RX32\n", (uint32_t)pSvmTransient->u64ExitCode));
6695 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
6696 return VERR_SVM_UNEXPECTED_EXIT;
6697 }
6698
6699 /*
6700 * Lazy DR0-3 loading.
6701 */
6702 if (!pSvmTransient->fWasHyperDebugStateActive)
6703 {
6704 Assert(!DBGFIsStepping(pVCpu)); Assert(!pVCpu->hm.s.fSingleInstruction);
6705 Log5(("hmR0SvmExitReadDRx: Lazy loading guest debug registers\n"));
6706
6707 /* Don't intercept DRx read and writes. */
6708 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
6709 pVmcb->ctrl.u16InterceptRdDRx = 0;
6710 pVmcb->ctrl.u16InterceptWrDRx = 0;
6711 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
6712
6713 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
6714 VMMRZCallRing3Disable(pVCpu);
6715 HM_DISABLE_PREEMPT();
6716
6717 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
6718 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
6719 Assert(CPUMIsGuestDebugStateActive(pVCpu) || HC_ARCH_BITS == 32);
6720
6721 HM_RESTORE_PREEMPT();
6722 VMMRZCallRing3Enable(pVCpu);
6723
6724 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
6725 return VINF_SUCCESS;
6726 }
6727 }
6728
6729 /*
6730 * Interpret the read/writing of DRx.
6731 */
6732 /** @todo Decode assist. */
6733 VBOXSTRICTRC rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
6734 Log5(("hmR0SvmExitReadDRx: Emulated DRx access: rc=%Rrc\n", VBOXSTRICTRC_VAL(rc)));
6735 if (RT_LIKELY(rc == VINF_SUCCESS))
6736 {
6737 /* Not necessary for read accesses but whatever doesn't hurt for now, will be fixed with decode assist. */
6738 /** @todo CPUM should set this flag! */
6739 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);
6740 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6741 }
6742 else
6743 Assert(rc == VERR_EM_INTERPRETER);
6744 return VBOXSTRICTRC_TODO(rc);
6745}
6746
6747
6748/**
6749 * \#VMEXIT handler for DRx write (SVM_EXIT_WRITE_DRx). Conditional \#VMEXIT.
6750 */
6751HMSVM_EXIT_DECL hmR0SvmExitWriteDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6752{
6753 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6754 /* For now it's the same since we interpret the instruction anyway. Will change when using of Decode Assist is implemented. */
6755 int rc = hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
6756 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
6757 STAM_COUNTER_DEC(&pVCpu->hm.s.StatExitDRxRead);
6758 return rc;
6759}
6760
6761
6762/**
6763 * \#VMEXIT handler for XCRx write (SVM_EXIT_XSETBV). Conditional \#VMEXIT.
6764 */
6765HMSVM_EXIT_DECL hmR0SvmExitXsetbv(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6766{
6767 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6768
6769 /** @todo decode assists... */
6770 VBOXSTRICTRC rcStrict = IEMExecOne(pVCpu);
6771 if (rcStrict == VINF_IEM_RAISED_XCPT)
6772 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
6773
6774 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pCtx->cr4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
6775 Log4(("hmR0SvmExitXsetbv: New XCR0=%#RX64 fLoadSaveGuestXcr0=%d (cr4=%RX64) rcStrict=%Rrc\n",
6776 pCtx->aXcr[0], pVCpu->hm.s.fLoadSaveGuestXcr0, pCtx->cr4, VBOXSTRICTRC_VAL(rcStrict)));
6777
6778 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6779 return VBOXSTRICTRC_TODO(rcStrict);
6780}
6781
6782
6783/**
6784 * \#VMEXIT handler for I/O instructions (SVM_EXIT_IOIO). Conditional \#VMEXIT.
6785 */
6786HMSVM_EXIT_DECL hmR0SvmExitIOInstr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6787{
6788 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6789
6790 /* I/O operation lookup arrays. */
6791 static uint32_t const s_aIOSize[8] = { 0, 1, 2, 0, 4, 0, 0, 0 }; /* Size of the I/O accesses in bytes. */
6792 static uint32_t const s_aIOOpAnd[8] = { 0, 0xff, 0xffff, 0, 0xffffffff, 0, 0, 0 }; /* AND masks for saving
6793 the result (in AL/AX/EAX). */
6794 Log4(("hmR0SvmExitIOInstr: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
6795
6796 PVM pVM = pVCpu->CTX_SUFF(pVM);
6797 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6798
6799 /* Refer AMD spec. 15.10.2 "IN and OUT Behaviour" and Figure 15-2. "EXITINFO1 for IOIO Intercept" for the format. */
6800 SVMIOIOEXITINFO IoExitInfo;
6801 IoExitInfo.u = (uint32_t)pVmcb->ctrl.u64ExitInfo1;
6802 uint32_t uIOWidth = (IoExitInfo.u >> 4) & 0x7;
6803 uint32_t cbValue = s_aIOSize[uIOWidth];
6804 uint32_t uAndVal = s_aIOOpAnd[uIOWidth];
6805
6806 if (RT_UNLIKELY(!cbValue))
6807 {
6808 AssertMsgFailed(("hmR0SvmExitIOInstr: Invalid IO operation. uIOWidth=%u\n", uIOWidth));
6809 return VERR_EM_INTERPRETER;
6810 }
6811
6812 VBOXSTRICTRC rcStrict;
6813 bool fUpdateRipAlready = false;
6814 if (IoExitInfo.n.u1Str)
6815 {
6816#ifdef VBOX_WITH_2ND_IEM_STEP
6817 /* INS/OUTS - I/O String instruction. */
6818 /** @todo Huh? why can't we use the segment prefix information given by AMD-V
6819 * in EXITINFO1? Investigate once this thing is up and running. */
6820 Log4(("CS:RIP=%04x:%08RX64 %#06x/%u %c str\n", pCtx->cs.Sel, pCtx->rip, IoExitInfo.n.u16Port, cbValue,
6821 IoExitInfo.n.u1Type == SVM_IOIO_WRITE ? 'w' : 'r'));
6822 AssertReturn(pCtx->dx == IoExitInfo.n.u16Port, VERR_SVM_IPE_2);
6823 static IEMMODE const s_aenmAddrMode[8] =
6824 {
6825 (IEMMODE)-1, IEMMODE_16BIT, IEMMODE_32BIT, (IEMMODE)-1, IEMMODE_64BIT, (IEMMODE)-1, (IEMMODE)-1, (IEMMODE)-1
6826 };
6827 IEMMODE enmAddrMode = s_aenmAddrMode[(IoExitInfo.u >> 7) & 0x7];
6828 if (enmAddrMode != (IEMMODE)-1)
6829 {
6830 uint64_t cbInstr = pVmcb->ctrl.u64ExitInfo2 - pCtx->rip;
6831 if (cbInstr <= 15 && cbInstr >= 1)
6832 {
6833 Assert(cbInstr >= 1U + IoExitInfo.n.u1Rep);
6834 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
6835 {
6836 /* Don't know exactly how to detect whether u3Seg is valid, currently
6837 only enabling it for Bulldozer and later with NRIP. OS/2 broke on
6838 2384 Opterons when only checking NRIP. */
6839 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6840 if ( fSupportsNextRipSave
6841 && pVM->cpum.ro.GuestFeatures.enmMicroarch >= kCpumMicroarch_AMD_15h_First)
6842 {
6843 AssertMsg(IoExitInfo.n.u3Seg == X86_SREG_DS || cbInstr > 1U + IoExitInfo.n.u1Rep,
6844 ("u32Seg=%d cbInstr=%d u1REP=%d", IoExitInfo.n.u3Seg, cbInstr, IoExitInfo.n.u1Rep));
6845 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1Rep, (uint8_t)cbInstr,
6846 IoExitInfo.n.u3Seg, true /*fIoChecked*/);
6847 }
6848 else if (cbInstr == 1U + IoExitInfo.n.u1Rep)
6849 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1Rep, (uint8_t)cbInstr,
6850 X86_SREG_DS, true /*fIoChecked*/);
6851 else
6852 rcStrict = IEMExecOne(pVCpu);
6853 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
6854 }
6855 else
6856 {
6857 AssertMsg(IoExitInfo.n.u3Seg == X86_SREG_ES /*=0*/, ("%#x\n", IoExitInfo.n.u3Seg));
6858 rcStrict = IEMExecStringIoRead(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1Rep, (uint8_t)cbInstr,
6859 true /*fIoChecked*/);
6860 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
6861 }
6862 }
6863 else
6864 {
6865 AssertMsgFailed(("rip=%RX64 nrip=%#RX64 cbInstr=%#RX64\n", pCtx->rip, pVmcb->ctrl.u64ExitInfo2, cbInstr));
6866 rcStrict = IEMExecOne(pVCpu);
6867 }
6868 }
6869 else
6870 {
6871 AssertMsgFailed(("IoExitInfo=%RX64\n", IoExitInfo.u));
6872 rcStrict = IEMExecOne(pVCpu);
6873 }
6874 fUpdateRipAlready = true;
6875
6876#else
6877 /* INS/OUTS - I/O String instruction. */
6878 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
6879
6880 /** @todo Huh? why can't we use the segment prefix information given by AMD-V
6881 * in EXITINFO1? Investigate once this thing is up and running. */
6882
6883 rcStrict = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL);
6884 if (rcStrict == VINF_SUCCESS)
6885 {
6886 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
6887 {
6888 rcStrict = IOMInterpretOUTSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
6889 (DISCPUMODE)pDis->uAddrMode, cbValue);
6890 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
6891 }
6892 else
6893 {
6894 rcStrict = IOMInterpretINSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
6895 (DISCPUMODE)pDis->uAddrMode, cbValue);
6896 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
6897 }
6898 }
6899 else
6900 rcStrict = VINF_EM_RAW_EMULATE_INSTR;
6901#endif
6902 }
6903 else
6904 {
6905 /* IN/OUT - I/O instruction. */
6906 Assert(!IoExitInfo.n.u1Rep);
6907
6908 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
6909 {
6910 rcStrict = IOMIOPortWrite(pVM, pVCpu, IoExitInfo.n.u16Port, pCtx->eax & uAndVal, cbValue);
6911 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
6912 }
6913 else
6914 {
6915 uint32_t u32Val = 0;
6916 rcStrict = IOMIOPortRead(pVM, pVCpu, IoExitInfo.n.u16Port, &u32Val, cbValue);
6917 if (IOM_SUCCESS(rcStrict))
6918 {
6919 /* Save result of I/O IN instr. in AL/AX/EAX. */
6920 /** @todo r=bird: 32-bit op size should clear high bits of rax! */
6921 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
6922 }
6923 else if (rcStrict == VINF_IOM_R3_IOPORT_READ)
6924 HMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, cbValue);
6925
6926 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
6927 }
6928 }
6929
6930 if (IOM_SUCCESS(rcStrict))
6931 {
6932 /* AMD-V saves the RIP of the instruction following the IO instruction in EXITINFO2. */
6933 if (!fUpdateRipAlready)
6934 pCtx->rip = pVmcb->ctrl.u64ExitInfo2;
6935
6936 /*
6937 * If any I/O breakpoints are armed, we need to check if one triggered
6938 * and take appropriate action.
6939 * Note that the I/O breakpoint type is undefined if CR4.DE is 0.
6940 */
6941 /** @todo Optimize away the DBGFBpIsHwIoArmed call by having DBGF tell the
6942 * execution engines about whether hyper BPs and such are pending. */
6943 uint32_t const uDr7 = pCtx->dr[7];
6944 if (RT_UNLIKELY( ( (uDr7 & X86_DR7_ENABLED_MASK)
6945 && X86_DR7_ANY_RW_IO(uDr7)
6946 && (pCtx->cr4 & X86_CR4_DE))
6947 || DBGFBpIsHwIoArmed(pVM)))
6948 {
6949 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
6950 VMMRZCallRing3Disable(pVCpu);
6951 HM_DISABLE_PREEMPT();
6952
6953 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
6954 CPUMR0DebugStateMaybeSaveGuest(pVCpu, false /*fDr6*/);
6955
6956 VBOXSTRICTRC rcStrict2 = DBGFBpCheckIo(pVM, pVCpu, pCtx, IoExitInfo.n.u16Port, cbValue);
6957 if (rcStrict2 == VINF_EM_RAW_GUEST_TRAP)
6958 {
6959 /* Raise #DB. */
6960 pVmcb->guest.u64DR6 = pCtx->dr[6];
6961 pVmcb->guest.u64DR7 = pCtx->dr[7];
6962 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
6963 hmR0SvmSetPendingXcptDB(pVCpu);
6964 }
6965 /* rcStrict is VINF_SUCCESS, VINF_IOM_R3_IOPORT_COMMIT_WRITE, or in [VINF_EM_FIRST..VINF_EM_LAST],
6966 however we can ditch VINF_IOM_R3_IOPORT_COMMIT_WRITE as it has VMCPU_FF_IOM as backup. */
6967 else if ( rcStrict2 != VINF_SUCCESS
6968 && (rcStrict == VINF_SUCCESS || rcStrict2 < rcStrict))
6969 rcStrict = rcStrict2;
6970 AssertCompile(VINF_EM_LAST < VINF_IOM_R3_IOPORT_COMMIT_WRITE);
6971
6972 HM_RESTORE_PREEMPT();
6973 VMMRZCallRing3Enable(pVCpu);
6974 }
6975
6976 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6977 }
6978
6979#ifdef VBOX_STRICT
6980 if (rcStrict == VINF_IOM_R3_IOPORT_READ)
6981 Assert(IoExitInfo.n.u1Type == SVM_IOIO_READ);
6982 else if (rcStrict == VINF_IOM_R3_IOPORT_WRITE || rcStrict == VINF_IOM_R3_IOPORT_COMMIT_WRITE)
6983 Assert(IoExitInfo.n.u1Type == SVM_IOIO_WRITE);
6984 else
6985 {
6986 /** @todo r=bird: This is missing a bunch of VINF_EM_FIRST..VINF_EM_LAST
6987 * statuses, that the VMM device and some others may return. See
6988 * IOM_SUCCESS() for guidance. */
6989 AssertMsg( RT_FAILURE(rcStrict)
6990 || rcStrict == VINF_SUCCESS
6991 || rcStrict == VINF_EM_RAW_EMULATE_INSTR
6992 || rcStrict == VINF_EM_DBG_BREAKPOINT
6993 || rcStrict == VINF_EM_RAW_GUEST_TRAP
6994 || rcStrict == VINF_EM_RAW_TO_R3
6995 || rcStrict == VINF_TRPM_XCPT_DISPATCHED
6996 || rcStrict == VINF_EM_TRIPLE_FAULT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
6997 }
6998#endif
6999 return VBOXSTRICTRC_TODO(rcStrict);
7000}
7001
7002
7003/**
7004 * \#VMEXIT handler for Nested Page-faults (SVM_EXIT_NPF). Conditional \#VMEXIT.
7005 */
7006HMSVM_EXIT_DECL hmR0SvmExitNestedPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7007{
7008 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7009
7010 PVM pVM = pVCpu->CTX_SUFF(pVM);
7011 Assert(pVM->hm.s.fNestedPaging);
7012
7013 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7014
7015 /* See AMD spec. 15.25.6 "Nested versus Guest Page Faults, Fault Ordering" for VMCB details for #NPF. */
7016 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7017 RTGCPHYS GCPhysFaultAddr = pVmcb->ctrl.u64ExitInfo2;
7018 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1; /* Note! High bits in EXITINFO1 may contain additional info and are
7019 thus intentionally not copied into u32ErrCode. */
7020
7021 Log4(("#NPF at CS:RIP=%04x:%#RX64 faultaddr=%RGp errcode=%#x \n", pCtx->cs.Sel, pCtx->rip, GCPhysFaultAddr, u32ErrCode));
7022
7023 /*
7024 * TPR patching for 32-bit guests, using the reserved bit in the page tables for MMIO regions.
7025 */
7026 if ( pVM->hm.s.fTprPatchingAllowed
7027 && (GCPhysFaultAddr & PAGE_OFFSET_MASK) == XAPIC_OFF_TPR
7028 && ( !(u32ErrCode & X86_TRAP_PF_P) /* Not present */
7029 || (u32ErrCode & (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) == (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) /* MMIO page. */
7030 && !CPUMIsGuestInLongModeEx(pCtx)
7031 && !CPUMGetGuestCPL(pVCpu)
7032 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
7033 {
7034 RTGCPHYS GCPhysApicBase = APICGetBaseMsrNoCheck(pVCpu);
7035 GCPhysApicBase &= PAGE_BASE_GC_MASK;
7036
7037 if (GCPhysFaultAddr == GCPhysApicBase + XAPIC_OFF_TPR)
7038 {
7039 /* Only attempt to patch the instruction once. */
7040 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
7041 if (!pPatch)
7042 return VINF_EM_HM_PATCH_TPR_INSTR;
7043 }
7044 }
7045
7046 /*
7047 * Determine the nested paging mode.
7048 */
7049 PGMMODE enmNestedPagingMode;
7050#if HC_ARCH_BITS == 32
7051 if (CPUMIsGuestInLongModeEx(pCtx))
7052 enmNestedPagingMode = PGMMODE_AMD64_NX;
7053 else
7054#endif
7055 enmNestedPagingMode = PGMGetHostMode(pVM);
7056
7057 /*
7058 * MMIO optimization using the reserved (RSVD) bit in the guest page tables for MMIO pages.
7059 */
7060 int rc;
7061 Assert((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) != X86_TRAP_PF_RSVD);
7062 if ((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) == (X86_TRAP_PF_RSVD | X86_TRAP_PF_P))
7063 {
7064 /* If event delivery causes an MMIO #NPF, go back to instruction emulation as
7065 otherwise injecting the original pending event would most likely cause the same MMIO #NPF. */
7066 if (pVCpu->hm.s.Event.fPending)
7067 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7068
7069 VBOXSTRICTRC rc2 = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, enmNestedPagingMode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr,
7070 u32ErrCode);
7071 rc = VBOXSTRICTRC_VAL(rc2);
7072
7073 /*
7074 * If we succeed, resume guest execution.
7075 * If we fail in interpreting the instruction because we couldn't get the guest physical address
7076 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
7077 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
7078 * weird case. See @bugref{6043}.
7079 */
7080 if ( rc == VINF_SUCCESS
7081 || rc == VERR_PAGE_TABLE_NOT_PRESENT
7082 || rc == VERR_PAGE_NOT_PRESENT)
7083 {
7084 /* Successfully handled MMIO operation. */
7085 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
7086 rc = VINF_SUCCESS;
7087 }
7088 return rc;
7089 }
7090
7091 TRPMAssertXcptPF(pVCpu, GCPhysFaultAddr, u32ErrCode);
7092 rc = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, enmNestedPagingMode, u32ErrCode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr);
7093 TRPMResetTrap(pVCpu);
7094
7095 Log4(("#NPF: PGMR0Trap0eHandlerNestedPaging returned %Rrc CS:RIP=%04x:%#RX64\n", rc, pCtx->cs.Sel, pCtx->rip));
7096
7097 /*
7098 * Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}.
7099 */
7100 if ( rc == VINF_SUCCESS
7101 || rc == VERR_PAGE_TABLE_NOT_PRESENT
7102 || rc == VERR_PAGE_NOT_PRESENT)
7103 {
7104 /* We've successfully synced our shadow page tables. */
7105 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
7106 rc = VINF_SUCCESS;
7107 }
7108
7109 return rc;
7110}
7111
7112
7113/**
7114 * \#VMEXIT handler for virtual interrupt (SVM_EXIT_VINTR). Conditional
7115 * \#VMEXIT.
7116 */
7117HMSVM_EXIT_DECL hmR0SvmExitVIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7118{
7119 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7120 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
7121
7122 /* Indicate that we no longer need to #VMEXIT when the guest is ready to receive NMIs, it is now ready. */
7123 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7124 hmR0SvmClearIntWindowExiting(pVCpu, pVmcb, pCtx);
7125
7126 /* Deliver the pending interrupt via hmR0SvmEvaluatePendingEvent() and resume guest execution. */
7127 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
7128 return VINF_SUCCESS;
7129}
7130
7131
7132/**
7133 * \#VMEXIT handler for task switches (SVM_EXIT_TASK_SWITCH). Conditional
7134 * \#VMEXIT.
7135 */
7136HMSVM_EXIT_DECL hmR0SvmExitTaskSwitch(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7137{
7138 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7139
7140 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7141
7142#ifndef HMSVM_ALWAYS_TRAP_TASK_SWITCH
7143 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
7144#endif
7145
7146 /* Check if this task-switch occurred while delivering an event through the guest IDT. */
7147 if (pVCpu->hm.s.Event.fPending) /* Can happen with exceptions/NMI. See @bugref{8411}. */
7148 {
7149 /*
7150 * AMD-V provides us with the exception which caused the TS; we collect
7151 * the information in the call to hmR0SvmCheckExitDueToEventDelivery.
7152 */
7153 Log4(("hmR0SvmExitTaskSwitch: TS occurred during event delivery.\n"));
7154 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
7155 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7156 }
7157
7158 /** @todo Emulate task switch someday, currently just going back to ring-3 for
7159 * emulation. */
7160 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
7161 return VERR_EM_INTERPRETER;
7162}
7163
7164
7165/**
7166 * \#VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional \#VMEXIT.
7167 */
7168HMSVM_EXIT_DECL hmR0SvmExitVmmCall(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7169{
7170 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7171 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitVmcall);
7172
7173 bool fRipUpdated;
7174 VBOXSTRICTRC rcStrict = HMSvmVmmcall(pVCpu, pCtx, &fRipUpdated);
7175 if (RT_SUCCESS(rcStrict))
7176 {
7177 /* Only update the RIP if we're continuing guest execution and not
7178 in the case of say VINF_GIM_R3_HYPERCALL. */
7179 if ( rcStrict == VINF_SUCCESS
7180 && !fRipUpdated)
7181 {
7182 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3 /* cbInstr */);
7183 }
7184
7185 /* If the hypercall or TPR patching changes anything other than guest's general-purpose registers,
7186 we would need to reload the guest changed bits here before VM-entry. */
7187 return VBOXSTRICTRC_VAL(rcStrict);
7188 }
7189
7190 hmR0SvmSetPendingXcptUD(pVCpu);
7191 return VINF_SUCCESS;
7192}
7193
7194
7195/**
7196 * \#VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional \#VMEXIT.
7197 */
7198HMSVM_EXIT_DECL hmR0SvmExitPause(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7199{
7200 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7201 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitPause);
7202 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
7203 /** @todo The guest has likely hit a contended spinlock. We might want to
7204 * poke a schedule different guest VCPU. */
7205 return VINF_EM_RAW_INTERRUPT;
7206}
7207
7208
7209/**
7210 * \#VMEXIT handler for FERR intercept (SVM_EXIT_FERR_FREEZE). Conditional
7211 * \#VMEXIT.
7212 */
7213HMSVM_EXIT_DECL hmR0SvmExitFerrFreeze(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7214{
7215 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7216 Assert(!(pCtx->cr0 & X86_CR0_NE));
7217
7218 Log4(("hmR0SvmExitFerrFreeze: Raising IRQ 13 in response to #FERR\n"));
7219 return PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13 /* u8Irq */, 1 /* u8Level */, 0 /* uTagSrc */);
7220}
7221
7222
7223/**
7224 * \#VMEXIT handler for IRET (SVM_EXIT_IRET). Conditional \#VMEXIT.
7225 */
7226HMSVM_EXIT_DECL hmR0SvmExitIret(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7227{
7228 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7229
7230 /* Clear NMI blocking. */
7231 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
7232 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
7233
7234 /* Indicate that we no longer need to #VMEXIT when the guest is ready to receive NMIs, it is now ready. */
7235 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7236 hmR0SvmClearCtrlIntercept(pVCpu, pCtx, pVmcb, SVM_CTRL_INTERCEPT_IRET);
7237
7238 /* Deliver the pending NMI via hmR0SvmEvaluatePendingEvent() and resume guest execution. */
7239 return VINF_SUCCESS;
7240}
7241
7242
7243/**
7244 * \#VMEXIT handler for page-fault exceptions (SVM_EXIT_XCPT_14).
7245 * Conditional \#VMEXIT.
7246 */
7247HMSVM_EXIT_DECL hmR0SvmExitXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7248{
7249 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7250 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
7251
7252 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7253
7254 /* See AMD spec. 15.12.15 "#PF (Page Fault)". */
7255 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
7256 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1;
7257 RTGCUINTPTR uFaultAddress = pVmcb->ctrl.u64ExitInfo2;
7258 PVM pVM = pVCpu->CTX_SUFF(pVM);
7259
7260#if defined(HMSVM_ALWAYS_TRAP_ALL_XCPTS) || defined(HMSVM_ALWAYS_TRAP_PF)
7261 if (pVM->hm.s.fNestedPaging)
7262 {
7263 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
7264 if (!pSvmTransient->fVectoringDoublePF)
7265 {
7266 /* A genuine guest #PF, reflect it to the guest. */
7267 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
7268 Log4(("#PF: Guest page fault at %04X:%RGv FaultAddr=%RGv ErrCode=%#x\n", pCtx->cs.Sel, (RTGCPTR)pCtx->rip,
7269 uFaultAddress, u32ErrCode));
7270 }
7271 else
7272 {
7273 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
7274 hmR0SvmSetPendingXcptDF(pVCpu);
7275 Log4(("Pending #DF due to vectoring #PF. NP\n"));
7276 }
7277 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
7278 return VINF_SUCCESS;
7279 }
7280#endif
7281
7282 Assert(!pVM->hm.s.fNestedPaging);
7283
7284 /*
7285 * TPR patching shortcut for APIC TPR reads and writes; only applicable to 32-bit guests.
7286 */
7287 if ( pVM->hm.s.fTprPatchingAllowed
7288 && (uFaultAddress & 0xfff) == XAPIC_OFF_TPR
7289 && !(u32ErrCode & X86_TRAP_PF_P) /* Not present. */
7290 && !CPUMIsGuestInLongModeEx(pCtx)
7291 && !CPUMGetGuestCPL(pVCpu)
7292 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
7293 {
7294 RTGCPHYS GCPhysApicBase;
7295 GCPhysApicBase = APICGetBaseMsrNoCheck(pVCpu);
7296 GCPhysApicBase &= PAGE_BASE_GC_MASK;
7297
7298 /* Check if the page at the fault-address is the APIC base. */
7299 RTGCPHYS GCPhysPage;
7300 int rc2 = PGMGstGetPage(pVCpu, (RTGCPTR)uFaultAddress, NULL /* pfFlags */, &GCPhysPage);
7301 if ( rc2 == VINF_SUCCESS
7302 && GCPhysPage == GCPhysApicBase)
7303 {
7304 /* Only attempt to patch the instruction once. */
7305 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
7306 if (!pPatch)
7307 return VINF_EM_HM_PATCH_TPR_INSTR;
7308 }
7309 }
7310
7311 Log4(("#PF: uFaultAddress=%#RX64 CS:RIP=%#04x:%#RX64 u32ErrCode %#RX32 cr3=%#RX64\n", uFaultAddress, pCtx->cs.Sel,
7312 pCtx->rip, u32ErrCode, pCtx->cr3));
7313
7314 /* If it's a vectoring #PF, emulate injecting the original event injection as PGMTrap0eHandler() is incapable
7315 of differentiating between instruction emulation and event injection that caused a #PF. See @bugref{6607}. */
7316 if (pSvmTransient->fVectoringPF)
7317 {
7318 Assert(pVCpu->hm.s.Event.fPending);
7319 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7320 }
7321
7322 TRPMAssertXcptPF(pVCpu, uFaultAddress, u32ErrCode);
7323 int rc = PGMTrap0eHandler(pVCpu, u32ErrCode, CPUMCTX2CORE(pCtx), (RTGCPTR)uFaultAddress);
7324
7325 Log4(("#PF rc=%Rrc\n", rc));
7326
7327 if (rc == VINF_SUCCESS)
7328 {
7329 /* Successfully synced shadow pages tables or emulated an MMIO instruction. */
7330 TRPMResetTrap(pVCpu);
7331 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
7332 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
7333 return rc;
7334 }
7335 else if (rc == VINF_EM_RAW_GUEST_TRAP)
7336 {
7337 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
7338
7339 if (!pSvmTransient->fVectoringDoublePF)
7340 {
7341 /* It's a guest page fault and needs to be reflected to the guest. */
7342 u32ErrCode = TRPMGetErrorCode(pVCpu); /* The error code might have been changed. */
7343 TRPMResetTrap(pVCpu);
7344 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
7345 }
7346 else
7347 {
7348 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
7349 TRPMResetTrap(pVCpu);
7350 hmR0SvmSetPendingXcptDF(pVCpu);
7351 Log4(("#PF: Pending #DF due to vectoring #PF\n"));
7352 }
7353
7354 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
7355 return VINF_SUCCESS;
7356 }
7357
7358 TRPMResetTrap(pVCpu);
7359 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
7360 return rc;
7361}
7362
7363
7364/**
7365 * \#VMEXIT handler for undefined opcode (SVM_EXIT_XCPT_6).
7366 * Conditional \#VMEXIT.
7367 */
7368HMSVM_EXIT_DECL hmR0SvmExitXcptUD(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7369{
7370 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7371 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
7372
7373 /* Paranoia; Ensure we cannot be called as a result of event delivery. */
7374 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
7375 Assert(!pVmcb->ctrl.ExitIntInfo.n.u1Valid); NOREF(pVmcb);
7376
7377 int rc = VERR_SVM_UNEXPECTED_XCPT_EXIT;
7378 if (pVCpu->hm.s.fGIMTrapXcptUD)
7379 {
7380 uint8_t cbInstr = 0;
7381 VBOXSTRICTRC rcStrict = GIMXcptUD(pVCpu, pCtx, NULL /* pDis */, &cbInstr);
7382 if (rcStrict == VINF_SUCCESS)
7383 {
7384 /* #UD #VMEXIT does not have valid NRIP information, manually advance RIP. See @bugref{7270#c170}. */
7385 hmR0SvmAdvanceRipDumb(pVCpu, pCtx, cbInstr);
7386 rc = VINF_SUCCESS;
7387 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
7388 }
7389 else if (rcStrict == VINF_GIM_HYPERCALL_CONTINUING)
7390 rc = VINF_SUCCESS;
7391 else if (rcStrict == VINF_GIM_R3_HYPERCALL)
7392 rc = VINF_GIM_R3_HYPERCALL;
7393 else
7394 Assert(RT_FAILURE(VBOXSTRICTRC_VAL(rcStrict)));
7395 }
7396
7397 /* If the GIM #UD exception handler didn't succeed for some reason or wasn't needed, raise #UD. */
7398 if (RT_FAILURE(rc))
7399 {
7400 hmR0SvmSetPendingXcptUD(pVCpu);
7401 rc = VINF_SUCCESS;
7402 }
7403
7404 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD);
7405 return rc;
7406}
7407
7408
7409/**
7410 * \#VMEXIT handler for math-fault exceptions (SVM_EXIT_XCPT_16).
7411 * Conditional \#VMEXIT.
7412 */
7413HMSVM_EXIT_DECL hmR0SvmExitXcptMF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7414{
7415 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7416
7417 /* Paranoia; Ensure we cannot be called as a result of event delivery. */
7418 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7419 Assert(!pVmcb->ctrl.ExitIntInfo.n.u1Valid); NOREF(pVmcb);
7420
7421 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
7422
7423 if (!(pCtx->cr0 & X86_CR0_NE))
7424 {
7425 PVM pVM = pVCpu->CTX_SUFF(pVM);
7426 PDISSTATE pDis = &pVCpu->hm.s.DisState;
7427 unsigned cbOp;
7428 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
7429 if (RT_SUCCESS(rc))
7430 {
7431 /* Convert a #MF into a FERR -> IRQ 13. See @bugref{6117}. */
7432 rc = PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13 /* u8Irq */, 1 /* u8Level */, 0 /* uTagSrc */);
7433 if (RT_SUCCESS(rc))
7434 pCtx->rip += cbOp;
7435 }
7436 else
7437 Log4(("hmR0SvmExitXcptMF: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
7438 return rc;
7439 }
7440
7441 hmR0SvmSetPendingXcptMF(pVCpu);
7442 return VINF_SUCCESS;
7443}
7444
7445
7446/**
7447 * \#VMEXIT handler for debug exceptions (SVM_EXIT_XCPT_1). Conditional
7448 * \#VMEXIT.
7449 */
7450HMSVM_EXIT_DECL hmR0SvmExitXcptDB(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7451{
7452 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7453
7454 /* If this #DB is the result of delivering an event, go back to the interpreter. */
7455 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7456 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
7457 {
7458 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingInterpret);
7459 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7460 }
7461
7462 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
7463
7464 /* This can be a fault-type #DB (instruction breakpoint) or a trap-type #DB (data breakpoint). However, for both cases
7465 DR6 and DR7 are updated to what the exception handler expects. See AMD spec. 15.12.2 "#DB (Debug)". */
7466 PVM pVM = pVCpu->CTX_SUFF(pVM);
7467 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
7468 int rc = DBGFRZTrap01Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx), pVmcb->guest.u64DR6, pVCpu->hm.s.fSingleInstruction);
7469 if (rc == VINF_EM_RAW_GUEST_TRAP)
7470 {
7471 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> guest trap\n", pVmcb->guest.u64DR6));
7472 if (CPUMIsHyperDebugStateActive(pVCpu))
7473 CPUMSetGuestDR6(pVCpu, CPUMGetGuestDR6(pVCpu) | pVmcb->guest.u64DR6);
7474
7475 /* Reflect the exception back to the guest. */
7476 hmR0SvmSetPendingXcptDB(pVCpu);
7477 rc = VINF_SUCCESS;
7478 }
7479
7480 /*
7481 * Update DR6.
7482 */
7483 if (CPUMIsHyperDebugStateActive(pVCpu))
7484 {
7485 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> %Rrc\n", pVmcb->guest.u64DR6, rc));
7486 pVmcb->guest.u64DR6 = X86_DR6_INIT_VAL;
7487 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
7488 }
7489 else
7490 {
7491 AssertMsg(rc == VINF_SUCCESS, ("rc=%Rrc\n", rc));
7492 Assert(!pVCpu->hm.s.fSingleInstruction && !DBGFIsStepping(pVCpu));
7493 }
7494
7495 return rc;
7496}
7497
7498
7499/**
7500 * \#VMEXIT handler for alignment check exceptions (SVM_EXIT_XCPT_17).
7501 * Conditional \#VMEXIT.
7502 */
7503HMSVM_EXIT_DECL hmR0SvmExitXcptAC(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7504{
7505 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7506
7507 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7508
7509 SVMEVENT Event;
7510 Event.u = 0;
7511 Event.n.u1Valid = 1;
7512 Event.n.u3Type = SVM_EVENT_EXCEPTION;
7513 Event.n.u8Vector = X86_XCPT_AC;
7514 Event.n.u1ErrorCodeValid = 1;
7515 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
7516 return VINF_SUCCESS;
7517}
7518
7519
7520/**
7521 * \#VMEXIT handler for breakpoint exceptions (SVM_EXIT_XCPT_3).
7522 * Conditional \#VMEXIT.
7523 */
7524HMSVM_EXIT_DECL hmR0SvmExitXcptBP(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7525{
7526 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7527
7528 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7529
7530 int rc = DBGFRZTrap03Handler(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
7531 if (rc == VINF_EM_RAW_GUEST_TRAP)
7532 {
7533 SVMEVENT Event;
7534 Event.u = 0;
7535 Event.n.u1Valid = 1;
7536 Event.n.u3Type = SVM_EVENT_EXCEPTION;
7537 Event.n.u8Vector = X86_XCPT_BP;
7538 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
7539 }
7540
7541 Assert(rc == VINF_SUCCESS || rc == VINF_EM_RAW_GUEST_TRAP || rc == VINF_EM_DBG_BREAKPOINT);
7542 return rc;
7543}
7544
7545
7546#if defined(HMSVM_ALWAYS_TRAP_ALL_XCPTS) || defined(VBOX_WITH_NESTED_HWVIRT)
7547/**
7548 * \#VMEXIT handler for generic exceptions. Conditional \#VMEXIT.
7549 */
7550HMSVM_EXIT_DECL hmR0SvmExitXcptGeneric(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7551{
7552 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7553
7554 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7555
7556 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7557 uint8_t const uVector = pVmcb->ctrl.u64ExitCode - SVM_EXIT_XCPT_0;
7558 uint32_t const uErrCode = pVmcb->ctrl.u64ExitInfo1;
7559 Assert(pSvmTransient->u64ExitCode == pVmcb->ctrl.u64ExitCode);
7560 Assert(uVector <= X86_XCPT_LAST);
7561 Log4(("hmR0SvmExitXcptGeneric: uVector=%#x uErrCode=%u\n", uVector, uErrCode));
7562
7563 SVMEVENT Event;
7564 Event.u = 0;
7565 Event.n.u1Valid = 1;
7566 Event.n.u3Type = SVM_EVENT_EXCEPTION;
7567 Event.n.u8Vector = uVector;
7568 switch (uVector)
7569 {
7570 /* Shouldn't be here for reflecting #PFs (among other things, the fault address isn't passed along). */
7571 case X86_XCPT_PF: AssertMsgFailed(("hmR0SvmExitXcptGeneric: Unexpected exception")); return VERR_SVM_IPE_5;
7572 case X86_XCPT_DF:
7573 case X86_XCPT_TS:
7574 case X86_XCPT_NP:
7575 case X86_XCPT_SS:
7576 case X86_XCPT_GP:
7577 case X86_XCPT_AC:
7578 {
7579 Event.n.u1ErrorCodeValid = 1;
7580 Event.n.u32ErrorCode = uErrCode;
7581 break;
7582 }
7583 }
7584
7585 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
7586 return VINF_SUCCESS;
7587}
7588#endif
7589
7590#ifdef VBOX_WITH_NESTED_HWVIRT
7591/**
7592 * \#VMEXIT handler for #PF occuring while in nested-guest execution
7593 * (SVM_EXIT_XCPT_14). Conditional \#VMEXIT.
7594 */
7595HMSVM_EXIT_DECL hmR0SvmExitXcptPFNested(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7596{
7597 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7598
7599 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7600
7601 /* See AMD spec. 15.12.15 "#PF (Page Fault)". */
7602 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7603 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1;
7604 uint64_t const uFaultAddress = pVmcb->ctrl.u64ExitInfo2;
7605
7606 Log4(("#PFNested: uFaultAddress=%#RX64 CS:RIP=%#04x:%#RX64 u32ErrCode=%#RX32 CR3=%#RX64\n", uFaultAddress, pCtx->cs.Sel,
7607 pCtx->rip, u32ErrCode, pCtx->cr3));
7608
7609 /* If it's a vectoring #PF, emulate injecting the original event injection as PGMTrap0eHandler() is incapable
7610 of differentiating between instruction emulation and event injection that caused a #PF. See @bugref{6607}. */
7611 if (pSvmTransient->fVectoringPF)
7612 {
7613 Assert(pVCpu->hm.s.Event.fPending);
7614 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7615 }
7616
7617 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
7618
7619 TRPMAssertXcptPF(pVCpu, uFaultAddress, u32ErrCode);
7620 int rc = PGMTrap0eHandler(pVCpu, u32ErrCode, CPUMCTX2CORE(pCtx), (RTGCPTR)uFaultAddress);
7621
7622 Log4(("#PFNested: rc=%Rrc\n", rc));
7623
7624 if (rc == VINF_SUCCESS)
7625 {
7626 /* Successfully synced shadow pages tables or emulated an MMIO instruction. */
7627 TRPMResetTrap(pVCpu);
7628 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
7629 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
7630 return rc;
7631 }
7632
7633 if (rc == VINF_EM_RAW_GUEST_TRAP)
7634 {
7635 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
7636
7637 if (!pSvmTransient->fVectoringDoublePF)
7638 {
7639 /* It's a nested-guest page fault and needs to be reflected to the nested-guest. */
7640 u32ErrCode = TRPMGetErrorCode(pVCpu); /* The error code might have been changed. */
7641 TRPMResetTrap(pVCpu);
7642 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
7643 }
7644 else
7645 {
7646 /* A nested-guest page-fault occurred during delivery of a page-fault. Inject #DF. */
7647 TRPMResetTrap(pVCpu);
7648 hmR0SvmSetPendingXcptDF(pVCpu);
7649 Log4(("#PF: Pending #DF due to vectoring #PF\n"));
7650 }
7651
7652 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
7653 return VINF_SUCCESS;
7654 }
7655
7656 TRPMResetTrap(pVCpu);
7657 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
7658 return rc;
7659}
7660
7661
7662/**
7663 * \#VMEXIT handler for CLGI (SVM_EXIT_CLGI). Conditional \#VMEXIT.
7664 */
7665HMSVM_EXIT_DECL hmR0SvmExitClgi(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7666{
7667 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7668
7669#ifdef VBOX_STRICT
7670 PCSVMVMCB pVmcbTmp = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7671 Assert(pVmcbTmp);
7672 Assert(!pVmcbTmp->ctrl.IntCtrl.n.u1VGifEnable);
7673 RT_NOREF(pVmcbTmp);
7674#endif
7675
7676 /** @todo Stat. */
7677 /* STAM_COUNTER_INC(&pVCpu->hm.s.StatExitClgi); */
7678 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7679 VBOXSTRICTRC rcStrict = IEMExecDecodedClgi(pVCpu, cbInstr);
7680 return VBOXSTRICTRC_VAL(rcStrict);
7681}
7682
7683
7684/**
7685 * \#VMEXIT handler for STGI (SVM_EXIT_STGI). Conditional \#VMEXIT.
7686 */
7687HMSVM_EXIT_DECL hmR0SvmExitStgi(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7688{
7689 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7690
7691 /*
7692 * When VGIF is not used we always intercept STGI instructions. When VGIF is used,
7693 * we only intercept STGI when events are pending for GIF to become 1.
7694 */
7695 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7696 if (pVmcb->ctrl.IntCtrl.n.u1VGifEnable)
7697 hmR0SvmClearCtrlIntercept(pVCpu, pCtx, pVmcb, SVM_CTRL_INTERCEPT_STGI);
7698
7699 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7700 VBOXSTRICTRC rcStrict = IEMExecDecodedStgi(pVCpu, cbInstr);
7701 return VBOXSTRICTRC_VAL(rcStrict);
7702}
7703
7704
7705/**
7706 * \#VMEXIT handler for VMLOAD (SVM_EXIT_VMLOAD). Conditional \#VMEXIT.
7707 */
7708HMSVM_EXIT_DECL hmR0SvmExitVmload(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7709{
7710 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7711
7712#ifdef VBOX_STRICT
7713 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7714 Assert(pVmcb);
7715 Assert(!pVmcb->ctrl.LbrVirt.n.u1VirtVmsaveVmload);
7716 RT_NOREF(pVmcb);
7717#endif
7718
7719 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7720 VBOXSTRICTRC rcStrict = IEMExecDecodedVmload(pVCpu, cbInstr);
7721 if (rcStrict == VINF_SUCCESS)
7722 {
7723 /* We skip flagging changes made to LSTAR, STAR, SFMASK and other MSRs as they are always re-loaded. */
7724 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS
7725 | HM_CHANGED_GUEST_TR
7726 | HM_CHANGED_GUEST_LDTR);
7727 }
7728 return VBOXSTRICTRC_VAL(rcStrict);
7729}
7730
7731
7732/**
7733 * \#VMEXIT handler for VMSAVE (SVM_EXIT_VMSAVE). Conditional \#VMEXIT.
7734 */
7735HMSVM_EXIT_DECL hmR0SvmExitVmsave(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7736{
7737 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7738
7739#ifdef VBOX_STRICT
7740 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7741 Assert(pVmcb);
7742 Assert(!pVmcb->ctrl.LbrVirt.n.u1VirtVmsaveVmload);
7743 RT_NOREF(pVmcb);
7744#endif
7745
7746 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7747 VBOXSTRICTRC rcStrict = IEMExecDecodedVmsave(pVCpu, cbInstr);
7748 return VBOXSTRICTRC_VAL(rcStrict);
7749}
7750
7751
7752/**
7753 * \#VMEXIT handler for INVLPGA (SVM_EXIT_INVLPGA). Conditional \#VMEXIT.
7754 */
7755HMSVM_EXIT_DECL hmR0SvmExitInvlpga(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7756{
7757 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7758 /** @todo Stat. */
7759 /* STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpga); */
7760 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7761 VBOXSTRICTRC rcStrict = IEMExecDecodedInvlpga(pVCpu, cbInstr);
7762 return VBOXSTRICTRC_VAL(rcStrict);
7763}
7764
7765
7766/**
7767 * \#VMEXIT handler for STGI (SVM_EXIT_VMRUN). Conditional \#VMEXIT.
7768 */
7769HMSVM_EXIT_DECL hmR0SvmExitVmrun(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7770{
7771 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7772
7773 VBOXSTRICTRC rcStrict;
7774 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7775 rcStrict = IEMExecDecodedVmrun(pVCpu, cbInstr);
7776 Log4(("IEMExecDecodedVmrun: returned %d\n", VBOXSTRICTRC_VAL(rcStrict)));
7777 if (rcStrict == VINF_SUCCESS)
7778 {
7779 rcStrict = VINF_SVM_VMRUN;
7780 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
7781 }
7782 return VBOXSTRICTRC_VAL(rcStrict);
7783}
7784
7785
7786/**
7787 * Nested-guest \#VMEXIT handler for debug exceptions (SVM_EXIT_XCPT_1).
7788 * Unconditional \#VMEXIT.
7789 */
7790HMSVM_EXIT_DECL hmR0SvmNestedExitXcptDB(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7791{
7792 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7793
7794 /* If this #DB is the result of delivering an event, go back to the interpreter. */
7795 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7796 if (pVCpu->hm.s.Event.fPending)
7797 {
7798 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingInterpret);
7799 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7800 }
7801
7802 hmR0SvmSetPendingXcptDB(pVCpu);
7803 return VINF_SUCCESS;
7804}
7805
7806
7807/**
7808 * Nested-guest \#VMEXIT handler for breakpoint exceptions (SVM_EXIT_XCPT_3).
7809 * Conditional \#VMEXIT.
7810 */
7811HMSVM_EXIT_DECL hmR0SvmNestedExitXcptBP(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7812{
7813 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7814
7815 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7816
7817 SVMEVENT Event;
7818 Event.u = 0;
7819 Event.n.u1Valid = 1;
7820 Event.n.u3Type = SVM_EVENT_EXCEPTION;
7821 Event.n.u8Vector = X86_XCPT_BP;
7822 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
7823 return VINF_SUCCESS;
7824}
7825
7826#endif /* VBOX_WITH_NESTED_HWVIRT */
7827
7828
7829/** @} */
7830
Note: See TracBrowser for help on using the repository browser.

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