VirtualBox

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

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

VMM/HM: Nested hw.virt: Fix the issue with preserving reserved bits across VMRUN/VM-exit.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 306.9 KB
Line 
1/* $Id: HMSVMR0.cpp 71933 2018-04-20 10:54:01Z vboxsync $ */
2/** @file
3 * HM SVM (AMD-V) - Host Context Ring-0.
4 */
5
6/*
7 * Copyright (C) 2013-2017 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_HM
23#define VMCPU_INCL_CPUM_GST_CTX
24#include <iprt/asm-amd64-x86.h>
25#include <iprt/thread.h>
26
27#include <VBox/vmm/pdmapi.h>
28#include <VBox/vmm/dbgf.h>
29#include <VBox/vmm/iem.h>
30#include <VBox/vmm/iom.h>
31#include <VBox/vmm/tm.h>
32#include <VBox/vmm/gim.h>
33#include <VBox/vmm/apic.h>
34#include "HMInternal.h"
35#include <VBox/vmm/vm.h>
36#include "HMSVMR0.h"
37#include "dtrace/VBoxVMM.h"
38
39#define HMSVM_USE_IEM_EVENT_REFLECTION
40#ifdef DEBUG_ramshankar
41# define HMSVM_SYNC_FULL_GUEST_STATE
42# define HMSVM_SYNC_FULL_NESTED_GUEST_STATE
43# define HMSVM_ALWAYS_TRAP_ALL_XCPTS
44# define HMSVM_ALWAYS_TRAP_PF
45# define HMSVM_ALWAYS_TRAP_TASK_SWITCH
46#endif
47
48
49/*********************************************************************************************************************************
50* Defined Constants And Macros *
51*********************************************************************************************************************************/
52#ifdef VBOX_WITH_STATISTICS
53# define HMSVM_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { \
54 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll); \
55 if ((u64ExitCode) == SVM_EXIT_NPF) \
56 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitReasonNpf); \
57 else \
58 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[(u64ExitCode) & MASK_EXITREASON_STAT]); \
59 } while (0)
60
61# ifdef VBOX_WITH_NESTED_HWVIRT
62# define HMSVM_NESTED_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { \
63 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll); \
64 if ((u64ExitCode) == SVM_EXIT_NPF) \
65 STAM_COUNTER_INC(&pVCpu->hm.s.StatNestedExitReasonNpf); \
66 else \
67 STAM_COUNTER_INC(&pVCpu->hm.s.paStatNestedExitReasonR0[(u64ExitCode) & MASK_EXITREASON_STAT]); \
68 } while (0)
69# endif
70#else
71# define HMSVM_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { } while (0)
72# ifdef VBOX_WITH_NESTED_HWVIRT
73# define HMSVM_NESTED_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { } while (0)
74# endif
75#endif /* !VBOX_WITH_STATISTICS */
76
77
78/** If we decide to use a function table approach this can be useful to
79 * switch to a "static DECLCALLBACK(int)". */
80#define HMSVM_EXIT_DECL static int
81
82/** Macro for checking and returning from the using function for
83 * \#VMEXIT intercepts that maybe caused during delivering of another
84 * event in the guest. */
85#ifdef VBOX_WITH_NESTED_HWVIRT
86# define HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY() \
87 do \
88 { \
89 int rc = hmR0SvmCheckExitDueToEventDelivery(pVCpu, pCtx, pSvmTransient); \
90 if (RT_LIKELY(rc == VINF_SUCCESS)) { /* continue #VMEXIT handling */ } \
91 else if ( rc == VINF_HM_DOUBLE_FAULT) { return VINF_SUCCESS; } \
92 else if ( rc == VINF_EM_RESET \
93 && HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_SHUTDOWN)) \
94 return VBOXSTRICTRC_TODO(IEMExecSvmVmexit(pVCpu, SVM_EXIT_SHUTDOWN, 0, 0)); \
95 else \
96 return rc; \
97 } while (0)
98#else
99# define HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY() \
100 do \
101 { \
102 int rc = hmR0SvmCheckExitDueToEventDelivery(pVCpu, pCtx, pSvmTransient); \
103 if (RT_LIKELY(rc == VINF_SUCCESS)) { /* continue #VMEXIT handling */ } \
104 else if ( rc == VINF_HM_DOUBLE_FAULT) { return VINF_SUCCESS; } \
105 else \
106 return rc; \
107 } while (0)
108#endif
109
110/**
111 * Updates interrupt shadow for the current RIP.
112 */
113#define HMSVM_UPDATE_INTR_SHADOW(pVCpu, pCtx) \
114 do { \
115 /* Update interrupt shadow. */ \
116 if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS) \
117 && pCtx->rip != EMGetInhibitInterruptsPC(pVCpu)) \
118 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS); \
119 } while (0)
120
121/** Macro for upgrading a @a a_rc to VINF_EM_DBG_STEPPED after emulating an
122 * instruction that exited. */
123#define HMSVM_CHECK_SINGLE_STEP(a_pVCpu, a_rc) \
124 do { \
125 if ((a_pVCpu)->hm.s.fSingleInstruction && (a_rc) == VINF_SUCCESS) \
126 (a_rc) = VINF_EM_DBG_STEPPED; \
127 } while (0)
128
129/** Assert that preemption is disabled or covered by thread-context hooks. */
130#define HMSVM_ASSERT_PREEMPT_SAFE() Assert( VMMR0ThreadCtxHookIsEnabled(pVCpu) \
131 || !RTThreadPreemptIsEnabled(NIL_RTTHREAD));
132
133/** Assert that we haven't migrated CPUs when thread-context hooks are not
134 * used. */
135#define HMSVM_ASSERT_CPU_SAFE() AssertMsg( VMMR0ThreadCtxHookIsEnabled(pVCpu) \
136 || pVCpu->hm.s.idEnteredCpu == RTMpCpuId(), \
137 ("Illegal migration! Entered on CPU %u Current %u\n", \
138 pVCpu->hm.s.idEnteredCpu, RTMpCpuId()));
139
140/** Assert that we're not executing a nested-guest. */
141#ifdef VBOX_WITH_NESTED_HWVIRT
142# define HMSVM_ASSERT_NOT_IN_NESTED_GUEST(a_pCtx) Assert(!CPUMIsGuestInSvmNestedHwVirtMode((a_pCtx)))
143#else
144# define HMSVM_ASSERT_NOT_IN_NESTED_GUEST(a_pCtx) do { NOREF((a_pCtx)); } while (0)
145#endif
146
147/** Assert that we're executing a nested-guest. */
148#ifdef VBOX_WITH_NESTED_HWVIRT
149# define HMSVM_ASSERT_IN_NESTED_GUEST(a_pCtx) Assert(CPUMIsGuestInSvmNestedHwVirtMode((a_pCtx)))
150#else
151# define HMSVM_ASSERT_IN_NESTED_GUEST(a_pCtx) do { NOREF((a_pCtx)); } while (0)
152#endif
153
154/** Validate segment descriptor granularity bit. */
155#ifdef VBOX_STRICT
156# define HMSVM_ASSERT_SEG_GRANULARITY(reg) \
157 AssertMsg( !pMixedCtx->reg.Attr.n.u1Present \
158 || ( pMixedCtx->reg.Attr.n.u1Granularity \
159 ? (pMixedCtx->reg.u32Limit & 0xfff) == 0xfff \
160 : pMixedCtx->reg.u32Limit <= UINT32_C(0xfffff)), \
161 ("Invalid Segment Attributes Limit=%#RX32 Attr=%#RX32 Base=%#RX64\n", pMixedCtx->reg.u32Limit, \
162 pMixedCtx->reg.Attr.u, pMixedCtx->reg.u64Base))
163#else
164# define HMSVM_ASSERT_SEG_GRANULARITY(reg) do { } while (0)
165#endif
166
167/**
168 * Exception bitmap mask for all contributory exceptions.
169 *
170 * Page fault is deliberately excluded here as it's conditional as to whether
171 * it's contributory or benign. Page faults are handled separately.
172 */
173#define HMSVM_CONTRIBUTORY_XCPT_MASK ( RT_BIT(X86_XCPT_GP) | RT_BIT(X86_XCPT_NP) | RT_BIT(X86_XCPT_SS) | RT_BIT(X86_XCPT_TS) \
174 | RT_BIT(X86_XCPT_DE))
175
176/**
177 * Mandatory/unconditional guest control intercepts.
178 *
179 * SMIs can and do happen in normal operation. We need not intercept them
180 * while executing the guest (or nested-guest).
181 */
182#define HMSVM_MANDATORY_GUEST_CTRL_INTERCEPTS ( SVM_CTRL_INTERCEPT_INTR \
183 | SVM_CTRL_INTERCEPT_NMI \
184 | SVM_CTRL_INTERCEPT_INIT \
185 | SVM_CTRL_INTERCEPT_RDPMC \
186 | SVM_CTRL_INTERCEPT_CPUID \
187 | SVM_CTRL_INTERCEPT_RSM \
188 | SVM_CTRL_INTERCEPT_HLT \
189 | SVM_CTRL_INTERCEPT_IOIO_PROT \
190 | SVM_CTRL_INTERCEPT_MSR_PROT \
191 | SVM_CTRL_INTERCEPT_INVLPGA \
192 | SVM_CTRL_INTERCEPT_SHUTDOWN \
193 | SVM_CTRL_INTERCEPT_FERR_FREEZE \
194 | SVM_CTRL_INTERCEPT_VMRUN \
195 | SVM_CTRL_INTERCEPT_SKINIT \
196 | SVM_CTRL_INTERCEPT_WBINVD \
197 | SVM_CTRL_INTERCEPT_MONITOR \
198 | SVM_CTRL_INTERCEPT_MWAIT \
199 | SVM_CTRL_INTERCEPT_CR0_SEL_WRITE \
200 | SVM_CTRL_INTERCEPT_XSETBV)
201
202/** @name VMCB Clean Bits.
203 *
204 * These flags are used for VMCB-state caching. A set VMCB Clean bit indicates
205 * AMD-V doesn't need to reload the corresponding value(s) from the VMCB in
206 * memory.
207 *
208 * @{ */
209/** All intercepts vectors, TSC offset, PAUSE filter counter. */
210#define HMSVM_VMCB_CLEAN_INTERCEPTS RT_BIT(0)
211/** I/O permission bitmap, MSR permission bitmap. */
212#define HMSVM_VMCB_CLEAN_IOPM_MSRPM RT_BIT(1)
213/** ASID. */
214#define HMSVM_VMCB_CLEAN_ASID RT_BIT(2)
215/** TRP: V_TPR, V_IRQ, V_INTR_PRIO, V_IGN_TPR, V_INTR_MASKING,
216V_INTR_VECTOR. */
217#define HMSVM_VMCB_CLEAN_TPR RT_BIT(3)
218/** Nested Paging: Nested CR3 (nCR3), PAT. */
219#define HMSVM_VMCB_CLEAN_NP RT_BIT(4)
220/** Control registers (CR0, CR3, CR4, EFER). */
221#define HMSVM_VMCB_CLEAN_CRX_EFER RT_BIT(5)
222/** Debug registers (DR6, DR7). */
223#define HMSVM_VMCB_CLEAN_DRX RT_BIT(6)
224/** GDT, IDT limit and base. */
225#define HMSVM_VMCB_CLEAN_DT RT_BIT(7)
226/** Segment register: CS, SS, DS, ES limit and base. */
227#define HMSVM_VMCB_CLEAN_SEG RT_BIT(8)
228/** CR2.*/
229#define HMSVM_VMCB_CLEAN_CR2 RT_BIT(9)
230/** Last-branch record (DbgCtlMsr, br_from, br_to, lastint_from, lastint_to) */
231#define HMSVM_VMCB_CLEAN_LBR RT_BIT(10)
232/** AVIC (AVIC APIC_BAR; AVIC APIC_BACKING_PAGE, AVIC
233PHYSICAL_TABLE and AVIC LOGICAL_TABLE Pointers). */
234#define HMSVM_VMCB_CLEAN_AVIC RT_BIT(11)
235/** Mask of all valid VMCB Clean bits. */
236#define HMSVM_VMCB_CLEAN_ALL ( HMSVM_VMCB_CLEAN_INTERCEPTS \
237 | HMSVM_VMCB_CLEAN_IOPM_MSRPM \
238 | HMSVM_VMCB_CLEAN_ASID \
239 | HMSVM_VMCB_CLEAN_TPR \
240 | HMSVM_VMCB_CLEAN_NP \
241 | HMSVM_VMCB_CLEAN_CRX_EFER \
242 | HMSVM_VMCB_CLEAN_DRX \
243 | HMSVM_VMCB_CLEAN_DT \
244 | HMSVM_VMCB_CLEAN_SEG \
245 | HMSVM_VMCB_CLEAN_CR2 \
246 | HMSVM_VMCB_CLEAN_LBR \
247 | HMSVM_VMCB_CLEAN_AVIC)
248/** @} */
249
250/** @name SVM transient.
251 *
252 * A state structure for holding miscellaneous information across AMD-V
253 * VMRUN/\#VMEXIT operation, restored after the transition.
254 *
255 * @{ */
256typedef struct SVMTRANSIENT
257{
258 /** The host's rflags/eflags. */
259 RTCCUINTREG fEFlags;
260#if HC_ARCH_BITS == 32
261 uint32_t u32Alignment0;
262#endif
263
264 /** The \#VMEXIT exit code (the EXITCODE field in the VMCB). */
265 uint64_t u64ExitCode;
266 /** The guest's TPR value used for TPR shadowing. */
267 uint8_t u8GuestTpr;
268 /** Alignment. */
269 uint8_t abAlignment0[7];
270
271 /** 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 hmR0SvmInjectPendingEvent() */
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. */
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 hmR0SvmVmRunSetupVmcb() 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_TPR);
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 == 1)
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 hmR0SvmVmRunCacheVmcb(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(("hmR0SvmVmRunCacheVmcb: 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 the 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 hmR0SvmVmRunSetupVmcb(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 = hmR0SvmVmRunCacheVmcb(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); Assert(pVmcbNstGst);
2607
2608 int rc = hmR0SvmLoadGuestControlRegs(pVCpu, pVmcbNstGst, pCtx);
2609 AssertRCReturn(rc, rc);
2610
2611 /*
2612 * We need to load the entire state (including FS, GS etc.) as we could be continuing
2613 * to execute the nested-guest at any point (not just immediately after VMRUN) and thus
2614 * the VMCB can possibly be out-of-sync with the actual nested-guest state if it was
2615 * executed in IEM.
2616 */
2617 hmR0SvmLoadGuestSegmentRegs(pVCpu, pVmcbNstGst, pCtx);
2618 hmR0SvmLoadGuestMsrs(pVCpu, pVmcbNstGst, pCtx);
2619 hmR0SvmLoadGuestApicStateNested(pVCpu, pVmcbNstGst);
2620 hmR0SvmLoadGuestHwvirtStateNested(pVCpu, pVmcbNstGst, pCtx);
2621
2622 pVmcbNstGst->guest.u64RIP = pCtx->rip;
2623 pVmcbNstGst->guest.u64RSP = pCtx->rsp;
2624 pVmcbNstGst->guest.u64RFlags = pCtx->eflags.u32;
2625 pVmcbNstGst->guest.u64RAX = pCtx->rax;
2626
2627#ifdef VBOX_WITH_NESTED_HWVIRT
2628 Assert(pVmcbNstGst->ctrl.IntCtrl.n.u1VGifEnable == 0); /* Nested VGIF not supported yet. */
2629#endif
2630
2631 rc = hmR0SvmSetupVMRunHandler(pVCpu);
2632 AssertRCReturn(rc, rc);
2633
2634 /* Clear any unused and reserved bits. */
2635 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_RIP /* Unused (loaded unconditionally). */
2636 | HM_CHANGED_GUEST_RSP
2637 | HM_CHANGED_GUEST_RFLAGS
2638 | HM_CHANGED_GUEST_SYSENTER_CS_MSR
2639 | HM_CHANGED_GUEST_SYSENTER_EIP_MSR
2640 | HM_CHANGED_GUEST_SYSENTER_ESP_MSR
2641 | HM_CHANGED_VMM_GUEST_XCPT_INTERCEPTS /* Unused. */
2642 | HM_CHANGED_VMM_GUEST_LAZY_MSRS
2643 | HM_CHANGED_SVM_RESERVED1 /* Reserved. */
2644 | HM_CHANGED_SVM_RESERVED2
2645 | HM_CHANGED_SVM_RESERVED3
2646 | HM_CHANGED_SVM_RESERVED4);
2647
2648 /* All the guest state bits should be loaded except maybe the host context and/or shared host/guest bits. */
2649 AssertMsg( !HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_ALL_GUEST)
2650 || HMCPU_CF_IS_PENDING_ONLY(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE),
2651 ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
2652
2653#ifdef VBOX_STRICT
2654 hmR0SvmLogState(pVCpu, pVmcbNstGst, pCtx, "hmR0SvmLoadGuestStateNested", HMSVM_LOG_ALL, 0 /* uVerbose */);
2655#endif
2656 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestState, x);
2657 return rc;
2658}
2659#endif /* VBOX_WITH_NESTED_HWVIRT */
2660
2661
2662/**
2663 * Loads the state shared between the host and guest (or nested-guest) into the
2664 * VMCB.
2665 *
2666 * @param pVCpu The cross context virtual CPU structure.
2667 * @param pVmcb Pointer to the VM control block.
2668 * @param pCtx Pointer to the guest-CPU context.
2669 *
2670 * @remarks No-long-jump zone!!!
2671 */
2672static void hmR0SvmLoadSharedState(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
2673{
2674 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2675 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2676
2677 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR0))
2678 {
2679 hmR0SvmLoadSharedCR0(pVCpu, pVmcb, pCtx);
2680 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR0);
2681 }
2682
2683 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_DEBUG))
2684 {
2685 /** @todo Figure out stepping with nested-guest. */
2686 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
2687 hmR0SvmLoadSharedDebugState(pVCpu, pVmcb, pCtx);
2688 else
2689 {
2690 pVmcb->guest.u64DR6 = pCtx->dr[6];
2691 pVmcb->guest.u64DR7 = pCtx->dr[7];
2692 Log4(("hmR0SvmLoadSharedState: DR6=%#RX64 DR7=%#RX64\n", pCtx->dr[6], pCtx->dr[7]));
2693 }
2694
2695 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_DEBUG);
2696 }
2697
2698 /* Unused on AMD-V (no lazy MSRs). */
2699 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_VMM_GUEST_LAZY_MSRS);
2700
2701 AssertMsg(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_GUEST_SHARED_STATE),
2702 ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
2703}
2704
2705
2706/**
2707 * Saves the guest (or nested-guest) state from the VMCB into the guest-CPU
2708 * context.
2709 *
2710 * Currently there is no residual state left in the CPU that is not updated in the
2711 * VMCB.
2712 *
2713 * @returns VBox status code.
2714 * @param pVCpu The cross context virtual CPU structure.
2715 * @param pMixedCtx Pointer to the guest-CPU or nested-guest-CPU
2716 * context. The data may be out-of-sync. Make sure to
2717 * update the required fields before using them.
2718 * @param pVmcb Pointer to the VM control block.
2719 */
2720static void hmR0SvmSaveGuestState(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PCSVMVMCB pVmcb)
2721{
2722 Assert(VMMRZCallRing3IsEnabled(pVCpu));
2723
2724 pMixedCtx->rip = pVmcb->guest.u64RIP;
2725 pMixedCtx->rsp = pVmcb->guest.u64RSP;
2726 pMixedCtx->eflags.u32 = pVmcb->guest.u64RFlags;
2727 pMixedCtx->rax = pVmcb->guest.u64RAX;
2728
2729 PCSVMVMCBCTRL pVmcbCtrl = &pVmcb->ctrl;
2730#ifdef VBOX_WITH_NESTED_HWVIRT
2731 if (!CPUMIsGuestInSvmNestedHwVirtMode(pMixedCtx))
2732 {
2733 if (pVmcbCtrl->IntCtrl.n.u1VGifEnable)
2734 {
2735 /*
2736 * Guest Virtual GIF (Global Interrupt Flag).
2737 * We don't yet support passing VGIF feature to the guest.
2738 */
2739 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.svm.fVGif);
2740 pMixedCtx->hwvirt.fGif = pVmcbCtrl->IntCtrl.n.u1VGif;
2741 }
2742 }
2743 else
2744 {
2745 /* Sync/verify nested-guest's V_IRQ pending and our force-flag. */
2746 if (!pVmcbCtrl->IntCtrl.n.u1VIrqPending)
2747 {
2748 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NESTED_GUEST))
2749 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NESTED_GUEST);
2750 }
2751 else
2752 Assert(VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NESTED_GUEST));
2753 }
2754#endif
2755
2756 /*
2757 * Guest interrupt shadow.
2758 */
2759 if (pVmcbCtrl->IntShadow.n.u1IntShadow)
2760 EMSetInhibitInterruptsPC(pVCpu, pMixedCtx->rip);
2761 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
2762 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
2763
2764 /*
2765 * Guest control registers: CR0, CR2, CR3 (handled at the end).
2766 * Accesses to other control registers are always intercepted.
2767 */
2768 pMixedCtx->cr2 = pVmcb->guest.u64CR2;
2769
2770 /* If we're not intercepting changes to CR0 TS & MP bits, sync those bits here. */
2771 if (!(pVmcbCtrl->u16InterceptWrCRx & RT_BIT(0)))
2772 {
2773 pMixedCtx->cr0 = (pMixedCtx->cr0 & ~(X86_CR0_TS | X86_CR0_MP))
2774 | (pVmcb->guest.u64CR0 & (X86_CR0_TS | X86_CR0_MP));
2775 }
2776
2777 /*
2778 * Guest MSRs.
2779 */
2780 pMixedCtx->msrSTAR = pVmcb->guest.u64STAR; /* legacy syscall eip, cs & ss */
2781 pMixedCtx->msrLSTAR = pVmcb->guest.u64LSTAR; /* 64-bit mode syscall rip */
2782 pMixedCtx->msrCSTAR = pVmcb->guest.u64CSTAR; /* compatibility mode syscall rip */
2783 pMixedCtx->msrSFMASK = pVmcb->guest.u64SFMASK; /* syscall flag mask */
2784 pMixedCtx->msrKERNELGSBASE = pVmcb->guest.u64KernelGSBase; /* swapgs exchange value */
2785 pMixedCtx->SysEnter.cs = pVmcb->guest.u64SysEnterCS;
2786 pMixedCtx->SysEnter.eip = pVmcb->guest.u64SysEnterEIP;
2787 pMixedCtx->SysEnter.esp = pVmcb->guest.u64SysEnterESP;
2788
2789 /*
2790 * Guest segment registers (includes FS, GS base MSRs for 64-bit guests).
2791 */
2792 HMSVM_SEG_REG_COPY_FROM_VMCB(pMixedCtx, &pVmcb->guest, CS, cs);
2793 HMSVM_SEG_REG_COPY_FROM_VMCB(pMixedCtx, &pVmcb->guest, SS, ss);
2794 HMSVM_SEG_REG_COPY_FROM_VMCB(pMixedCtx, &pVmcb->guest, DS, ds);
2795 HMSVM_SEG_REG_COPY_FROM_VMCB(pMixedCtx, &pVmcb->guest, ES, es);
2796 HMSVM_SEG_REG_COPY_FROM_VMCB(pMixedCtx, &pVmcb->guest, FS, fs);
2797 HMSVM_SEG_REG_COPY_FROM_VMCB(pMixedCtx, &pVmcb->guest, GS, gs);
2798
2799 /*
2800 * Correct the hidden CS granularity bit. Haven't seen it being wrong in any other
2801 * register (yet).
2802 */
2803 /** @todo SELM might need to be fixed as it too should not care about the
2804 * granularity bit. See @bugref{6785}. */
2805 if ( !pMixedCtx->cs.Attr.n.u1Granularity
2806 && pMixedCtx->cs.Attr.n.u1Present
2807 && pMixedCtx->cs.u32Limit > UINT32_C(0xfffff))
2808 {
2809 Assert((pMixedCtx->cs.u32Limit & 0xfff) == 0xfff);
2810 pMixedCtx->cs.Attr.n.u1Granularity = 1;
2811 }
2812
2813 HMSVM_ASSERT_SEG_GRANULARITY(cs);
2814 HMSVM_ASSERT_SEG_GRANULARITY(ss);
2815 HMSVM_ASSERT_SEG_GRANULARITY(ds);
2816 HMSVM_ASSERT_SEG_GRANULARITY(es);
2817 HMSVM_ASSERT_SEG_GRANULARITY(fs);
2818 HMSVM_ASSERT_SEG_GRANULARITY(gs);
2819
2820 /*
2821 * Sync the hidden SS DPL field. AMD CPUs have a separate CPL field in the VMCB and uses that
2822 * and thus it's possible that when the CPL changes during guest execution that the SS DPL
2823 * isn't updated by AMD-V. Observed on some AMD Fusion CPUs with 64-bit guests.
2824 * See AMD spec. 15.5.1 "Basic operation".
2825 */
2826 Assert(!(pVmcb->guest.u8CPL & ~0x3));
2827 uint8_t const uCpl = pVmcb->guest.u8CPL;
2828 if (pMixedCtx->ss.Attr.n.u2Dpl != uCpl)
2829 {
2830 Log4(("hmR0SvmSaveGuestState: CPL differs. SS.DPL=%u, CPL=%u, overwriting SS.DPL!\n", pMixedCtx->ss.Attr.n.u2Dpl, uCpl));
2831 pMixedCtx->ss.Attr.n.u2Dpl = pVmcb->guest.u8CPL & 0x3;
2832 }
2833
2834 /*
2835 * Guest TR.
2836 * Fixup TR attributes so it's compatible with Intel. Important when saved-states are used
2837 * between Intel and AMD. See @bugref{6208#c39}.
2838 * ASSUME that it's normally correct and that we're in 32-bit or 64-bit mode.
2839 */
2840 HMSVM_SEG_REG_COPY_FROM_VMCB(pMixedCtx, &pVmcb->guest, TR, tr);
2841 if (pMixedCtx->tr.Attr.n.u4Type != X86_SEL_TYPE_SYS_386_TSS_BUSY)
2842 {
2843 if ( pMixedCtx->tr.Attr.n.u4Type == X86_SEL_TYPE_SYS_386_TSS_AVAIL
2844 || CPUMIsGuestInLongModeEx(pMixedCtx))
2845 pMixedCtx->tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_386_TSS_BUSY;
2846 else if (pMixedCtx->tr.Attr.n.u4Type == X86_SEL_TYPE_SYS_286_TSS_AVAIL)
2847 pMixedCtx->tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_286_TSS_BUSY;
2848 }
2849
2850 /*
2851 * Guest Descriptor-Table registers (GDTR, IDTR, LDTR).
2852 */
2853 HMSVM_SEG_REG_COPY_FROM_VMCB(pMixedCtx, &pVmcb->guest, LDTR, ldtr);
2854 pMixedCtx->gdtr.cbGdt = pVmcb->guest.GDTR.u32Limit;
2855 pMixedCtx->gdtr.pGdt = pVmcb->guest.GDTR.u64Base;
2856
2857 pMixedCtx->idtr.cbIdt = pVmcb->guest.IDTR.u32Limit;
2858 pMixedCtx->idtr.pIdt = pVmcb->guest.IDTR.u64Base;
2859
2860 /*
2861 * Guest Debug registers.
2862 */
2863 if (!pVCpu->hm.s.fUsingHyperDR7)
2864 {
2865 pMixedCtx->dr[6] = pVmcb->guest.u64DR6;
2866 pMixedCtx->dr[7] = pVmcb->guest.u64DR7;
2867 }
2868 else
2869 {
2870 Assert(pVmcb->guest.u64DR7 == CPUMGetHyperDR7(pVCpu));
2871 CPUMSetHyperDR6(pVCpu, pVmcb->guest.u64DR6);
2872 }
2873
2874 /*
2875 * With Nested Paging, CR3 changes are not intercepted. Therefore, sync. it now.
2876 * This is done as the very last step of syncing the guest state, as PGMUpdateCR3() may cause longjmp's to ring-3.
2877 */
2878 if ( pVmcbCtrl->NestedPagingCtrl.n.u1NestedPaging
2879 && pMixedCtx->cr3 != pVmcb->guest.u64CR3)
2880 {
2881 CPUMSetGuestCR3(pVCpu, pVmcb->guest.u64CR3);
2882 PGMUpdateCR3(pVCpu, pVmcb->guest.u64CR3);
2883 }
2884
2885#ifdef VBOX_STRICT
2886 if (CPUMIsGuestInSvmNestedHwVirtMode(pMixedCtx))
2887 hmR0SvmLogState(pVCpu, pVmcb, pMixedCtx, "hmR0SvmSaveGuestStateNested", HMSVM_LOG_ALL & ~HMSVM_LOG_LBR, 0 /* uVerbose */);
2888#endif
2889}
2890
2891
2892/**
2893 * Does the necessary state syncing before returning to ring-3 for any reason
2894 * (longjmp, preemption, voluntary exits to ring-3) from AMD-V.
2895 *
2896 * @param pVCpu The cross context virtual CPU structure.
2897 *
2898 * @remarks No-long-jmp zone!!!
2899 */
2900static void hmR0SvmLeave(PVMCPU pVCpu)
2901{
2902 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2903 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2904 Assert(VMMR0IsLogFlushDisabled(pVCpu));
2905
2906 /*
2907 * !!! IMPORTANT !!!
2908 * If you modify code here, make sure to check whether hmR0SvmCallRing3Callback() needs to be updated too.
2909 */
2910
2911 /* Restore host FPU state if necessary and resync on next R0 reentry .*/
2912 if (CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu))
2913 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0); /** @todo r=ramshankar: This shouldn't be necessary, it's set in HMR0EnterCpu. */
2914
2915 /*
2916 * Restore host debug registers if necessary and resync on next R0 reentry.
2917 */
2918#ifdef VBOX_STRICT
2919 if (CPUMIsHyperDebugStateActive(pVCpu))
2920 {
2921 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb; /** @todo nested-guest. */
2922 Assert(pVmcb->ctrl.u16InterceptRdDRx == 0xffff);
2923 Assert(pVmcb->ctrl.u16InterceptWrDRx == 0xffff);
2924 }
2925#endif
2926 if (CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, false /* save DR6 */))
2927 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);/** @todo r=ramshankar: This shouldn't be necessary, it's set in HMR0EnterCpu. */
2928
2929 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
2930 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
2931
2932 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatEntry);
2933 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatLoadGuestState);
2934 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit1);
2935 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit2);
2936 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
2937
2938 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
2939}
2940
2941
2942/**
2943 * Leaves the AMD-V session.
2944 *
2945 * @returns VBox status code.
2946 * @param pVCpu The cross context virtual CPU structure.
2947 */
2948static int hmR0SvmLeaveSession(PVMCPU pVCpu)
2949{
2950 HM_DISABLE_PREEMPT();
2951 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2952 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2953
2954 /* When thread-context hooks are used, we can avoid doing the leave again if we had been preempted before
2955 and done this from the SVMR0ThreadCtxCallback(). */
2956 if (!pVCpu->hm.s.fLeaveDone)
2957 {
2958 hmR0SvmLeave(pVCpu);
2959 pVCpu->hm.s.fLeaveDone = true;
2960 }
2961
2962 /*
2963 * !!! IMPORTANT !!!
2964 * If you modify code here, make sure to check whether hmR0SvmCallRing3Callback() needs to be updated too.
2965 */
2966
2967 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
2968 /* Deregister hook now that we've left HM context before re-enabling preemption. */
2969 VMMR0ThreadCtxHookDisable(pVCpu);
2970
2971 /* Leave HM context. This takes care of local init (term). */
2972 int rc = HMR0LeaveCpu(pVCpu);
2973
2974 HM_RESTORE_PREEMPT();
2975 return rc;
2976}
2977
2978
2979/**
2980 * Does the necessary state syncing before doing a longjmp to ring-3.
2981 *
2982 * @returns VBox status code.
2983 * @param pVCpu The cross context virtual CPU structure.
2984 *
2985 * @remarks No-long-jmp zone!!!
2986 */
2987static int hmR0SvmLongJmpToRing3(PVMCPU pVCpu)
2988{
2989 return hmR0SvmLeaveSession(pVCpu);
2990}
2991
2992
2993/**
2994 * VMMRZCallRing3() callback wrapper which saves the guest state (or restores
2995 * any remaining host state) before we longjump to ring-3 and possibly get
2996 * preempted.
2997 *
2998 * @param pVCpu The cross context virtual CPU structure.
2999 * @param enmOperation The operation causing the ring-3 longjump.
3000 * @param pvUser The user argument (pointer to the possibly
3001 * out-of-date guest-CPU context).
3002 */
3003static DECLCALLBACK(int) hmR0SvmCallRing3Callback(PVMCPU pVCpu, VMMCALLRING3 enmOperation, void *pvUser)
3004{
3005 RT_NOREF_PV(pvUser);
3006
3007 if (enmOperation == VMMCALLRING3_VM_R0_ASSERTION)
3008 {
3009 /*
3010 * !!! IMPORTANT !!!
3011 * If you modify code here, make sure to check whether hmR0SvmLeave() and hmR0SvmLeaveSession() needs
3012 * to be updated too. This is a stripped down version which gets out ASAP trying to not trigger any assertion.
3013 */
3014 VMMRZCallRing3RemoveNotification(pVCpu);
3015 VMMRZCallRing3Disable(pVCpu);
3016 HM_DISABLE_PREEMPT();
3017
3018 /* Restore host FPU state if necessary and resync on next R0 reentry. */
3019 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
3020
3021 /* Restore host debug registers if necessary and resync on next R0 reentry. */
3022 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, false /* save DR6 */);
3023
3024 /* Deregister the hook now that we've left HM context before re-enabling preemption. */
3025 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
3026 VMMR0ThreadCtxHookDisable(pVCpu);
3027
3028 /* Leave HM context. This takes care of local init (term). */
3029 HMR0LeaveCpu(pVCpu);
3030
3031 HM_RESTORE_PREEMPT();
3032 return VINF_SUCCESS;
3033 }
3034
3035 Assert(pVCpu);
3036 Assert(pvUser);
3037 Assert(VMMRZCallRing3IsEnabled(pVCpu));
3038 HMSVM_ASSERT_PREEMPT_SAFE();
3039
3040 VMMRZCallRing3Disable(pVCpu);
3041 Assert(VMMR0IsLogFlushDisabled(pVCpu));
3042
3043 Log4(("hmR0SvmCallRing3Callback->hmR0SvmLongJmpToRing3\n"));
3044 int rc = hmR0SvmLongJmpToRing3(pVCpu);
3045 AssertRCReturn(rc, rc);
3046
3047 VMMRZCallRing3Enable(pVCpu);
3048 return VINF_SUCCESS;
3049}
3050
3051
3052/**
3053 * Take necessary actions before going back to ring-3.
3054 *
3055 * An action requires us to go back to ring-3. This function does the necessary
3056 * steps before we can safely return to ring-3. This is not the same as longjmps
3057 * to ring-3, this is voluntary.
3058 *
3059 * @returns VBox status code.
3060 * @param pVM The cross context VM structure.
3061 * @param pVCpu The cross context virtual CPU structure.
3062 * @param pCtx Pointer to the guest-CPU context.
3063 * @param rcExit The reason for exiting to ring-3. Can be
3064 * VINF_VMM_UNKNOWN_RING3_CALL.
3065 */
3066static int hmR0SvmExitToRing3(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int rcExit)
3067{
3068 Assert(pVM);
3069 Assert(pVCpu);
3070 Assert(pCtx);
3071 HMSVM_ASSERT_PREEMPT_SAFE();
3072
3073 /* Please, no longjumps here (any logging shouldn't flush jump back to ring-3). NO LOGGING BEFORE THIS POINT! */
3074 VMMRZCallRing3Disable(pVCpu);
3075 Log4(("hmR0SvmExitToRing3: VCPU[%u]: rcExit=%d LocalFF=%#RX32 GlobalFF=%#RX32\n", pVCpu->idCpu, rcExit,
3076 pVCpu->fLocalForcedActions, pVM->fGlobalForcedActions));
3077
3078 /* We need to do this only while truly exiting the "inner loop" back to ring-3 and -not- for any longjmp to ring3. */
3079 if (pVCpu->hm.s.Event.fPending)
3080 {
3081 hmR0SvmPendingEventToTrpmTrap(pVCpu);
3082 Assert(!pVCpu->hm.s.Event.fPending);
3083 }
3084
3085 /* Sync. the necessary state for going back to ring-3. */
3086 hmR0SvmLeaveSession(pVCpu);
3087 STAM_COUNTER_DEC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
3088
3089 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
3090 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR
3091 | CPUM_CHANGED_LDTR
3092 | CPUM_CHANGED_GDTR
3093 | CPUM_CHANGED_IDTR
3094 | CPUM_CHANGED_TR
3095 | CPUM_CHANGED_HIDDEN_SEL_REGS);
3096 if ( pVM->hm.s.fNestedPaging
3097 && CPUMIsGuestPagingEnabledEx(pCtx))
3098 {
3099 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_GLOBAL_TLB_FLUSH);
3100 }
3101
3102 /* On our way back from ring-3 reload the guest state if there is a possibility of it being changed. */
3103 if (rcExit != VINF_EM_RAW_INTERRUPT)
3104 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
3105
3106 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchExitToR3);
3107
3108 /* We do -not- want any longjmp notifications after this! We must return to ring-3 ASAP. */
3109 VMMRZCallRing3RemoveNotification(pVCpu);
3110 VMMRZCallRing3Enable(pVCpu);
3111
3112 /*
3113 * If we're emulating an instruction, we shouldn't have any TRPM traps pending
3114 * and if we're injecting an event we should have a TRPM trap pending.
3115 */
3116 AssertReturnStmt(rcExit != VINF_EM_RAW_INJECT_TRPM_EVENT || TRPMHasTrap(pVCpu),
3117 pVCpu->hm.s.u32HMError = rcExit,
3118 VERR_SVM_IPE_5);
3119 AssertReturnStmt(rcExit != VINF_EM_RAW_EMULATE_INSTR || !TRPMHasTrap(pVCpu),
3120 pVCpu->hm.s.u32HMError = rcExit,
3121 VERR_SVM_IPE_4);
3122
3123 return rcExit;
3124}
3125
3126
3127/**
3128 * Updates the use of TSC offsetting mode for the CPU and adjusts the necessary
3129 * intercepts.
3130 *
3131 * @param pVM The cross context VM structure.
3132 * @param pVCpu The cross context virtual CPU structure.
3133 * @param pCtx Pointer to the guest-CPU or nested-guest-CPU context.
3134 * @param pVmcb Pointer to the VM control block.
3135 *
3136 * @remarks No-long-jump zone!!!
3137 */
3138static void hmR0SvmUpdateTscOffsetting(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMVMCB pVmcb)
3139{
3140 /*
3141 * Avoid intercepting RDTSC/RDTSCP if we determined the host TSC (++) is stable
3142 * and in case of a nested-guest, if the nested-VMCB specifies it is not intercepting
3143 * RDTSC/RDTSCP as well.
3144 */
3145 bool fParavirtTsc;
3146 uint64_t uTscOffset;
3147 bool const fCanUseRealTsc = TMCpuTickCanUseRealTSC(pVM, pVCpu, &uTscOffset, &fParavirtTsc);
3148
3149 bool fIntercept;
3150 if (fCanUseRealTsc)
3151 fIntercept = hmR0SvmClearCtrlIntercept(pVCpu, pCtx, pVmcb, SVM_CTRL_INTERCEPT_RDTSC | SVM_CTRL_INTERCEPT_RDTSCP);
3152 else
3153 {
3154 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_RDTSC | SVM_CTRL_INTERCEPT_RDTSCP);
3155 fIntercept = true;
3156 }
3157
3158 if (!fIntercept)
3159 {
3160 /* Apply the nested-guest VMCB's TSC offset over the guest TSC offset. */
3161 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
3162 uTscOffset = HMSvmNstGstApplyTscOffset(pVCpu, uTscOffset);
3163
3164 /* Update the TSC offset in the VMCB and the relevant clean bits. */
3165 pVmcb->ctrl.u64TSCOffset = uTscOffset;
3166 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
3167
3168 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
3169 }
3170 else
3171 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
3172
3173 /* Currently neither Hyper-V nor KVM need to update their paravirt. TSC
3174 information before every VM-entry, hence we have nothing to do here at the moment. */
3175 if (fParavirtTsc)
3176 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscParavirt);
3177}
3178
3179
3180/**
3181 * Sets an event as a pending event to be injected into the guest.
3182 *
3183 * @param pVCpu The cross context virtual CPU structure.
3184 * @param pEvent Pointer to the SVM event.
3185 * @param GCPtrFaultAddress The fault-address (CR2) in case it's a
3186 * page-fault.
3187 *
3188 * @remarks Statistics counter assumes this is a guest event being reflected to
3189 * the guest i.e. 'StatInjectPendingReflect' is incremented always.
3190 */
3191DECLINLINE(void) hmR0SvmSetPendingEvent(PVMCPU pVCpu, PSVMEVENT pEvent, RTGCUINTPTR GCPtrFaultAddress)
3192{
3193 Assert(!pVCpu->hm.s.Event.fPending);
3194 Assert(pEvent->n.u1Valid);
3195
3196 pVCpu->hm.s.Event.u64IntInfo = pEvent->u;
3197 pVCpu->hm.s.Event.fPending = true;
3198 pVCpu->hm.s.Event.GCPtrFaultAddress = GCPtrFaultAddress;
3199
3200 Log4(("hmR0SvmSetPendingEvent: u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u,
3201 pEvent->n.u8Vector, (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
3202}
3203
3204
3205/**
3206 * Sets an invalid-opcode (\#UD) exception as pending-for-injection into the VM.
3207 *
3208 * @param pVCpu The cross context virtual CPU structure.
3209 */
3210DECLINLINE(void) hmR0SvmSetPendingXcptUD(PVMCPU pVCpu)
3211{
3212 SVMEVENT Event;
3213 Event.u = 0;
3214 Event.n.u1Valid = 1;
3215 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3216 Event.n.u8Vector = X86_XCPT_UD;
3217 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3218}
3219
3220
3221/**
3222 * Sets a debug (\#DB) exception as pending-for-injection into the VM.
3223 *
3224 * @param pVCpu The cross context virtual CPU structure.
3225 */
3226DECLINLINE(void) hmR0SvmSetPendingXcptDB(PVMCPU pVCpu)
3227{
3228 SVMEVENT Event;
3229 Event.u = 0;
3230 Event.n.u1Valid = 1;
3231 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3232 Event.n.u8Vector = X86_XCPT_DB;
3233 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3234}
3235
3236
3237/**
3238 * Sets a page fault (\#PF) exception as pending-for-injection into the VM.
3239 *
3240 * @param pVCpu The cross context virtual CPU structure.
3241 * @param pCtx Pointer to the guest-CPU context.
3242 * @param u32ErrCode The error-code for the page-fault.
3243 * @param uFaultAddress The page fault address (CR2).
3244 *
3245 * @remarks This updates the guest CR2 with @a uFaultAddress!
3246 */
3247DECLINLINE(void) hmR0SvmSetPendingXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t u32ErrCode, RTGCUINTPTR uFaultAddress)
3248{
3249 SVMEVENT Event;
3250 Event.u = 0;
3251 Event.n.u1Valid = 1;
3252 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3253 Event.n.u8Vector = X86_XCPT_PF;
3254 Event.n.u1ErrorCodeValid = 1;
3255 Event.n.u32ErrorCode = u32ErrCode;
3256
3257 /* Update CR2 of the guest. */
3258 if (pCtx->cr2 != uFaultAddress)
3259 {
3260 pCtx->cr2 = uFaultAddress;
3261 /* The VMCB clean bit for CR2 will be updated while re-loading the guest state. */
3262 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR2);
3263 }
3264
3265 hmR0SvmSetPendingEvent(pVCpu, &Event, uFaultAddress);
3266}
3267
3268
3269/**
3270 * Sets a math-fault (\#MF) exception as pending-for-injection into the VM.
3271 *
3272 * @param pVCpu The cross context virtual CPU structure.
3273 */
3274DECLINLINE(void) hmR0SvmSetPendingXcptMF(PVMCPU pVCpu)
3275{
3276 SVMEVENT Event;
3277 Event.u = 0;
3278 Event.n.u1Valid = 1;
3279 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3280 Event.n.u8Vector = X86_XCPT_MF;
3281 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3282}
3283
3284
3285/**
3286 * Sets a double fault (\#DF) exception as pending-for-injection into the VM.
3287 *
3288 * @param pVCpu The cross context virtual CPU structure.
3289 */
3290DECLINLINE(void) hmR0SvmSetPendingXcptDF(PVMCPU pVCpu)
3291{
3292 SVMEVENT Event;
3293 Event.u = 0;
3294 Event.n.u1Valid = 1;
3295 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3296 Event.n.u8Vector = X86_XCPT_DF;
3297 Event.n.u1ErrorCodeValid = 1;
3298 Event.n.u32ErrorCode = 0;
3299 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3300}
3301
3302
3303/**
3304 * Injects an event into the guest upon VMRUN by updating the relevant field
3305 * in the VMCB.
3306 *
3307 * @param pVCpu The cross context virtual CPU structure.
3308 * @param pVmcb Pointer to the guest VM control block.
3309 * @param pCtx Pointer to the guest-CPU context.
3310 * @param pEvent Pointer to the event.
3311 *
3312 * @remarks No-long-jump zone!!!
3313 * @remarks Requires CR0!
3314 */
3315DECLINLINE(void) hmR0SvmInjectEventVmcb(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx, PSVMEVENT pEvent)
3316{
3317 NOREF(pVCpu); NOREF(pCtx);
3318
3319 Assert(!pVmcb->ctrl.EventInject.n.u1Valid);
3320 pVmcb->ctrl.EventInject.u = pEvent->u;
3321 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[pEvent->n.u8Vector & MASK_INJECT_IRQ_STAT]);
3322
3323 Log4(("hmR0SvmInjectEventVmcb: u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u,
3324 pEvent->n.u8Vector, (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
3325}
3326
3327
3328
3329/**
3330 * Converts any TRPM trap into a pending HM event. This is typically used when
3331 * entering from ring-3 (not longjmp returns).
3332 *
3333 * @param pVCpu The cross context virtual CPU structure.
3334 */
3335static void hmR0SvmTrpmTrapToPendingEvent(PVMCPU pVCpu)
3336{
3337 Assert(TRPMHasTrap(pVCpu));
3338 Assert(!pVCpu->hm.s.Event.fPending);
3339
3340 uint8_t uVector;
3341 TRPMEVENT enmTrpmEvent;
3342 RTGCUINT uErrCode;
3343 RTGCUINTPTR GCPtrFaultAddress;
3344 uint8_t cbInstr;
3345
3346 int rc = TRPMQueryTrapAll(pVCpu, &uVector, &enmTrpmEvent, &uErrCode, &GCPtrFaultAddress, &cbInstr);
3347 AssertRC(rc);
3348
3349 SVMEVENT Event;
3350 Event.u = 0;
3351 Event.n.u1Valid = 1;
3352 Event.n.u8Vector = uVector;
3353
3354 /* Refer AMD spec. 15.20 "Event Injection" for the format. */
3355 if (enmTrpmEvent == TRPM_TRAP)
3356 {
3357 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3358 switch (uVector)
3359 {
3360 case X86_XCPT_NMI:
3361 {
3362 Event.n.u3Type = SVM_EVENT_NMI;
3363 break;
3364 }
3365
3366 case X86_XCPT_PF:
3367 case X86_XCPT_DF:
3368 case X86_XCPT_TS:
3369 case X86_XCPT_NP:
3370 case X86_XCPT_SS:
3371 case X86_XCPT_GP:
3372 case X86_XCPT_AC:
3373 {
3374 Event.n.u1ErrorCodeValid = 1;
3375 Event.n.u32ErrorCode = uErrCode;
3376 break;
3377 }
3378 }
3379 }
3380 else if (enmTrpmEvent == TRPM_HARDWARE_INT)
3381 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
3382 else if (enmTrpmEvent == TRPM_SOFTWARE_INT)
3383 Event.n.u3Type = SVM_EVENT_SOFTWARE_INT;
3384 else
3385 AssertMsgFailed(("Invalid TRPM event type %d\n", enmTrpmEvent));
3386
3387 rc = TRPMResetTrap(pVCpu);
3388 AssertRC(rc);
3389
3390 Log4(("TRPM->HM event: u=%#RX64 u8Vector=%#x uErrorCodeValid=%RTbool uErrorCode=%#RX32\n", Event.u, Event.n.u8Vector,
3391 !!Event.n.u1ErrorCodeValid, Event.n.u32ErrorCode));
3392
3393 hmR0SvmSetPendingEvent(pVCpu, &Event, GCPtrFaultAddress);
3394}
3395
3396
3397/**
3398 * Converts any pending SVM event into a TRPM trap. Typically used when leaving
3399 * AMD-V to execute any instruction.
3400 *
3401 * @param pVCpu The cross context virtual CPU structure.
3402 */
3403static void hmR0SvmPendingEventToTrpmTrap(PVMCPU pVCpu)
3404{
3405 Assert(pVCpu->hm.s.Event.fPending);
3406 Assert(TRPMQueryTrap(pVCpu, NULL /* pu8TrapNo */, NULL /* pEnmType */) == VERR_TRPM_NO_ACTIVE_TRAP);
3407
3408 SVMEVENT Event;
3409 Event.u = pVCpu->hm.s.Event.u64IntInfo;
3410
3411 uint8_t uVector = Event.n.u8Vector;
3412 uint8_t uVectorType = Event.n.u3Type;
3413 TRPMEVENT enmTrapType = HMSvmEventToTrpmEventType(&Event);
3414
3415 Log4(("HM event->TRPM: uVector=%#x enmTrapType=%d\n", uVector, uVectorType));
3416
3417 int rc = TRPMAssertTrap(pVCpu, uVector, enmTrapType);
3418 AssertRC(rc);
3419
3420 if (Event.n.u1ErrorCodeValid)
3421 TRPMSetErrorCode(pVCpu, Event.n.u32ErrorCode);
3422
3423 if ( uVectorType == SVM_EVENT_EXCEPTION
3424 && uVector == X86_XCPT_PF)
3425 {
3426 TRPMSetFaultAddress(pVCpu, pVCpu->hm.s.Event.GCPtrFaultAddress);
3427 Assert(pVCpu->hm.s.Event.GCPtrFaultAddress == CPUMGetGuestCR2(pVCpu));
3428 }
3429 else if (uVectorType == SVM_EVENT_SOFTWARE_INT)
3430 {
3431 AssertMsg( uVectorType == SVM_EVENT_SOFTWARE_INT
3432 || (uVector == X86_XCPT_BP || uVector == X86_XCPT_OF),
3433 ("Invalid vector: uVector=%#x uVectorType=%#x\n", uVector, uVectorType));
3434 TRPMSetInstrLength(pVCpu, pVCpu->hm.s.Event.cbInstr);
3435 }
3436 pVCpu->hm.s.Event.fPending = false;
3437}
3438
3439
3440/**
3441 * Checks if the guest (or nested-guest) has an interrupt shadow active right
3442 * now.
3443 *
3444 * @returns @c true if the interrupt shadow is active, @c false otherwise.
3445 * @param pVCpu The cross context virtual CPU structure.
3446 * @param pCtx Pointer to the guest-CPU context.
3447 *
3448 * @remarks No-long-jump zone!!!
3449 * @remarks Has side-effects with VMCPU_FF_INHIBIT_INTERRUPTS force-flag.
3450 */
3451DECLINLINE(bool) hmR0SvmIsIntrShadowActive(PVMCPU pVCpu, PCPUMCTX pCtx)
3452{
3453 /*
3454 * Instructions like STI and MOV SS inhibit interrupts till the next instruction completes. Check if we should
3455 * inhibit interrupts or clear any existing interrupt-inhibition.
3456 */
3457 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
3458 {
3459 if (pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
3460 {
3461 /*
3462 * We can clear the inhibit force flag as even if we go back to the recompiler without executing guest code in
3463 * AMD-V, the flag's condition to be cleared is met and thus the cleared state is correct.
3464 */
3465 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
3466 return false;
3467 }
3468 return true;
3469 }
3470 return false;
3471}
3472
3473
3474/**
3475 * Sets the virtual interrupt intercept control in the VMCB.
3476 *
3477 * @param pVmcb Pointer to the VM control block.
3478 */
3479DECLINLINE(void) hmR0SvmSetVirtIntrIntercept(PSVMVMCB pVmcb)
3480{
3481 /*
3482 * When AVIC isn't supported, indicate that a virtual interrupt is pending and to
3483 * cause a #VMEXIT when the guest is ready to accept interrupts. At #VMEXIT, we
3484 * then get the interrupt from the APIC (updating ISR at the right time) and
3485 * inject the interrupt.
3486 *
3487 * With AVIC is supported, we could make use of the asynchronously delivery without
3488 * #VMEXIT and we would be passing the AVIC page to SVM.
3489 */
3490 if (!(pVmcb->ctrl.u64InterceptCtrl & SVM_CTRL_INTERCEPT_VINTR))
3491 {
3492 Assert(pVmcb->ctrl.IntCtrl.n.u1VIrqPending == 0);
3493 pVmcb->ctrl.IntCtrl.n.u1VIrqPending = 1;
3494 pVmcb->ctrl.u64InterceptCtrl |= SVM_CTRL_INTERCEPT_VINTR;
3495 pVmcb->ctrl.u32VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
3496 Log4(("Set VINTR intercept\n"));
3497 }
3498}
3499
3500
3501/**
3502 * Clears the virtual interrupt intercept control in the VMCB as
3503 * we are figured the guest is unable process any interrupts
3504 * at this point of time.
3505 *
3506 * @param pVmcb Pointer to the VM control block.
3507 */
3508DECLINLINE(void) hmR0SvmClearVirtIntrIntercept(PSVMVMCB pVmcb)
3509{
3510 if (pVmcb->ctrl.u64InterceptCtrl & SVM_CTRL_INTERCEPT_VINTR)
3511 {
3512 Assert(pVmcb->ctrl.IntCtrl.n.u1VIrqPending == 1);
3513 pVmcb->ctrl.IntCtrl.n.u1VIrqPending = 0;
3514 pVmcb->ctrl.u64InterceptCtrl &= ~SVM_CTRL_INTERCEPT_VINTR;
3515 pVmcb->ctrl.u32VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
3516 Log4(("Cleared VINTR intercept\n"));
3517 }
3518}
3519
3520
3521/**
3522 * Sets the IRET intercept control in the VMCB which instructs AMD-V to cause a
3523 * \#VMEXIT as soon as a guest starts executing an IRET. This is used to unblock
3524 * virtual NMIs.
3525 *
3526 * @param pVmcb Pointer to the VM control block.
3527 */
3528DECLINLINE(void) hmR0SvmSetIretIntercept(PSVMVMCB pVmcb)
3529{
3530 if (!(pVmcb->ctrl.u64InterceptCtrl & SVM_CTRL_INTERCEPT_IRET))
3531 {
3532 pVmcb->ctrl.u64InterceptCtrl |= SVM_CTRL_INTERCEPT_IRET;
3533 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
3534
3535 Log4(("Setting IRET intercept\n"));
3536 }
3537}
3538
3539
3540/**
3541 * Clears the IRET intercept control in the VMCB.
3542 *
3543 * @param pVmcb Pointer to the VM control block.
3544 */
3545DECLINLINE(void) hmR0SvmClearIretIntercept(PSVMVMCB pVmcb)
3546{
3547 if (pVmcb->ctrl.u64InterceptCtrl & SVM_CTRL_INTERCEPT_IRET)
3548 {
3549 pVmcb->ctrl.u64InterceptCtrl &= ~SVM_CTRL_INTERCEPT_IRET;
3550 pVmcb->ctrl.u32VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS);
3551
3552 Log4(("Clearing IRET intercept\n"));
3553 }
3554}
3555
3556#ifdef VBOX_WITH_NESTED_HWVIRT
3557
3558
3559/**
3560 * Evaluates the event to be delivered to the nested-guest and sets it as the
3561 * pending event.
3562 *
3563 * @returns VBox strict status code.
3564 * @param pVCpu The cross context virtual CPU structure.
3565 * @param pCtx Pointer to the guest-CPU context.
3566 */
3567static VBOXSTRICTRC hmR0SvmEvaluatePendingEventNested(PVMCPU pVCpu, PCPUMCTX pCtx)
3568{
3569 Log4Func(("\n"));
3570
3571 Assert(!pVCpu->hm.s.Event.fPending);
3572
3573 bool const fGif = pCtx->hwvirt.fGif;
3574 if (fGif)
3575 {
3576 PSVMVMCB pVmcbNstGst = pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
3577
3578 bool const fIntShadow = hmR0SvmIsIntrShadowActive(pVCpu, pCtx);
3579
3580 /*
3581 * Check if the nested-guest can receive NMIs.
3582 * NMIs are higher priority than regular interrupts.
3583 */
3584 /** @todo SMI. SMIs take priority over NMIs. */
3585 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI))
3586 {
3587 bool const fBlockNmi = VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS);
3588 if (fBlockNmi)
3589 hmR0SvmSetIretIntercept(pVmcbNstGst);
3590 else if (fIntShadow)
3591 {
3592 /** @todo Figure this out, how we shall manage virt. intercept if the
3593 * nested-guest already has one set and/or if we really need it? */
3594 //hmR0SvmSetVirtIntrIntercept(pVmcbNstGst);
3595 }
3596 else
3597 {
3598 if (CPUMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_NMI))
3599 {
3600 Log4(("Intercepting NMI -> #VMEXIT\n"));
3601 return IEMExecSvmVmexit(pVCpu, SVM_EXIT_NMI, 0, 0);
3602 }
3603
3604 Log4(("Pending NMI\n"));
3605 SVMEVENT Event;
3606 Event.u = 0;
3607 Event.n.u1Valid = 1;
3608 Event.n.u8Vector = X86_XCPT_NMI;
3609 Event.n.u3Type = SVM_EVENT_NMI;
3610 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3611 hmR0SvmSetIretIntercept(pVmcbNstGst);
3612 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
3613 return VINF_SUCCESS;
3614 }
3615 }
3616
3617 /*
3618 * Check if the nested-guest can receive external interrupts (generated by
3619 * the guest's PIC/APIC).
3620 *
3621 * External intercepts, NMI, SMI etc. from the physical CPU are -always- intercepted
3622 * when executing using hardware-assisted SVM, see HMSVM_MANDATORY_GUEST_CTRL_INTERCEPTS.
3623 *
3624 * External interrupts that are generated for the outer guest may be intercepted
3625 * depending on how the nested-guest VMCB was programmed by guest software.
3626 *
3627 * Physical interrupts always take priority over virtual interrupts,
3628 * see AMD spec. 15.21.4 "Injecting Virtual (INTR) Interrupts".
3629 */
3630 if (!fIntShadow)
3631 {
3632 if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)
3633 && !pVCpu->hm.s.fSingleInstruction
3634 && CPUMCanSvmNstGstTakePhysIntr(pVCpu, pCtx))
3635 {
3636 if (CPUMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_INTR))
3637 {
3638 Log4(("Intercepting external interrupt -> #VMEXIT\n"));
3639 return IEMExecSvmVmexit(pVCpu, SVM_EXIT_INTR, 0, 0);
3640 }
3641
3642 uint8_t u8Interrupt;
3643 int rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
3644 if (RT_SUCCESS(rc))
3645 {
3646 Log4(("Injecting external interrupt u8Interrupt=%#x\n", u8Interrupt));
3647 SVMEVENT Event;
3648 Event.u = 0;
3649 Event.n.u1Valid = 1;
3650 Event.n.u8Vector = u8Interrupt;
3651 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
3652 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3653 }
3654 else if (rc == VERR_APIC_INTR_MASKED_BY_TPR)
3655 {
3656 /*
3657 * AMD-V has no TPR thresholding feature. TPR and the force-flag will be
3658 * updated eventually when the TPR is written by the guest.
3659 */
3660 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchTprMaskedIrq);
3661 }
3662 else
3663 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
3664 }
3665
3666 /*
3667 * Check if the nested-guest is intercepting virtual (using V_IRQ and related fields)
3668 * interrupt injection. The virtual interrupt injection itself, if any, will be done
3669 * by the physical CPU.
3670 */
3671 /** @todo later explore this for performance reasons. Right now the hardware
3672 * takes care of virtual interrupt injection for nested-guest. */
3673#if 0
3674 if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NESTED_GUEST)
3675 && CPUMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_VINTR)
3676 && CPUMCanSvmNstGstTakeVirtIntr(pVCpu, pCtx))
3677 {
3678 Log4(("Intercepting virtual interrupt -> #VMEXIT\n"));
3679 return IEMExecSvmVmexit(pVCpu, SVM_EXIT_VINTR, 0, 0);
3680 }
3681#endif
3682 }
3683 }
3684
3685 return VINF_SUCCESS;
3686}
3687#endif
3688
3689
3690/**
3691 * Evaluates the event to be delivered to the guest and sets it as the pending
3692 * event.
3693 *
3694 * @param pVCpu The cross context virtual CPU structure.
3695 * @param pCtx Pointer to the guest-CPU context.
3696 *
3697 * @remarks Don't use this function when we are actively executing a
3698 * nested-guest, use hmR0SvmEvaluatePendingEventNested instead.
3699 */
3700static void hmR0SvmEvaluatePendingEvent(PVMCPU pVCpu, PCPUMCTX pCtx)
3701{
3702 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
3703 Assert(!pVCpu->hm.s.Event.fPending);
3704
3705#ifdef VBOX_WITH_NESTED_HWVIRT
3706 bool const fGif = pCtx->hwvirt.fGif;
3707#else
3708 bool const fGif = true;
3709#endif
3710 Log4Func(("fGif=%RTbool\n", fGif));
3711
3712 /*
3713 * If the global interrupt flag (GIF) isn't set, even NMIs and other events are blocked.
3714 * See AMD spec. Table 15-10. "Effect of the GIF on Interrupt Handling".
3715 */
3716 if (fGif)
3717 {
3718 bool const fIntShadow = hmR0SvmIsIntrShadowActive(pVCpu, pCtx);
3719 bool const fBlockInt = !(pCtx->eflags.u32 & X86_EFL_IF);
3720 bool const fBlockNmi = VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS);
3721 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
3722
3723 Log4Func(("fBlockInt=%RTbool fIntShadow=%RTbool APIC/PIC_Pending=%RTbool\n", fBlockInt, fIntShadow,
3724 VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)));
3725
3726 /** @todo SMI. SMIs take priority over NMIs. */
3727 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)) /* NMI. NMIs take priority over regular interrupts. */
3728 {
3729 if (fBlockNmi)
3730 hmR0SvmSetIretIntercept(pVmcb);
3731 else if (fIntShadow)
3732 hmR0SvmSetVirtIntrIntercept(pVmcb);
3733 else
3734 {
3735 Log4(("Pending NMI\n"));
3736
3737 SVMEVENT Event;
3738 Event.u = 0;
3739 Event.n.u1Valid = 1;
3740 Event.n.u8Vector = X86_XCPT_NMI;
3741 Event.n.u3Type = SVM_EVENT_NMI;
3742
3743 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3744 hmR0SvmSetIretIntercept(pVmcb);
3745 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
3746 return;
3747 }
3748 }
3749 else if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)
3750 && !pVCpu->hm.s.fSingleInstruction)
3751 {
3752 /*
3753 * Check if the guest can receive external interrupts (PIC/APIC). Once PDMGetInterrupt() returns
3754 * a valid interrupt we -must- deliver the interrupt. We can no longer re-request it from the APIC.
3755 */
3756 if ( !fBlockInt
3757 && !fIntShadow)
3758 {
3759 uint8_t u8Interrupt;
3760 int rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
3761 if (RT_SUCCESS(rc))
3762 {
3763 Log4(("Injecting external interrupt u8Interrupt=%#x\n", u8Interrupt));
3764
3765 SVMEVENT Event;
3766 Event.u = 0;
3767 Event.n.u1Valid = 1;
3768 Event.n.u8Vector = u8Interrupt;
3769 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
3770
3771 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3772 }
3773 else if (rc == VERR_APIC_INTR_MASKED_BY_TPR)
3774 {
3775 /*
3776 * AMD-V has no TPR thresholding feature. TPR and the force-flag will be
3777 * updated eventually when the TPR is written by the guest.
3778 */
3779 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchTprMaskedIrq);
3780 }
3781 else
3782 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
3783 }
3784 else
3785 hmR0SvmSetVirtIntrIntercept(pVmcb);
3786 }
3787 }
3788}
3789
3790
3791/**
3792 * Injects any pending events into the guest (or nested-guest).
3793 *
3794 * @param pVCpu The cross context virtual CPU structure.
3795 * @param pCtx Pointer to the guest-CPU context.
3796 * @param pVmcb Pointer to the VM control block.
3797 */
3798static void hmR0SvmInjectPendingEvent(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMVMCB pVmcb)
3799{
3800 Assert(!TRPMHasTrap(pVCpu));
3801 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
3802
3803 bool const fIntShadow = hmR0SvmIsIntrShadowActive(pVCpu, pCtx);
3804#ifdef VBOX_STRICT
3805 bool const fGif = pCtx->hwvirt.fGif;
3806 bool fAllowInt = fGif;
3807 if (fGif)
3808 {
3809 /*
3810 * For nested-guests we have no way to determine if we're injecting a physical or virtual
3811 * interrupt at this point. Hence the partial verification below.
3812 */
3813 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
3814 fAllowInt = CPUMCanSvmNstGstTakePhysIntr(pVCpu, pCtx) || CPUMCanSvmNstGstTakeVirtIntr(pVCpu, pCtx);
3815 else
3816 fAllowInt = RT_BOOL(pCtx->eflags.u32 & X86_EFL_IF);
3817 }
3818#endif
3819
3820 if (pVCpu->hm.s.Event.fPending)
3821 {
3822 SVMEVENT Event;
3823 Event.u = pVCpu->hm.s.Event.u64IntInfo;
3824 Assert(Event.n.u1Valid);
3825
3826 /*
3827 * Validate event injection pre-conditions.
3828 */
3829 if (Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ)
3830 {
3831 Assert(fAllowInt);
3832 Assert(!fIntShadow);
3833 }
3834 else if (Event.n.u3Type == SVM_EVENT_NMI)
3835 {
3836 Assert(fGif);
3837 Assert(!fIntShadow);
3838 }
3839
3840 /*
3841 * Inject it (update VMCB for injection by the hardware).
3842 */
3843 Log4(("Injecting pending HM event\n"));
3844 hmR0SvmInjectEventVmcb(pVCpu, pVmcb, pCtx, &Event);
3845 pVCpu->hm.s.Event.fPending = false;
3846
3847 if (Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ)
3848 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterrupt);
3849 else
3850 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectXcpt);
3851 }
3852 else
3853 Assert(pVmcb->ctrl.EventInject.n.u1Valid == 0);
3854
3855 /*
3856 * Update the guest interrupt shadow in the guest (or nested-guest) VMCB.
3857 *
3858 * For nested-guests: We need to update it too for the scenario where IEM executes
3859 * the nested-guest but execution later continues here with an interrupt shadow active.
3860 */
3861 pVmcb->ctrl.IntShadow.n.u1IntShadow = fIntShadow;
3862}
3863
3864
3865/**
3866 * Reports world-switch error and dumps some useful debug info.
3867 *
3868 * @param pVM The cross context VM structure.
3869 * @param pVCpu The cross context virtual CPU structure.
3870 * @param rcVMRun The return code from VMRUN (or
3871 * VERR_SVM_INVALID_GUEST_STATE for invalid
3872 * guest-state).
3873 * @param pCtx Pointer to the guest-CPU context.
3874 */
3875static void hmR0SvmReportWorldSwitchError(PVM pVM, PVMCPU pVCpu, int rcVMRun, PCPUMCTX pCtx)
3876{
3877 NOREF(pCtx);
3878 HMSVM_ASSERT_PREEMPT_SAFE();
3879 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
3880 PCSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
3881
3882 if (rcVMRun == VERR_SVM_INVALID_GUEST_STATE)
3883 {
3884 hmR0DumpRegs(pVM, pVCpu, pCtx); NOREF(pVM);
3885#ifdef VBOX_STRICT
3886 Log4(("ctrl.u32VmcbCleanBits %#RX32\n", pVmcb->ctrl.u32VmcbCleanBits));
3887 Log4(("ctrl.u16InterceptRdCRx %#x\n", pVmcb->ctrl.u16InterceptRdCRx));
3888 Log4(("ctrl.u16InterceptWrCRx %#x\n", pVmcb->ctrl.u16InterceptWrCRx));
3889 Log4(("ctrl.u16InterceptRdDRx %#x\n", pVmcb->ctrl.u16InterceptRdDRx));
3890 Log4(("ctrl.u16InterceptWrDRx %#x\n", pVmcb->ctrl.u16InterceptWrDRx));
3891 Log4(("ctrl.u32InterceptXcpt %#x\n", pVmcb->ctrl.u32InterceptXcpt));
3892 Log4(("ctrl.u64InterceptCtrl %#RX64\n", pVmcb->ctrl.u64InterceptCtrl));
3893 Log4(("ctrl.u64IOPMPhysAddr %#RX64\n", pVmcb->ctrl.u64IOPMPhysAddr));
3894 Log4(("ctrl.u64MSRPMPhysAddr %#RX64\n", pVmcb->ctrl.u64MSRPMPhysAddr));
3895 Log4(("ctrl.u64TSCOffset %#RX64\n", pVmcb->ctrl.u64TSCOffset));
3896
3897 Log4(("ctrl.TLBCtrl.u32ASID %#x\n", pVmcb->ctrl.TLBCtrl.n.u32ASID));
3898 Log4(("ctrl.TLBCtrl.u8TLBFlush %#x\n", pVmcb->ctrl.TLBCtrl.n.u8TLBFlush));
3899 Log4(("ctrl.TLBCtrl.u24Reserved %#x\n", pVmcb->ctrl.TLBCtrl.n.u24Reserved));
3900
3901 Log4(("ctrl.IntCtrl.u8VTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u8VTPR));
3902 Log4(("ctrl.IntCtrl.u1VIrqPending %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqPending));
3903 Log4(("ctrl.IntCtrl.u1VGif %#x\n", pVmcb->ctrl.IntCtrl.n.u1VGif));
3904 Log4(("ctrl.IntCtrl.u6Reserved0 %#x\n", pVmcb->ctrl.IntCtrl.n.u6Reserved));
3905 Log4(("ctrl.IntCtrl.u4VIntrPrio %#x\n", pVmcb->ctrl.IntCtrl.n.u4VIntrPrio));
3906 Log4(("ctrl.IntCtrl.u1IgnoreTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR));
3907 Log4(("ctrl.IntCtrl.u3Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u3Reserved));
3908 Log4(("ctrl.IntCtrl.u1VIntrMasking %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIntrMasking));
3909 Log4(("ctrl.IntCtrl.u1VGifEnable %#x\n", pVmcb->ctrl.IntCtrl.n.u1VGifEnable));
3910 Log4(("ctrl.IntCtrl.u5Reserved1 %#x\n", pVmcb->ctrl.IntCtrl.n.u5Reserved));
3911 Log4(("ctrl.IntCtrl.u8VIntrVector %#x\n", pVmcb->ctrl.IntCtrl.n.u8VIntrVector));
3912 Log4(("ctrl.IntCtrl.u24Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u24Reserved));
3913
3914 Log4(("ctrl.IntShadow.u1IntShadow %#x\n", pVmcb->ctrl.IntShadow.n.u1IntShadow));
3915 Log4(("ctrl.IntShadow.u1GuestIntMask %#x\n", pVmcb->ctrl.IntShadow.n.u1GuestIntMask));
3916 Log4(("ctrl.u64ExitCode %#RX64\n", pVmcb->ctrl.u64ExitCode));
3917 Log4(("ctrl.u64ExitInfo1 %#RX64\n", pVmcb->ctrl.u64ExitInfo1));
3918 Log4(("ctrl.u64ExitInfo2 %#RX64\n", pVmcb->ctrl.u64ExitInfo2));
3919 Log4(("ctrl.ExitIntInfo.u8Vector %#x\n", pVmcb->ctrl.ExitIntInfo.n.u8Vector));
3920 Log4(("ctrl.ExitIntInfo.u3Type %#x\n", pVmcb->ctrl.ExitIntInfo.n.u3Type));
3921 Log4(("ctrl.ExitIntInfo.u1ErrorCodeValid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid));
3922 Log4(("ctrl.ExitIntInfo.u19Reserved %#x\n", pVmcb->ctrl.ExitIntInfo.n.u19Reserved));
3923 Log4(("ctrl.ExitIntInfo.u1Valid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1Valid));
3924 Log4(("ctrl.ExitIntInfo.u32ErrorCode %#x\n", pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
3925 Log4(("ctrl.NestedPagingCtrl.u1NestedPaging %#x\n", pVmcb->ctrl.NestedPagingCtrl.n.u1NestedPaging));
3926 Log4(("ctrl.NestedPagingCtrl.u1Sev %#x\n", pVmcb->ctrl.NestedPagingCtrl.n.u1Sev));
3927 Log4(("ctrl.NestedPagingCtrl.u1SevEs %#x\n", pVmcb->ctrl.NestedPagingCtrl.n.u1SevEs));
3928 Log4(("ctrl.EventInject.u8Vector %#x\n", pVmcb->ctrl.EventInject.n.u8Vector));
3929 Log4(("ctrl.EventInject.u3Type %#x\n", pVmcb->ctrl.EventInject.n.u3Type));
3930 Log4(("ctrl.EventInject.u1ErrorCodeValid %#x\n", pVmcb->ctrl.EventInject.n.u1ErrorCodeValid));
3931 Log4(("ctrl.EventInject.u19Reserved %#x\n", pVmcb->ctrl.EventInject.n.u19Reserved));
3932 Log4(("ctrl.EventInject.u1Valid %#x\n", pVmcb->ctrl.EventInject.n.u1Valid));
3933 Log4(("ctrl.EventInject.u32ErrorCode %#x\n", pVmcb->ctrl.EventInject.n.u32ErrorCode));
3934
3935 Log4(("ctrl.u64NestedPagingCR3 %#RX64\n", pVmcb->ctrl.u64NestedPagingCR3));
3936
3937 Log4(("ctrl.LbrVirt.u1LbrVirt %#x\n", pVmcb->ctrl.LbrVirt.n.u1LbrVirt));
3938 Log4(("ctrl.LbrVirt.u1VirtVmsaveVmload %#x\n", pVmcb->ctrl.LbrVirt.n.u1VirtVmsaveVmload));
3939
3940 Log4(("guest.CS.u16Sel %RTsel\n", pVmcb->guest.CS.u16Sel));
3941 Log4(("guest.CS.u16Attr %#x\n", pVmcb->guest.CS.u16Attr));
3942 Log4(("guest.CS.u32Limit %#RX32\n", pVmcb->guest.CS.u32Limit));
3943 Log4(("guest.CS.u64Base %#RX64\n", pVmcb->guest.CS.u64Base));
3944 Log4(("guest.DS.u16Sel %#RTsel\n", pVmcb->guest.DS.u16Sel));
3945 Log4(("guest.DS.u16Attr %#x\n", pVmcb->guest.DS.u16Attr));
3946 Log4(("guest.DS.u32Limit %#RX32\n", pVmcb->guest.DS.u32Limit));
3947 Log4(("guest.DS.u64Base %#RX64\n", pVmcb->guest.DS.u64Base));
3948 Log4(("guest.ES.u16Sel %RTsel\n", pVmcb->guest.ES.u16Sel));
3949 Log4(("guest.ES.u16Attr %#x\n", pVmcb->guest.ES.u16Attr));
3950 Log4(("guest.ES.u32Limit %#RX32\n", pVmcb->guest.ES.u32Limit));
3951 Log4(("guest.ES.u64Base %#RX64\n", pVmcb->guest.ES.u64Base));
3952 Log4(("guest.FS.u16Sel %RTsel\n", pVmcb->guest.FS.u16Sel));
3953 Log4(("guest.FS.u16Attr %#x\n", pVmcb->guest.FS.u16Attr));
3954 Log4(("guest.FS.u32Limit %#RX32\n", pVmcb->guest.FS.u32Limit));
3955 Log4(("guest.FS.u64Base %#RX64\n", pVmcb->guest.FS.u64Base));
3956 Log4(("guest.GS.u16Sel %RTsel\n", pVmcb->guest.GS.u16Sel));
3957 Log4(("guest.GS.u16Attr %#x\n", pVmcb->guest.GS.u16Attr));
3958 Log4(("guest.GS.u32Limit %#RX32\n", pVmcb->guest.GS.u32Limit));
3959 Log4(("guest.GS.u64Base %#RX64\n", pVmcb->guest.GS.u64Base));
3960
3961 Log4(("guest.GDTR.u32Limit %#RX32\n", pVmcb->guest.GDTR.u32Limit));
3962 Log4(("guest.GDTR.u64Base %#RX64\n", pVmcb->guest.GDTR.u64Base));
3963
3964 Log4(("guest.LDTR.u16Sel %RTsel\n", pVmcb->guest.LDTR.u16Sel));
3965 Log4(("guest.LDTR.u16Attr %#x\n", pVmcb->guest.LDTR.u16Attr));
3966 Log4(("guest.LDTR.u32Limit %#RX32\n", pVmcb->guest.LDTR.u32Limit));
3967 Log4(("guest.LDTR.u64Base %#RX64\n", pVmcb->guest.LDTR.u64Base));
3968
3969 Log4(("guest.IDTR.u32Limit %#RX32\n", pVmcb->guest.IDTR.u32Limit));
3970 Log4(("guest.IDTR.u64Base %#RX64\n", pVmcb->guest.IDTR.u64Base));
3971
3972 Log4(("guest.TR.u16Sel %RTsel\n", pVmcb->guest.TR.u16Sel));
3973 Log4(("guest.TR.u16Attr %#x\n", pVmcb->guest.TR.u16Attr));
3974 Log4(("guest.TR.u32Limit %#RX32\n", pVmcb->guest.TR.u32Limit));
3975 Log4(("guest.TR.u64Base %#RX64\n", pVmcb->guest.TR.u64Base));
3976
3977 Log4(("guest.u8CPL %#x\n", pVmcb->guest.u8CPL));
3978 Log4(("guest.u64CR0 %#RX64\n", pVmcb->guest.u64CR0));
3979 Log4(("guest.u64CR2 %#RX64\n", pVmcb->guest.u64CR2));
3980 Log4(("guest.u64CR3 %#RX64\n", pVmcb->guest.u64CR3));
3981 Log4(("guest.u64CR4 %#RX64\n", pVmcb->guest.u64CR4));
3982 Log4(("guest.u64DR6 %#RX64\n", pVmcb->guest.u64DR6));
3983 Log4(("guest.u64DR7 %#RX64\n", pVmcb->guest.u64DR7));
3984
3985 Log4(("guest.u64RIP %#RX64\n", pVmcb->guest.u64RIP));
3986 Log4(("guest.u64RSP %#RX64\n", pVmcb->guest.u64RSP));
3987 Log4(("guest.u64RAX %#RX64\n", pVmcb->guest.u64RAX));
3988 Log4(("guest.u64RFlags %#RX64\n", pVmcb->guest.u64RFlags));
3989
3990 Log4(("guest.u64SysEnterCS %#RX64\n", pVmcb->guest.u64SysEnterCS));
3991 Log4(("guest.u64SysEnterEIP %#RX64\n", pVmcb->guest.u64SysEnterEIP));
3992 Log4(("guest.u64SysEnterESP %#RX64\n", pVmcb->guest.u64SysEnterESP));
3993
3994 Log4(("guest.u64EFER %#RX64\n", pVmcb->guest.u64EFER));
3995 Log4(("guest.u64STAR %#RX64\n", pVmcb->guest.u64STAR));
3996 Log4(("guest.u64LSTAR %#RX64\n", pVmcb->guest.u64LSTAR));
3997 Log4(("guest.u64CSTAR %#RX64\n", pVmcb->guest.u64CSTAR));
3998 Log4(("guest.u64SFMASK %#RX64\n", pVmcb->guest.u64SFMASK));
3999 Log4(("guest.u64KernelGSBase %#RX64\n", pVmcb->guest.u64KernelGSBase));
4000 Log4(("guest.u64PAT %#RX64\n", pVmcb->guest.u64PAT));
4001 Log4(("guest.u64DBGCTL %#RX64\n", pVmcb->guest.u64DBGCTL));
4002 Log4(("guest.u64BR_FROM %#RX64\n", pVmcb->guest.u64BR_FROM));
4003 Log4(("guest.u64BR_TO %#RX64\n", pVmcb->guest.u64BR_TO));
4004 Log4(("guest.u64LASTEXCPFROM %#RX64\n", pVmcb->guest.u64LASTEXCPFROM));
4005 Log4(("guest.u64LASTEXCPTO %#RX64\n", pVmcb->guest.u64LASTEXCPTO));
4006#endif /* VBOX_STRICT */
4007 }
4008 else
4009 Log4(("hmR0SvmReportWorldSwitchError: rcVMRun=%d\n", rcVMRun));
4010
4011 NOREF(pVmcb);
4012}
4013
4014
4015/**
4016 * Check per-VM and per-VCPU force flag actions that require us to go back to
4017 * ring-3 for one reason or another.
4018 *
4019 * @returns VBox status code (information status code included).
4020 * @retval VINF_SUCCESS if we don't have any actions that require going back to
4021 * ring-3.
4022 * @retval VINF_PGM_SYNC_CR3 if we have pending PGM CR3 sync.
4023 * @retval VINF_EM_PENDING_REQUEST if we have pending requests (like hardware
4024 * interrupts)
4025 * @retval VINF_PGM_POOL_FLUSH_PENDING if PGM is doing a pool flush and requires
4026 * all EMTs to be in ring-3.
4027 * @retval VINF_EM_RAW_TO_R3 if there is pending DMA requests.
4028 * @retval VINF_EM_NO_MEMORY PGM is out of memory, we need to return
4029 * to the EM loop.
4030 *
4031 * @param pVM The cross context VM structure.
4032 * @param pVCpu The cross context virtual CPU structure.
4033 * @param pCtx Pointer to the guest-CPU context.
4034 */
4035static int hmR0SvmCheckForceFlags(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4036{
4037 Assert(VMMRZCallRing3IsEnabled(pVCpu));
4038
4039 /* On AMD-V we don't need to update CR3, PAE PDPES lazily. See hmR0SvmSaveGuestState(). */
4040 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
4041 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
4042
4043 /* Update pending interrupts into the APIC's IRR. */
4044 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_UPDATE_APIC))
4045 APICUpdatePendingInterrupts(pVCpu);
4046
4047 if ( VM_FF_IS_PENDING(pVM, !pVCpu->hm.s.fSingleInstruction
4048 ? VM_FF_HP_R0_PRE_HM_MASK : VM_FF_HP_R0_PRE_HM_STEP_MASK)
4049 || VMCPU_FF_IS_PENDING(pVCpu, !pVCpu->hm.s.fSingleInstruction
4050 ? VMCPU_FF_HP_R0_PRE_HM_MASK : VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
4051 {
4052 /* Pending PGM C3 sync. */
4053 if (VMCPU_FF_IS_PENDING(pVCpu,VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
4054 {
4055 int rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
4056 if (rc != VINF_SUCCESS)
4057 {
4058 Log4(("hmR0SvmCheckForceFlags: PGMSyncCR3 forcing us back to ring-3. rc=%d\n", rc));
4059 return rc;
4060 }
4061 }
4062
4063 /* Pending HM-to-R3 operations (critsects, timers, EMT rendezvous etc.) */
4064 /* -XXX- what was that about single stepping? */
4065 if ( VM_FF_IS_PENDING(pVM, VM_FF_HM_TO_R3_MASK)
4066 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
4067 {
4068 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
4069 int rc = RT_UNLIKELY(VM_FF_IS_PENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
4070 Log4(("hmR0SvmCheckForceFlags: HM_TO_R3 forcing us back to ring-3. rc=%d\n", rc));
4071 return rc;
4072 }
4073
4074 /* Pending VM request packets, such as hardware interrupts. */
4075 if ( VM_FF_IS_PENDING(pVM, VM_FF_REQUEST)
4076 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_REQUEST))
4077 {
4078 Log4(("hmR0SvmCheckForceFlags: Pending VM request forcing us back to ring-3\n"));
4079 return VINF_EM_PENDING_REQUEST;
4080 }
4081
4082 /* Pending PGM pool flushes. */
4083 if (VM_FF_IS_PENDING(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
4084 {
4085 Log4(("hmR0SvmCheckForceFlags: PGM pool flush pending forcing us back to ring-3\n"));
4086 return VINF_PGM_POOL_FLUSH_PENDING;
4087 }
4088
4089 /* Pending DMA requests. */
4090 if (VM_FF_IS_PENDING(pVM, VM_FF_PDM_DMA))
4091 {
4092 Log4(("hmR0SvmCheckForceFlags: Pending DMA request forcing us back to ring-3\n"));
4093 return VINF_EM_RAW_TO_R3;
4094 }
4095 }
4096
4097 return VINF_SUCCESS;
4098}
4099
4100
4101#ifdef VBOX_WITH_NESTED_HWVIRT
4102/**
4103 * Does the preparations before executing nested-guest code in AMD-V.
4104 *
4105 * @returns VBox status code (informational status codes included).
4106 * @retval VINF_SUCCESS if we can proceed with running the guest.
4107 * @retval VINF_* scheduling changes, we have to go back to ring-3.
4108 *
4109 * @param pVM The cross context VM structure.
4110 * @param pVCpu The cross context virtual CPU structure.
4111 * @param pCtx Pointer to the nested-guest-CPU context.
4112 * @param pSvmTransient Pointer to the SVM transient structure.
4113 *
4114 * @remarks Same caveats regarding longjumps as hmR0SvmPreRunGuest applies.
4115 * @sa hmR0SvmPreRunGuest.
4116 */
4117static int hmR0SvmPreRunGuestNested(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4118{
4119 HMSVM_ASSERT_PREEMPT_SAFE();
4120
4121 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
4122 {
4123#ifdef VBOX_WITH_NESTED_HWVIRT_ONLY_IN_IEM
4124 Log2(("hmR0SvmPreRunGuest: Rescheduling to IEM due to nested-hwvirt or forced IEM exec -> VINF_EM_RESCHEDULE_REM\n"));
4125 return VINF_EM_RESCHEDULE_REM;
4126#endif
4127 }
4128 else
4129 return VINF_SVM_VMEXIT;
4130
4131 /* Check force flag actions that might require us to go back to ring-3. */
4132 int rc = hmR0SvmCheckForceFlags(pVM, pVCpu, pCtx);
4133 if (rc != VINF_SUCCESS)
4134 return rc;
4135
4136 if (TRPMHasTrap(pVCpu))
4137 hmR0SvmTrpmTrapToPendingEvent(pVCpu);
4138 else if (!pVCpu->hm.s.Event.fPending)
4139 {
4140 VBOXSTRICTRC rcStrict = hmR0SvmEvaluatePendingEventNested(pVCpu, pCtx);
4141 if (rcStrict != VINF_SUCCESS)
4142 return VBOXSTRICTRC_VAL(rcStrict);
4143 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
4144 return VINF_SVM_VMEXIT;
4145 }
4146
4147 /*
4148 * On the oldest AMD-V systems, we may not get enough information to reinject an NMI.
4149 * Just do it in software, see @bugref{8411}.
4150 * NB: If we could continue a task switch exit we wouldn't need to do this.
4151 */
4152 if (RT_UNLIKELY( !pVM->hm.s.svm.u32Features
4153 && pVCpu->hm.s.Event.fPending
4154 && SVM_EVENT_GET_TYPE(pVCpu->hm.s.Event.u64IntInfo) == SVM_EVENT_NMI))
4155 {
4156 return VINF_EM_RAW_INJECT_TRPM_EVENT;
4157 }
4158
4159#ifdef HMSVM_SYNC_FULL_NESTED_GUEST_STATE
4160 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
4161#endif
4162
4163 /*
4164 * Set up the nested-guest VMCB for execution using hardware-assisted SVM.
4165 */
4166 hmR0SvmVmRunSetupVmcb(pVCpu, pCtx);
4167
4168 /*
4169 * Load the nested-guest state.
4170 */
4171 rc = hmR0SvmLoadGuestStateNested(pVCpu, pCtx);
4172 AssertRCReturn(rc, rc);
4173 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadFull); /** @todo Get new STAM counter for this? */
4174
4175 /* Ensure we've cached (and hopefully modified) the VMCB for execution using hardware-assisted SVM. */
4176 Assert(pCtx->hwvirt.svm.fHMCachedVmcb);
4177
4178 /*
4179 * No longjmps to ring-3 from this point on!!!
4180 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
4181 * This also disables flushing of the R0-logger instance (if any).
4182 */
4183 VMMRZCallRing3Disable(pVCpu);
4184
4185 /*
4186 * We disable interrupts so that we don't miss any interrupts that would flag preemption (IPI/timers etc.)
4187 * when thread-context hooks aren't used and we've been running with preemption disabled for a while.
4188 *
4189 * We need to check for force-flags that could've possible been altered since we last checked them (e.g.
4190 * by PDMGetInterrupt() leaving the PDM critical section, see @bugref{6398}).
4191 *
4192 * We also check a couple of other force-flags as a last opportunity to get the EMT back to ring-3 before
4193 * executing guest code.
4194 */
4195 pSvmTransient->fEFlags = ASMIntDisableFlags();
4196 if ( VM_FF_IS_PENDING(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
4197 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
4198 {
4199 ASMSetFlags(pSvmTransient->fEFlags);
4200 VMMRZCallRing3Enable(pVCpu);
4201 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
4202 return VINF_EM_RAW_TO_R3;
4203 }
4204 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
4205 {
4206 ASMSetFlags(pSvmTransient->fEFlags);
4207 VMMRZCallRing3Enable(pVCpu);
4208 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
4209 return VINF_EM_RAW_INTERRUPT;
4210 }
4211
4212 /*
4213 * If we are injecting an NMI, we must set VMCPU_FF_BLOCK_NMIS only when we are going to execute
4214 * guest code for certain (no exits to ring-3). Otherwise, we could re-read the flag on re-entry into
4215 * AMD-V and conclude that NMI inhibition is active when we have not even delivered the NMI.
4216 *
4217 * With VT-x, this is handled by the Guest interruptibility information VMCS field which will set the
4218 * VMCS field after actually delivering the NMI which we read on VM-exit to determine the state.
4219 */
4220 if (pVCpu->hm.s.Event.fPending)
4221 {
4222 SVMEVENT Event;
4223 Event.u = pVCpu->hm.s.Event.u64IntInfo;
4224 if ( Event.n.u1Valid
4225 && Event.n.u3Type == SVM_EVENT_NMI
4226 && Event.n.u8Vector == X86_XCPT_NMI
4227 && !VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
4228 {
4229 VMCPU_FF_SET(pVCpu, VMCPU_FF_BLOCK_NMIS);
4230 }
4231 }
4232
4233 return VINF_SUCCESS;
4234}
4235#endif
4236
4237
4238/**
4239 * Does the preparations before executing guest code in AMD-V.
4240 *
4241 * This may cause longjmps to ring-3 and may even result in rescheduling to the
4242 * recompiler. We must be cautious what we do here regarding committing
4243 * guest-state information into the VMCB assuming we assuredly execute the guest
4244 * in AMD-V. If we fall back to the recompiler after updating the VMCB and
4245 * clearing the common-state (TRPM/forceflags), we must undo those changes so
4246 * that the recompiler can (and should) use them when it resumes guest
4247 * execution. Otherwise such operations must be done when we can no longer
4248 * exit to ring-3.
4249 *
4250 * @returns VBox status code (informational status codes included).
4251 * @retval VINF_SUCCESS if we can proceed with running the guest.
4252 * @retval VINF_* scheduling changes, we have to go back to ring-3.
4253 *
4254 * @param pVM The cross context VM structure.
4255 * @param pVCpu The cross context virtual CPU structure.
4256 * @param pCtx Pointer to the guest-CPU context.
4257 * @param pSvmTransient Pointer to the SVM transient structure.
4258 */
4259static int hmR0SvmPreRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4260{
4261 HMSVM_ASSERT_PREEMPT_SAFE();
4262 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
4263
4264 /* Check force flag actions that might require us to go back to ring-3. */
4265 int rc = hmR0SvmCheckForceFlags(pVM, pVCpu, pCtx);
4266 if (rc != VINF_SUCCESS)
4267 return rc;
4268
4269 if (TRPMHasTrap(pVCpu))
4270 hmR0SvmTrpmTrapToPendingEvent(pVCpu);
4271 else if (!pVCpu->hm.s.Event.fPending)
4272 hmR0SvmEvaluatePendingEvent(pVCpu, pCtx);
4273
4274 /*
4275 * On the oldest AMD-V systems, we may not get enough information to reinject an NMI.
4276 * Just do it in software, see @bugref{8411}.
4277 * NB: If we could continue a task switch exit we wouldn't need to do this.
4278 */
4279 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending && (((pVCpu->hm.s.Event.u64IntInfo >> 8) & 7) == SVM_EVENT_NMI)))
4280 if (RT_UNLIKELY(!pVM->hm.s.svm.u32Features))
4281 return VINF_EM_RAW_INJECT_TRPM_EVENT;
4282
4283#ifdef HMSVM_SYNC_FULL_GUEST_STATE
4284 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
4285#endif
4286
4287 /* Load the guest bits that are not shared with the host in any way since we can longjmp or get preempted. */
4288 rc = hmR0SvmLoadGuestState(pVM, pVCpu, pCtx);
4289 AssertRCReturn(rc, rc);
4290 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadFull);
4291
4292 /*
4293 * If we're not intercepting TPR changes in the guest, save the guest TPR before the world-switch
4294 * so we can update it on the way back if the guest changed the TPR.
4295 */
4296 if (pVCpu->hm.s.svm.fSyncVTpr)
4297 {
4298 if (pVM->hm.s.fTPRPatchingActive)
4299 pSvmTransient->u8GuestTpr = pCtx->msrLSTAR;
4300 else
4301 {
4302 PCSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
4303 pSvmTransient->u8GuestTpr = pVmcb->ctrl.IntCtrl.n.u8VTPR;
4304 }
4305 }
4306
4307 /*
4308 * No longjmps to ring-3 from this point on!!!
4309 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
4310 * This also disables flushing of the R0-logger instance (if any).
4311 */
4312 VMMRZCallRing3Disable(pVCpu);
4313
4314 /*
4315 * We disable interrupts so that we don't miss any interrupts that would flag preemption (IPI/timers etc.)
4316 * when thread-context hooks aren't used and we've been running with preemption disabled for a while.
4317 *
4318 * We need to check for force-flags that could've possible been altered since we last checked them (e.g.
4319 * by PDMGetInterrupt() leaving the PDM critical section, see @bugref{6398}).
4320 *
4321 * We also check a couple of other force-flags as a last opportunity to get the EMT back to ring-3 before
4322 * executing guest code.
4323 */
4324 pSvmTransient->fEFlags = ASMIntDisableFlags();
4325 if ( VM_FF_IS_PENDING(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
4326 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
4327 {
4328 ASMSetFlags(pSvmTransient->fEFlags);
4329 VMMRZCallRing3Enable(pVCpu);
4330 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
4331 return VINF_EM_RAW_TO_R3;
4332 }
4333 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
4334 {
4335 ASMSetFlags(pSvmTransient->fEFlags);
4336 VMMRZCallRing3Enable(pVCpu);
4337 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
4338 return VINF_EM_RAW_INTERRUPT;
4339 }
4340
4341 /*
4342 * If we are injecting an NMI, we must set VMCPU_FF_BLOCK_NMIS only when we are going to execute
4343 * guest code for certain (no exits to ring-3). Otherwise, we could re-read the flag on re-entry into
4344 * AMD-V and conclude that NMI inhibition is active when we have not even delivered the NMI.
4345 *
4346 * With VT-x, this is handled by the Guest interruptibility information VMCS field which will set the
4347 * VMCS field after actually delivering the NMI which we read on VM-exit to determine the state.
4348 */
4349 if (pVCpu->hm.s.Event.fPending)
4350 {
4351 SVMEVENT Event;
4352 Event.u = pVCpu->hm.s.Event.u64IntInfo;
4353 if ( Event.n.u1Valid
4354 && Event.n.u3Type == SVM_EVENT_NMI
4355 && Event.n.u8Vector == X86_XCPT_NMI
4356 && !VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
4357 {
4358 VMCPU_FF_SET(pVCpu, VMCPU_FF_BLOCK_NMIS);
4359 }
4360 }
4361
4362 return VINF_SUCCESS;
4363}
4364
4365
4366/**
4367 * Prepares to run guest (or nested-guest) code in AMD-V and we've committed to
4368 * doing so.
4369 *
4370 * This means there is no backing out to ring-3 or anywhere else at this point.
4371 *
4372 * @param pVCpu The cross context virtual CPU structure.
4373 * @param pCtx Pointer to the guest-CPU context.
4374 * @param pSvmTransient Pointer to the SVM transient structure.
4375 *
4376 * @remarks Called with preemption disabled.
4377 * @remarks No-long-jump zone!!!
4378 */
4379static void hmR0SvmPreRunGuestCommitted(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4380{
4381 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
4382 Assert(VMMR0IsLogFlushDisabled(pVCpu));
4383 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4384
4385 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
4386 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC); /* Indicate the start of guest execution. */
4387
4388 PVM pVM = pVCpu->CTX_SUFF(pVM);
4389 PSVMVMCB pVmcb = pSvmTransient->pVmcb;
4390 hmR0SvmInjectPendingEvent(pVCpu, pCtx, pVmcb);
4391
4392 if (!CPUMIsGuestFPUStateActive(pVCpu))
4393 {
4394 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestFpuState, x);
4395 CPUMR0LoadGuestFPU(pVM, pVCpu); /* (Ignore rc, no need to set HM_CHANGED_HOST_CONTEXT for SVM.) */
4396 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestFpuState, x);
4397 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadGuestFpu);
4398 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
4399 }
4400
4401 /* Load the state shared between host and guest (FPU, debug). */
4402 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_GUEST_SHARED_STATE))
4403 hmR0SvmLoadSharedState(pVCpu, pVmcb, pCtx);
4404
4405 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_HOST_CONTEXT); /* Preemption might set this, nothing to do on AMD-V. */
4406 AssertMsg(!HMCPU_CF_VALUE(pVCpu), ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
4407
4408 PHMGLOBALCPUINFO pHostCpu = hmR0GetCurrentCpu();
4409 RTCPUID const idHostCpu = pHostCpu->idCpu;
4410 bool const fMigratedHostCpu = idHostCpu != pVCpu->hm.s.idLastCpu;
4411
4412 /* Setup TSC offsetting. */
4413 if ( pSvmTransient->fUpdateTscOffsetting
4414 || fMigratedHostCpu)
4415 {
4416 hmR0SvmUpdateTscOffsetting(pVM, pVCpu, pCtx, pVmcb);
4417 pSvmTransient->fUpdateTscOffsetting = false;
4418 }
4419
4420 /* If we've migrating CPUs, mark the VMCB Clean bits as dirty. */
4421 if (fMigratedHostCpu)
4422 pVmcb->ctrl.u32VmcbCleanBits = 0;
4423
4424 /* Store status of the shared guest-host state at the time of VMRUN. */
4425#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
4426 if (CPUMIsGuestInLongModeEx(pCtx))
4427 {
4428 pSvmTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActivePending(pVCpu);
4429 pSvmTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActivePending(pVCpu);
4430 }
4431 else
4432#endif
4433 {
4434 pSvmTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActive(pVCpu);
4435 pSvmTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActive(pVCpu);
4436 }
4437
4438 uint8_t *pbMsrBitmap;
4439 if (!pSvmTransient->fIsNestedGuest)
4440 pbMsrBitmap = (uint8_t *)pVCpu->hm.s.svm.pvMsrBitmap;
4441 else
4442 {
4443 hmR0SvmMergeMsrpmNested(pHostCpu, pVCpu, pCtx);
4444
4445 /* Update the nested-guest VMCB with the newly merged MSRPM (clean bits updated below). */
4446 pVmcb->ctrl.u64MSRPMPhysAddr = pHostCpu->n.svm.HCPhysNstGstMsrpm;
4447 pbMsrBitmap = (uint8_t *)pHostCpu->n.svm.pvNstGstMsrpm;
4448 }
4449
4450 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB flushing, set this across the world switch. */
4451 /* Flush the appropriate tagged-TLB entries. */
4452 hmR0SvmFlushTaggedTlb(pVCpu, pCtx, pVmcb, pHostCpu);
4453 Assert(pVCpu->hm.s.idLastCpu == idHostCpu);
4454
4455 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
4456
4457 TMNotifyStartOfExecution(pVCpu); /* Finally, notify TM to resume its clocks as we're about
4458 to start executing. */
4459
4460 /*
4461 * Save the current Host TSC_AUX and write the guest TSC_AUX to the host, so that
4462 * RDTSCPs (that don't cause exits) reads the guest MSR. See @bugref{3324}.
4463 *
4464 * This should be done -after- any RDTSCPs for obtaining the host timestamp (TM, STAM etc).
4465 */
4466 if ( (pVM->hm.s.cpuid.u32AMDFeatureEDX & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
4467 && !(pVmcb->ctrl.u64InterceptCtrl & SVM_CTRL_INTERCEPT_RDTSCP))
4468 {
4469 uint64_t const uGuestTscAux = CPUMR0GetGuestTscAux(pVCpu);
4470 pVCpu->hm.s.u64HostTscAux = ASMRdMsr(MSR_K8_TSC_AUX);
4471 if (uGuestTscAux != pVCpu->hm.s.u64HostTscAux)
4472 ASMWrMsr(MSR_K8_TSC_AUX, uGuestTscAux);
4473 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_TSC_AUX, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
4474 pSvmTransient->fRestoreTscAuxMsr = true;
4475 }
4476 else
4477 {
4478 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_TSC_AUX, SVMMSREXIT_INTERCEPT_READ, SVMMSREXIT_INTERCEPT_WRITE);
4479 pSvmTransient->fRestoreTscAuxMsr = false;
4480 }
4481 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_IOPM_MSRPM;
4482
4483 /*
4484 * If VMCB Clean bits isn't supported by the CPU or exposed to the guest in the
4485 * nested virtualization case, mark all state-bits as dirty indicating to the
4486 * CPU to re-load from VMCB.
4487 */
4488 bool const fSupportsVmcbCleanBits = hmR0SvmSupportsVmcbCleanBits(pVCpu, pCtx);
4489 if (!fSupportsVmcbCleanBits)
4490 pVmcb->ctrl.u32VmcbCleanBits = 0;
4491}
4492
4493
4494/**
4495 * Wrapper for running the guest code in AMD-V.
4496 *
4497 * @returns VBox strict status code.
4498 * @param pVM The cross context VM structure.
4499 * @param pVCpu The cross context virtual CPU structure.
4500 * @param pCtx Pointer to the guest-CPU context.
4501 *
4502 * @remarks No-long-jump zone!!!
4503 */
4504DECLINLINE(int) hmR0SvmRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4505{
4506 /*
4507 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses floating-point operations
4508 * using SSE instructions. Some XMM registers (XMM6-XMM15) are callee-saved and thus the need for this XMM wrapper.
4509 * Refer MSDN docs. "Configuring Programs for 64-bit / x64 Software Conventions / Register Usage" for details.
4510 */
4511#ifdef VBOX_WITH_KERNEL_USING_XMM
4512 return hmR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
4513 pVCpu->hm.s.svm.pfnVMRun);
4514#else
4515 return pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
4516#endif
4517}
4518
4519#ifdef VBOX_WITH_NESTED_HWVIRT
4520/**
4521 * Wrapper for running the nested-guest code in AMD-V.
4522 *
4523 * @returns VBox strict status code.
4524 * @param pVM The cross context VM structure.
4525 * @param pVCpu The cross context virtual CPU structure.
4526 * @param pCtx Pointer to the guest-CPU context.
4527 *
4528 * @remarks No-long-jump zone!!!
4529 */
4530DECLINLINE(int) hmR0SvmRunGuestNested(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4531{
4532 /*
4533 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses floating-point operations
4534 * using SSE instructions. Some XMM registers (XMM6-XMM15) are callee-saved and thus the need for this XMM wrapper.
4535 * Refer MSDN docs. "Configuring Programs for 64-bit / x64 Software Conventions / Register Usage" for details.
4536 */
4537#ifdef VBOX_WITH_KERNEL_USING_XMM
4538 return hmR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pCtx->hwvirt.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
4539 pVCpu->hm.s.svm.pfnVMRun);
4540#else
4541 return pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pCtx->hwvirt.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
4542#endif
4543}
4544#endif
4545
4546/**
4547 * Performs some essential restoration of state after running guest (or
4548 * nested-guest) code in AMD-V.
4549 *
4550 * @param pVCpu The cross context virtual CPU structure.
4551 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
4552 * out-of-sync. Make sure to update the required fields
4553 * before using them.
4554 * @param pSvmTransient Pointer to the SVM transient structure.
4555 * @param rcVMRun Return code of VMRUN.
4556 *
4557 * @remarks Called with interrupts disabled.
4558 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
4559 * unconditionally when it is safe to do so.
4560 */
4561static void hmR0SvmPostRunGuest(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PSVMTRANSIENT pSvmTransient, int rcVMRun)
4562{
4563 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
4564
4565 uint64_t const uHostTsc = ASMReadTSC(); /* Read the TSC as soon as possible. */
4566 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB flushing. */
4567 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for EMT poking. */
4568
4569 PSVMVMCB pVmcb = pSvmTransient->pVmcb;
4570 PSVMVMCBCTRL pVmcbCtrl = &pVmcb->ctrl;
4571
4572 /* TSC read must be done early for maximum accuracy. */
4573 if (!(pVmcbCtrl->u64InterceptCtrl & SVM_CTRL_INTERCEPT_RDTSC))
4574 {
4575 if (!pSvmTransient->fIsNestedGuest)
4576 TMCpuTickSetLastSeen(pVCpu, uHostTsc + pVmcbCtrl->u64TSCOffset);
4577 else
4578 {
4579 /*
4580 * Undo what we did in hmR0SvmUpdateTscOffsetting() and HMSvmNstGstApplyTscOffset()
4581 * but don't restore the nested-guest VMCB TSC offset here. It shall eventually be
4582 * restored on #VMEXIT in HMSvmNstGstVmExitNotify().
4583 */
4584 PCSVMNESTEDVMCBCACHE pVmcbNstGstCache = hmR0SvmGetNestedVmcbCache(pVCpu, pMixedCtx);
4585 TMCpuTickSetLastSeen(pVCpu, uHostTsc + pVmcbCtrl->u64TSCOffset - pVmcbNstGstCache->u64TSCOffset);
4586 }
4587 }
4588
4589 if (pSvmTransient->fRestoreTscAuxMsr)
4590 {
4591 uint64_t u64GuestTscAuxMsr = ASMRdMsr(MSR_K8_TSC_AUX);
4592 CPUMR0SetGuestTscAux(pVCpu, u64GuestTscAuxMsr);
4593 if (u64GuestTscAuxMsr != pVCpu->hm.s.u64HostTscAux)
4594 ASMWrMsr(MSR_K8_TSC_AUX, pVCpu->hm.s.u64HostTscAux);
4595 }
4596
4597 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatExit1, x);
4598 TMNotifyEndOfExecution(pVCpu); /* Notify TM that the guest is no longer running. */
4599 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
4600
4601 Assert(!(ASMGetFlags() & X86_EFL_IF));
4602 ASMSetFlags(pSvmTransient->fEFlags); /* Enable interrupts. */
4603 VMMRZCallRing3Enable(pVCpu); /* It is now safe to do longjmps to ring-3!!! */
4604
4605 /* If VMRUN failed, we can bail out early. This does -not- cover SVM_EXIT_INVALID. */
4606 if (RT_UNLIKELY(rcVMRun != VINF_SUCCESS))
4607 {
4608 Log4(("VMRUN failure: rcVMRun=%Rrc\n", rcVMRun));
4609 return;
4610 }
4611
4612 pSvmTransient->u64ExitCode = pVmcbCtrl->u64ExitCode; /* Save the #VMEXIT reason. */
4613 HMCPU_EXIT_HISTORY_ADD(pVCpu, pVmcbCtrl->u64ExitCode); /* Update the #VMEXIT history array. */
4614 pVmcbCtrl->u32VmcbCleanBits = HMSVM_VMCB_CLEAN_ALL; /* Mark the VMCB-state cache as unmodified by VMM. */
4615 pSvmTransient->fVectoringDoublePF = false; /* Vectoring double page-fault needs to be determined later. */
4616 pSvmTransient->fVectoringPF = false; /* Vectoring page-fault needs to be determined later. */
4617
4618 hmR0SvmSaveGuestState(pVCpu, pMixedCtx, pVmcb); /* Save the guest state from the VMCB to the guest-CPU context. */
4619
4620 if ( pSvmTransient->u64ExitCode != SVM_EXIT_INVALID
4621 && pVCpu->hm.s.svm.fSyncVTpr)
4622 {
4623 Assert(!pSvmTransient->fIsNestedGuest);
4624 /* TPR patching (for 32-bit guests) uses LSTAR MSR for holding the TPR value, otherwise uses the VTPR. */
4625 if ( pVCpu->CTX_SUFF(pVM)->hm.s.fTPRPatchingActive
4626 && (pMixedCtx->msrLSTAR & 0xff) != pSvmTransient->u8GuestTpr)
4627 {
4628 int rc = APICSetTpr(pVCpu, pMixedCtx->msrLSTAR & 0xff);
4629 AssertRC(rc);
4630 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
4631 }
4632 /* Sync TPR when we aren't intercepting CR8 writes. */
4633 else if (pSvmTransient->u8GuestTpr != pVmcbCtrl->IntCtrl.n.u8VTPR)
4634 {
4635 int rc = APICSetTpr(pVCpu, pVmcbCtrl->IntCtrl.n.u8VTPR << 4);
4636 AssertRC(rc);
4637 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
4638 }
4639 }
4640}
4641
4642
4643/**
4644 * Runs the guest code using AMD-V.
4645 *
4646 * @returns VBox status code.
4647 * @param pVM The cross context VM structure.
4648 * @param pVCpu The cross context virtual CPU structure.
4649 * @param pCtx Pointer to the guest-CPU context.
4650 * @param pcLoops Pointer to the number of executed loops.
4651 */
4652static int hmR0SvmRunGuestCodeNormal(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t *pcLoops)
4653{
4654 uint32_t const cMaxResumeLoops = pVM->hm.s.cMaxResumeLoops;
4655 Assert(pcLoops);
4656 Assert(*pcLoops <= cMaxResumeLoops);
4657
4658 SVMTRANSIENT SvmTransient;
4659 RT_ZERO(SvmTransient);
4660 SvmTransient.fUpdateTscOffsetting = true;
4661 SvmTransient.pVmcb = pVCpu->hm.s.svm.pVmcb;
4662
4663 int rc = VERR_INTERNAL_ERROR_5;
4664 for (;;)
4665 {
4666 Assert(!HMR0SuspendPending());
4667 HMSVM_ASSERT_CPU_SAFE();
4668
4669 /* Preparatory work for running guest code, this may force us to return
4670 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
4671 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
4672 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
4673 if (rc != VINF_SUCCESS)
4674 break;
4675
4676 /*
4677 * No longjmps to ring-3 from this point on!!!
4678 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
4679 * This also disables flushing of the R0-logger instance (if any).
4680 */
4681 hmR0SvmPreRunGuestCommitted(pVCpu, pCtx, &SvmTransient);
4682 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
4683
4684 /* Restore any residual host-state and save any bits shared between host
4685 and guest into the guest-CPU state. Re-enables interrupts! */
4686 hmR0SvmPostRunGuest(pVCpu, pCtx, &SvmTransient, rc);
4687
4688 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
4689 || SvmTransient.u64ExitCode == SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
4690 {
4691 if (rc == VINF_SUCCESS)
4692 rc = VERR_SVM_INVALID_GUEST_STATE;
4693 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
4694 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
4695 break;
4696 }
4697
4698 /* Handle the #VMEXIT. */
4699 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
4700 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
4701 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, pVCpu->hm.s.svm.pVmcb);
4702 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
4703 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
4704 if (rc != VINF_SUCCESS)
4705 break;
4706 if (++(*pcLoops) >= cMaxResumeLoops)
4707 {
4708 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
4709 rc = VINF_EM_RAW_INTERRUPT;
4710 break;
4711 }
4712 }
4713
4714 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
4715 return rc;
4716}
4717
4718
4719/**
4720 * Runs the guest code using AMD-V in single step mode.
4721 *
4722 * @returns VBox status code.
4723 * @param pVM The cross context VM structure.
4724 * @param pVCpu The cross context virtual CPU structure.
4725 * @param pCtx Pointer to the guest-CPU context.
4726 * @param pcLoops Pointer to the number of executed loops.
4727 */
4728static int hmR0SvmRunGuestCodeStep(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t *pcLoops)
4729{
4730 uint32_t const cMaxResumeLoops = pVM->hm.s.cMaxResumeLoops;
4731 Assert(pcLoops);
4732 Assert(*pcLoops <= cMaxResumeLoops);
4733
4734 SVMTRANSIENT SvmTransient;
4735 RT_ZERO(SvmTransient);
4736 SvmTransient.fUpdateTscOffsetting = true;
4737 SvmTransient.pVmcb = pVCpu->hm.s.svm.pVmcb;
4738
4739 uint16_t uCsStart = pCtx->cs.Sel;
4740 uint64_t uRipStart = pCtx->rip;
4741
4742 int rc = VERR_INTERNAL_ERROR_5;
4743 for (;;)
4744 {
4745 Assert(!HMR0SuspendPending());
4746 AssertMsg(pVCpu->hm.s.idEnteredCpu == RTMpCpuId(),
4747 ("Illegal migration! Entered on CPU %u Current %u cLoops=%u\n", (unsigned)pVCpu->hm.s.idEnteredCpu,
4748 (unsigned)RTMpCpuId(), *pcLoops));
4749
4750 /* Preparatory work for running guest code, this may force us to return
4751 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
4752 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
4753 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
4754 if (rc != VINF_SUCCESS)
4755 break;
4756
4757 /*
4758 * No longjmps to ring-3 from this point on!!!
4759 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
4760 * This also disables flushing of the R0-logger instance (if any).
4761 */
4762 VMMRZCallRing3Disable(pVCpu);
4763 VMMRZCallRing3RemoveNotification(pVCpu);
4764 hmR0SvmPreRunGuestCommitted(pVCpu, pCtx, &SvmTransient);
4765
4766 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
4767
4768 /*
4769 * Restore any residual host-state and save any bits shared between host and guest into the guest-CPU state.
4770 * This will also re-enable longjmps to ring-3 when it has reached a safe point!!!
4771 */
4772 hmR0SvmPostRunGuest(pVCpu, pCtx, &SvmTransient, rc);
4773 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
4774 || SvmTransient.u64ExitCode == SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
4775 {
4776 if (rc == VINF_SUCCESS)
4777 rc = VERR_SVM_INVALID_GUEST_STATE;
4778 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
4779 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
4780 return rc;
4781 }
4782
4783 /* Handle the #VMEXIT. */
4784 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
4785 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
4786 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, pVCpu->hm.s.svm.pVmcb);
4787 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
4788 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
4789 if (rc != VINF_SUCCESS)
4790 break;
4791 if (++(*pcLoops) >= cMaxResumeLoops)
4792 {
4793 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
4794 rc = VINF_EM_RAW_INTERRUPT;
4795 break;
4796 }
4797
4798 /*
4799 * Did the RIP change, if so, consider it a single step.
4800 * Otherwise, make sure one of the TFs gets set.
4801 */
4802 if ( pCtx->rip != uRipStart
4803 || pCtx->cs.Sel != uCsStart)
4804 {
4805 rc = VINF_EM_DBG_STEPPED;
4806 break;
4807 }
4808 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
4809 }
4810
4811 /*
4812 * Clear the X86_EFL_TF if necessary.
4813 */
4814 if (pVCpu->hm.s.fClearTrapFlag)
4815 {
4816 pVCpu->hm.s.fClearTrapFlag = false;
4817 pCtx->eflags.Bits.u1TF = 0;
4818 }
4819
4820 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
4821 return rc;
4822}
4823
4824#ifdef VBOX_WITH_NESTED_HWVIRT
4825/**
4826 * Runs the nested-guest code using AMD-V.
4827 *
4828 * @returns VBox status code.
4829 * @param pVM The cross context VM structure.
4830 * @param pVCpu The cross context virtual CPU structure.
4831 * @param pCtx Pointer to the guest-CPU context.
4832 * @param pcLoops Pointer to the number of executed loops. If we're switching
4833 * from the guest-code execution loop to this nested-guest
4834 * execution loop pass the remainder value, else pass 0.
4835 */
4836static int hmR0SvmRunGuestCodeNested(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t *pcLoops)
4837{
4838 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
4839 Assert(pcLoops);
4840 Assert(*pcLoops <= pVM->hm.s.cMaxResumeLoops);
4841
4842 SVMTRANSIENT SvmTransient;
4843 RT_ZERO(SvmTransient);
4844 SvmTransient.fUpdateTscOffsetting = true;
4845 SvmTransient.pVmcb = pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
4846 SvmTransient.fIsNestedGuest = true;
4847
4848 int rc = VERR_INTERNAL_ERROR_4;
4849 for (;;)
4850 {
4851 Assert(!HMR0SuspendPending());
4852 HMSVM_ASSERT_CPU_SAFE();
4853
4854 /* Preparatory work for running nested-guest code, this may force us to return
4855 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
4856 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
4857 rc = hmR0SvmPreRunGuestNested(pVM, pVCpu, pCtx, &SvmTransient);
4858 if ( rc != VINF_SUCCESS
4859 || !CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
4860 {
4861 break;
4862 }
4863
4864 /*
4865 * No longjmps to ring-3 from this point on!!!
4866 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
4867 * This also disables flushing of the R0-logger instance (if any).
4868 */
4869 hmR0SvmPreRunGuestCommitted(pVCpu, pCtx, &SvmTransient);
4870
4871 rc = hmR0SvmRunGuestNested(pVM, pVCpu, pCtx);
4872
4873 /* Restore any residual host-state and save any bits shared between host
4874 and guest into the guest-CPU state. Re-enables interrupts! */
4875 hmR0SvmPostRunGuest(pVCpu, pCtx, &SvmTransient, rc);
4876
4877 if (RT_LIKELY( rc == VINF_SUCCESS
4878 && SvmTransient.u64ExitCode != SVM_EXIT_INVALID))
4879 { /* extremely likely */ }
4880 else
4881 {
4882 /* VMRUN failed, shouldn't really happen, Guru. */
4883 if (rc != VINF_SUCCESS)
4884 break;
4885
4886 /* Invalid nested-guest state. Cause a #VMEXIT but assert on strict builds. */
4887 AssertMsgFailed(("Invalid nested-guest state. rc=%Rrc u64ExitCode=%#RX64\n", rc, SvmTransient.u64ExitCode));
4888 rc = VBOXSTRICTRC_TODO(IEMExecSvmVmexit(pVCpu, SVM_EXIT_INVALID, 0, 0));
4889 break;
4890 }
4891
4892 /* Handle the #VMEXIT. */
4893 HMSVM_NESTED_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
4894 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
4895 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, pCtx->hwvirt.svm.CTX_SUFF(pVmcb));
4896 rc = hmR0SvmHandleExitNested(pVCpu, pCtx, &SvmTransient);
4897 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
4898 if (rc != VINF_SUCCESS)
4899 break;
4900 if (++(*pcLoops) >= pVM->hm.s.cMaxResumeLoops)
4901 {
4902 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
4903 rc = VINF_EM_RAW_INTERRUPT;
4904 break;
4905 }
4906
4907 /** @todo handle single-stepping */
4908 }
4909
4910 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
4911 return rc;
4912}
4913#endif
4914
4915
4916/**
4917 * Runs the guest code using AMD-V.
4918 *
4919 * @returns Strict VBox status code.
4920 * @param pVM The cross context VM structure.
4921 * @param pVCpu The cross context virtual CPU structure.
4922 * @param pCtx Pointer to the guest-CPU context.
4923 */
4924VMMR0DECL(VBOXSTRICTRC) SVMR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4925{
4926 Assert(VMMRZCallRing3IsEnabled(pVCpu));
4927 HMSVM_ASSERT_PREEMPT_SAFE();
4928 VMMRZCallRing3SetNotification(pVCpu, hmR0SvmCallRing3Callback, pCtx);
4929
4930 uint32_t cLoops = 0;
4931 int rc;
4932#ifdef VBOX_WITH_NESTED_HWVIRT
4933 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
4934#endif
4935 {
4936 if (!pVCpu->hm.s.fSingleInstruction)
4937 rc = hmR0SvmRunGuestCodeNormal(pVM, pVCpu, pCtx, &cLoops);
4938 else
4939 rc = hmR0SvmRunGuestCodeStep(pVM, pVCpu, pCtx, &cLoops);
4940 }
4941#ifdef VBOX_WITH_NESTED_HWVIRT
4942 else
4943 {
4944 rc = VINF_SVM_VMRUN;
4945 }
4946
4947 /* Re-check the nested-guest condition here as we may be transitioning from the normal
4948 execution loop into the nested-guest, hence this is not placed in the 'else' part above. */
4949 if (rc == VINF_SVM_VMRUN)
4950 {
4951 rc = hmR0SvmRunGuestCodeNested(pVM, pVCpu, pCtx, &cLoops);
4952 if (rc == VINF_SVM_VMEXIT)
4953 rc = VINF_SUCCESS;
4954 }
4955#endif
4956
4957 /* Fixup error codes. */
4958 if (rc == VERR_EM_INTERPRETER)
4959 rc = VINF_EM_RAW_EMULATE_INSTR;
4960 else if (rc == VINF_EM_RESET)
4961 rc = VINF_EM_TRIPLE_FAULT;
4962
4963 /* Prepare to return to ring-3. This will remove longjmp notifications. */
4964 rc = hmR0SvmExitToRing3(pVM, pVCpu, pCtx, rc);
4965 Assert(!VMMRZCallRing3IsNotificationSet(pVCpu));
4966 return rc;
4967}
4968
4969
4970#ifdef VBOX_WITH_NESTED_HWVIRT
4971/**
4972 * Determines whether an IOIO intercept is active for the nested-guest or not.
4973 *
4974 * @param pvIoBitmap Pointer to the nested-guest IO bitmap.
4975 * @param pIoExitInfo Pointer to the SVMIOIOEXITINFO.
4976 */
4977static bool hmR0SvmIsIoInterceptActive(void *pvIoBitmap, PSVMIOIOEXITINFO pIoExitInfo)
4978{
4979 const uint16_t u16Port = pIoExitInfo->n.u16Port;
4980 const SVMIOIOTYPE enmIoType = (SVMIOIOTYPE)pIoExitInfo->n.u1Type;
4981 const uint8_t cbReg = (pIoExitInfo->u >> SVM_IOIO_OP_SIZE_SHIFT) & 7;
4982 const uint8_t cAddrSizeBits = ((pIoExitInfo->u >> SVM_IOIO_ADDR_SIZE_SHIFT) & 7) << 4;
4983 const uint8_t iEffSeg = pIoExitInfo->n.u3Seg;
4984 const bool fRep = pIoExitInfo->n.u1Rep;
4985 const bool fStrIo = pIoExitInfo->n.u1Str;
4986
4987 return HMSvmIsIOInterceptActive(pvIoBitmap, u16Port, enmIoType, cbReg, cAddrSizeBits, iEffSeg, fRep, fStrIo,
4988 NULL /* pIoExitInfo */);
4989}
4990
4991
4992/**
4993 * Handles a nested-guest \#VMEXIT (for all EXITCODE values except
4994 * SVM_EXIT_INVALID).
4995 *
4996 * @returns VBox status code (informational status codes included).
4997 * @param pVCpu The cross context virtual CPU structure.
4998 * @param pCtx Pointer to the guest-CPU context.
4999 * @param pSvmTransient Pointer to the SVM transient structure.
5000 */
5001static int hmR0SvmHandleExitNested(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5002{
5003 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
5004 Assert(pSvmTransient->u64ExitCode != SVM_EXIT_INVALID);
5005 Assert(pSvmTransient->u64ExitCode <= SVM_EXIT_MAX);
5006
5007#define HM_SVM_VMEXIT_NESTED(a_pVCpu, a_uExitCode, a_uExitInfo1, a_uExitInfo2) \
5008 VBOXSTRICTRC_TODO(IEMExecSvmVmexit(a_pVCpu, a_uExitCode, a_uExitInfo1, a_uExitInfo2))
5009
5010 /*
5011 * For all the #VMEXITs here we primarily figure out if the #VMEXIT is expected
5012 * by the nested-guest. If it isn't, it should be handled by the (outer) guest.
5013 */
5014 PSVMVMCB pVmcbNstGst = pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
5015 PSVMVMCBCTRL pVmcbNstGstCtrl = &pVmcbNstGst->ctrl;
5016 uint64_t const uExitCode = pVmcbNstGstCtrl->u64ExitCode;
5017 uint64_t const uExitInfo1 = pVmcbNstGstCtrl->u64ExitInfo1;
5018 uint64_t const uExitInfo2 = pVmcbNstGstCtrl->u64ExitInfo2;
5019
5020 Assert(uExitCode == pVmcbNstGstCtrl->u64ExitCode);
5021 switch (uExitCode)
5022 {
5023 case SVM_EXIT_CPUID:
5024 {
5025 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_CPUID))
5026 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5027 return hmR0SvmExitCpuid(pVCpu, pCtx, pSvmTransient);
5028 }
5029
5030 case SVM_EXIT_RDTSC:
5031 {
5032 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_RDTSC))
5033 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5034 return hmR0SvmExitRdtsc(pVCpu, pCtx, pSvmTransient);
5035 }
5036
5037 case SVM_EXIT_RDTSCP:
5038 {
5039 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_RDTSCP))
5040 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5041 return hmR0SvmExitRdtscp(pVCpu, pCtx, pSvmTransient);
5042 }
5043
5044 case SVM_EXIT_MONITOR:
5045 {
5046 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_MONITOR))
5047 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5048 return hmR0SvmExitMonitor(pVCpu, pCtx, pSvmTransient);
5049 }
5050
5051 case SVM_EXIT_MWAIT:
5052 {
5053 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_MWAIT))
5054 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5055 return hmR0SvmExitMwait(pVCpu, pCtx, pSvmTransient);
5056 }
5057
5058 case SVM_EXIT_HLT:
5059 {
5060 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_HLT))
5061 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5062 return hmR0SvmExitHlt(pVCpu, pCtx, pSvmTransient);
5063 }
5064
5065 case SVM_EXIT_MSR:
5066 {
5067 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_MSR_PROT))
5068 {
5069 uint32_t const idMsr = pCtx->ecx;
5070 uint16_t offMsrpm;
5071 uint8_t uMsrpmBit;
5072 int rc = HMSvmGetMsrpmOffsetAndBit(idMsr, &offMsrpm, &uMsrpmBit);
5073 if (RT_SUCCESS(rc))
5074 {
5075 Assert(uMsrpmBit == 0 || uMsrpmBit == 2 || uMsrpmBit == 4 || uMsrpmBit == 6);
5076 Assert(offMsrpm < SVM_MSRPM_PAGES << X86_PAGE_4K_SHIFT);
5077
5078 uint8_t const *pbMsrBitmap = (uint8_t const *)pCtx->hwvirt.svm.CTX_SUFF(pvMsrBitmap);
5079 pbMsrBitmap += offMsrpm;
5080 bool const fInterceptRead = RT_BOOL(*pbMsrBitmap & RT_BIT(uMsrpmBit));
5081 bool const fInterceptWrite = RT_BOOL(*pbMsrBitmap & RT_BIT(uMsrpmBit + 1));
5082
5083 if ( (fInterceptWrite && pVmcbNstGstCtrl->u64ExitInfo1 == SVM_EXIT1_MSR_WRITE)
5084 || (fInterceptRead && pVmcbNstGstCtrl->u64ExitInfo1 == SVM_EXIT1_MSR_READ))
5085 {
5086 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5087 }
5088 }
5089 else
5090 {
5091 /*
5092 * MSRs not covered by the MSRPM automatically cause an #VMEXIT.
5093 * See AMD-V spec. "15.11 MSR Intercepts".
5094 */
5095 Assert(rc == VERR_OUT_OF_RANGE);
5096 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5097 }
5098 }
5099 return hmR0SvmExitMsr(pVCpu, pCtx, pSvmTransient);
5100 }
5101
5102 case SVM_EXIT_IOIO:
5103 {
5104 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_IOIO_PROT))
5105 {
5106 void *pvIoBitmap = pCtx->hwvirt.svm.CTX_SUFF(pvIoBitmap);
5107 SVMIOIOEXITINFO IoExitInfo;
5108 IoExitInfo.u = pVmcbNstGst->ctrl.u64ExitInfo1;
5109 bool const fIntercept = hmR0SvmIsIoInterceptActive(pvIoBitmap, &IoExitInfo);
5110 if (fIntercept)
5111 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5112 }
5113 return hmR0SvmExitIOInstr(pVCpu, pCtx, pSvmTransient);
5114 }
5115
5116 case SVM_EXIT_XCPT_PF:
5117 {
5118 PVM pVM = pVCpu->CTX_SUFF(pVM);
5119 if (pVM->hm.s.fNestedPaging)
5120 {
5121 uint32_t const u32ErrCode = pVmcbNstGstCtrl->u64ExitInfo1;
5122 uint64_t const uFaultAddress = pVmcbNstGstCtrl->u64ExitInfo2;
5123
5124 /* If the nested-guest is intercepting #PFs, cause a #PF #VMEXIT. */
5125 if (HMIsGuestSvmXcptInterceptSet(pVCpu, pCtx, X86_XCPT_PF))
5126 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, u32ErrCode, uFaultAddress);
5127
5128 /* If the nested-guest is not intercepting #PFs, forward the #PF to the nested-guest. */
5129 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
5130 return VINF_SUCCESS;
5131 }
5132 return hmR0SvmExitXcptPFNested(pVCpu, pCtx,pSvmTransient);
5133 }
5134
5135 case SVM_EXIT_XCPT_UD:
5136 {
5137 if (HMIsGuestSvmXcptInterceptSet(pVCpu, pCtx, X86_XCPT_UD))
5138 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5139 hmR0SvmSetPendingXcptUD(pVCpu);
5140 return VINF_SUCCESS;
5141 }
5142
5143 case SVM_EXIT_XCPT_MF:
5144 {
5145 if (HMIsGuestSvmXcptInterceptSet(pVCpu, pCtx, X86_XCPT_MF))
5146 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5147 return hmR0SvmExitXcptMF(pVCpu, pCtx, pSvmTransient);
5148 }
5149
5150 case SVM_EXIT_XCPT_DB:
5151 {
5152 if (HMIsGuestSvmXcptInterceptSet(pVCpu, pCtx, X86_XCPT_DB))
5153 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5154 return hmR0SvmNestedExitXcptDB(pVCpu, pCtx, pSvmTransient);
5155 }
5156
5157 case SVM_EXIT_XCPT_AC:
5158 {
5159 if (HMIsGuestSvmXcptInterceptSet(pVCpu, pCtx, X86_XCPT_AC))
5160 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5161 return hmR0SvmExitXcptAC(pVCpu, pCtx, pSvmTransient);
5162 }
5163
5164 case SVM_EXIT_XCPT_BP:
5165 {
5166 if (HMIsGuestSvmXcptInterceptSet(pVCpu, pCtx, X86_XCPT_BP))
5167 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5168 return hmR0SvmNestedExitXcptBP(pVCpu, pCtx, pSvmTransient);
5169 }
5170
5171 case SVM_EXIT_READ_CR0:
5172 case SVM_EXIT_READ_CR3:
5173 case SVM_EXIT_READ_CR4:
5174 {
5175 uint8_t const uCr = uExitCode - SVM_EXIT_READ_CR0;
5176 if (HMIsGuestSvmReadCRxInterceptSet(pVCpu, pCtx, uCr))
5177 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5178 return hmR0SvmExitReadCRx(pVCpu, pCtx, pSvmTransient);
5179 }
5180
5181 case SVM_EXIT_CR0_SEL_WRITE:
5182 {
5183 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_CR0_SEL_WRITE))
5184 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5185 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
5186 }
5187
5188 case SVM_EXIT_WRITE_CR0:
5189 case SVM_EXIT_WRITE_CR3:
5190 case SVM_EXIT_WRITE_CR4:
5191 case SVM_EXIT_WRITE_CR8: /** @todo Shouldn't writes to CR8 go to V_TPR instead since we run with V_INTR_MASKING set? */
5192 {
5193 uint8_t const uCr = uExitCode - SVM_EXIT_WRITE_CR0;
5194 Log4(("hmR0SvmHandleExitNested: Write CR%u: uExitInfo1=%#RX64 uExitInfo2=%#RX64\n", uCr, uExitInfo1, uExitInfo2));
5195
5196 if (HMIsGuestSvmWriteCRxInterceptSet(pVCpu, pCtx, uCr))
5197 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5198 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
5199 }
5200
5201 case SVM_EXIT_PAUSE:
5202 {
5203 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_PAUSE))
5204 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5205 return hmR0SvmExitPause(pVCpu, pCtx, pSvmTransient);
5206 }
5207
5208 case SVM_EXIT_VINTR:
5209 {
5210 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_VINTR))
5211 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5212 return hmR0SvmExitUnexpected(pVCpu, pCtx, pSvmTransient);
5213 }
5214
5215 case SVM_EXIT_INTR:
5216 case SVM_EXIT_NMI:
5217 case SVM_EXIT_XCPT_NMI: /* Shouldn't ever happen, SVM_EXIT_NMI is used instead. */
5218 case SVM_EXIT_SMI:
5219 {
5220 /*
5221 * We shouldn't direct physical interrupts, NMIs, SMIs to the nested-guest.
5222 *
5223 * Although we don't intercept SMIs, the nested-guest might. Therefore, we
5224 * might get an SMI #VMEXIT here so simply ignore rather than causing a
5225 * corresponding nested-guest #VMEXIT.
5226 */
5227 return hmR0SvmExitIntr(pVCpu, pCtx, pSvmTransient);
5228 }
5229
5230 case SVM_EXIT_FERR_FREEZE:
5231 {
5232 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_FERR_FREEZE))
5233 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5234 return hmR0SvmExitFerrFreeze(pVCpu, pCtx, pSvmTransient);
5235 }
5236
5237 case SVM_EXIT_INVLPG:
5238 {
5239 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_INVLPG))
5240 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5241 return hmR0SvmExitInvlpg(pVCpu, pCtx, pSvmTransient);
5242 }
5243
5244 case SVM_EXIT_WBINVD:
5245 {
5246 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_WBINVD))
5247 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5248 return hmR0SvmExitWbinvd(pVCpu, pCtx, pSvmTransient);
5249 }
5250
5251 case SVM_EXIT_INVD:
5252 {
5253 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_INVD))
5254 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5255 return hmR0SvmExitInvd(pVCpu, pCtx, pSvmTransient);
5256 }
5257
5258 case SVM_EXIT_RDPMC:
5259 {
5260 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_RDPMC))
5261 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5262 return hmR0SvmExitRdpmc(pVCpu, pCtx, pSvmTransient);
5263 }
5264
5265 default:
5266 {
5267 switch (uExitCode)
5268 {
5269 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
5270 case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7: case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9:
5271 case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11: case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13:
5272 case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
5273 {
5274 uint8_t const uDr = uExitCode - SVM_EXIT_READ_DR0;
5275 if (HMIsGuestSvmReadDRxInterceptSet(pVCpu, pCtx, uDr))
5276 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5277 return hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
5278 }
5279
5280 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
5281 case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7: case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9:
5282 case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11: case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13:
5283 case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
5284 {
5285 uint8_t const uDr = uExitCode - SVM_EXIT_WRITE_DR0;
5286 if (HMIsGuestSvmWriteDRxInterceptSet(pVCpu, pCtx, uDr))
5287 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5288 return hmR0SvmExitWriteDRx(pVCpu, pCtx, pSvmTransient);
5289 }
5290
5291 case SVM_EXIT_XCPT_0: /* #DE */
5292 /* SVM_EXIT_XCPT_1: */ /* #DB - Handled above. */
5293 /* SVM_EXIT_XCPT_2: */ /* #NMI - Handled above. */
5294 /* SVM_EXIT_XCPT_3: */ /* #BP - Handled above. */
5295 case SVM_EXIT_XCPT_4: /* #OF */
5296 case SVM_EXIT_XCPT_5: /* #BR */
5297 /* SVM_EXIT_XCPT_6: */ /* #UD - Handled above. */
5298 case SVM_EXIT_XCPT_7: /* #NM */
5299 case SVM_EXIT_XCPT_8: /* #DF */
5300 case SVM_EXIT_XCPT_9: /* #CO_SEG_OVERRUN */
5301 case SVM_EXIT_XCPT_10: /* #TS */
5302 case SVM_EXIT_XCPT_11: /* #NP */
5303 case SVM_EXIT_XCPT_12: /* #SS */
5304 case SVM_EXIT_XCPT_13: /* #GP */
5305 /* SVM_EXIT_XCPT_14: */ /* #PF - Handled above. */
5306 case SVM_EXIT_XCPT_15: /* Reserved. */
5307 /* SVM_EXIT_XCPT_16: */ /* #MF - Handled above. */
5308 /* SVM_EXIT_XCPT_17: */ /* #AC - Handled above. */
5309 case SVM_EXIT_XCPT_18: /* #MC */
5310 case SVM_EXIT_XCPT_19: /* #XF */
5311 case SVM_EXIT_XCPT_20: case SVM_EXIT_XCPT_21: case SVM_EXIT_XCPT_22: case SVM_EXIT_XCPT_23:
5312 case SVM_EXIT_XCPT_24: case SVM_EXIT_XCPT_25: case SVM_EXIT_XCPT_26: case SVM_EXIT_XCPT_27:
5313 case SVM_EXIT_XCPT_28: case SVM_EXIT_XCPT_29: case SVM_EXIT_XCPT_30: case SVM_EXIT_XCPT_31:
5314 {
5315 uint8_t const uVector = uExitCode - SVM_EXIT_XCPT_0;
5316 if (HMIsGuestSvmXcptInterceptSet(pVCpu, pCtx, uVector))
5317 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5318 return hmR0SvmExitXcptGeneric(pVCpu, pCtx, pSvmTransient);
5319 }
5320
5321 case SVM_EXIT_XSETBV:
5322 {
5323 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_XSETBV))
5324 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5325 return hmR0SvmExitXsetbv(pVCpu, pCtx, pSvmTransient);
5326 }
5327
5328 case SVM_EXIT_TASK_SWITCH:
5329 {
5330 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_TASK_SWITCH))
5331 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5332 return hmR0SvmExitTaskSwitch(pVCpu, pCtx, pSvmTransient);
5333 }
5334
5335 case SVM_EXIT_IRET:
5336 {
5337 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_IRET))
5338 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5339 return hmR0SvmExitIret(pVCpu, pCtx, pSvmTransient);
5340 }
5341
5342 case SVM_EXIT_SHUTDOWN:
5343 {
5344 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_SHUTDOWN))
5345 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5346 return hmR0SvmExitShutdown(pVCpu, pCtx, pSvmTransient);
5347 }
5348
5349 case SVM_EXIT_VMMCALL:
5350 {
5351 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_VMMCALL))
5352 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5353 return hmR0SvmExitVmmCall(pVCpu, pCtx, pSvmTransient);
5354 }
5355
5356 case SVM_EXIT_CLGI:
5357 {
5358 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_CLGI))
5359 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5360 return hmR0SvmExitClgi(pVCpu, pCtx, pSvmTransient);
5361 }
5362
5363 case SVM_EXIT_STGI:
5364 {
5365 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_STGI))
5366 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5367 return hmR0SvmExitStgi(pVCpu, pCtx, pSvmTransient);
5368 }
5369
5370 case SVM_EXIT_VMLOAD:
5371 {
5372 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_VMLOAD))
5373 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5374 return hmR0SvmExitVmload(pVCpu, pCtx, pSvmTransient);
5375 }
5376
5377 case SVM_EXIT_VMSAVE:
5378 {
5379 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_VMSAVE))
5380 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5381 return hmR0SvmExitVmsave(pVCpu, pCtx, pSvmTransient);
5382 }
5383
5384 case SVM_EXIT_INVLPGA:
5385 {
5386 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_INVLPGA))
5387 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5388 return hmR0SvmExitInvlpga(pVCpu, pCtx, pSvmTransient);
5389 }
5390
5391 case SVM_EXIT_VMRUN:
5392 {
5393 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_VMRUN))
5394 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5395 return hmR0SvmExitVmrun(pVCpu, pCtx, pSvmTransient);
5396 }
5397
5398 case SVM_EXIT_RSM:
5399 {
5400 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_RSM))
5401 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5402 hmR0SvmSetPendingXcptUD(pVCpu);
5403 return VINF_SUCCESS;
5404 }
5405
5406 case SVM_EXIT_SKINIT:
5407 {
5408 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_SKINIT))
5409 return HM_SVM_VMEXIT_NESTED(pVCpu, uExitCode, uExitInfo1, uExitInfo2);
5410 hmR0SvmSetPendingXcptUD(pVCpu);
5411 return VINF_SUCCESS;
5412 }
5413
5414 /** @todo Needed when restoring saved-state when saved state support wasn't yet
5415 * added. Perhaps it won't be required later. */
5416#if 0
5417 case SVM_EXIT_NPF:
5418 {
5419 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
5420 if (HMIsGuestSvmXcptInterceptSet(pVCpu, pCtx, X86_XCPT_PF))
5421 return HM_SVM_VMEXIT_NESTED(pVCpu, SVM_EXIT_XCPT_14, RT_LO_U32(uExitInfo1), uExitInfo2);
5422 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, RT_LO_U32(uExitInfo1), uExitInfo2);
5423 return VINF_SUCCESS;
5424 }
5425#else
5426 case SVM_EXIT_NPF:
5427#endif
5428 case SVM_EXIT_INIT: /* We shouldn't get INIT signals while executing a nested-guest. */
5429 {
5430 return hmR0SvmExitUnexpected(pVCpu, pCtx, pSvmTransient);
5431 }
5432
5433 default:
5434 {
5435 AssertMsgFailed(("hmR0SvmHandleExitNested: Unknown exit code %#x\n", pSvmTransient->u64ExitCode));
5436 pVCpu->hm.s.u32HMError = pSvmTransient->u64ExitCode;
5437 return VERR_SVM_UNKNOWN_EXIT;
5438 }
5439 }
5440 }
5441 }
5442 /* not reached */
5443
5444#undef HM_SVM_VMEXIT_NESTED
5445}
5446#endif
5447
5448
5449/**
5450 * Handles a guest \#VMEXIT (for all EXITCODE values except SVM_EXIT_INVALID).
5451 *
5452 * @returns VBox status code (informational status codes included).
5453 * @param pVCpu The cross context virtual CPU structure.
5454 * @param pCtx Pointer to the guest-CPU context.
5455 * @param pSvmTransient Pointer to the SVM transient structure.
5456 */
5457static int hmR0SvmHandleExit(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5458{
5459 Assert(pSvmTransient->u64ExitCode != SVM_EXIT_INVALID);
5460 Assert(pSvmTransient->u64ExitCode <= SVM_EXIT_MAX);
5461
5462 /*
5463 * The ordering of the case labels is based on most-frequently-occurring #VMEXITs for most guests under
5464 * normal workloads (for some definition of "normal").
5465 */
5466 uint64_t const uExitCode = pSvmTransient->u64ExitCode;
5467 switch (uExitCode)
5468 {
5469 case SVM_EXIT_NPF:
5470 return hmR0SvmExitNestedPF(pVCpu, pCtx, pSvmTransient);
5471
5472 case SVM_EXIT_IOIO:
5473 return hmR0SvmExitIOInstr(pVCpu, pCtx, pSvmTransient);
5474
5475 case SVM_EXIT_RDTSC:
5476 return hmR0SvmExitRdtsc(pVCpu, pCtx, pSvmTransient);
5477
5478 case SVM_EXIT_RDTSCP:
5479 return hmR0SvmExitRdtscp(pVCpu, pCtx, pSvmTransient);
5480
5481 case SVM_EXIT_CPUID:
5482 return hmR0SvmExitCpuid(pVCpu, pCtx, pSvmTransient);
5483
5484 case SVM_EXIT_XCPT_14: /* X86_XCPT_PF */
5485 return hmR0SvmExitXcptPF(pVCpu, pCtx, pSvmTransient);
5486
5487 case SVM_EXIT_XCPT_6: /* X86_XCPT_UD */
5488 return hmR0SvmExitXcptUD(pVCpu, pCtx, pSvmTransient);
5489
5490 case SVM_EXIT_XCPT_16: /* X86_XCPT_MF */
5491 return hmR0SvmExitXcptMF(pVCpu, pCtx, pSvmTransient);
5492
5493 case SVM_EXIT_XCPT_1: /* X86_XCPT_DB */
5494 return hmR0SvmExitXcptDB(pVCpu, pCtx, pSvmTransient);
5495
5496 case SVM_EXIT_XCPT_17: /* X86_XCPT_AC */
5497 return hmR0SvmExitXcptAC(pVCpu, pCtx, pSvmTransient);
5498
5499 case SVM_EXIT_XCPT_3: /* X86_XCPT_BP */
5500 return hmR0SvmExitXcptBP(pVCpu, pCtx, pSvmTransient);
5501
5502 case SVM_EXIT_MONITOR:
5503 return hmR0SvmExitMonitor(pVCpu, pCtx, pSvmTransient);
5504
5505 case SVM_EXIT_MWAIT:
5506 return hmR0SvmExitMwait(pVCpu, pCtx, pSvmTransient);
5507
5508 case SVM_EXIT_HLT:
5509 return hmR0SvmExitHlt(pVCpu, pCtx, pSvmTransient);
5510
5511 case SVM_EXIT_READ_CR0:
5512 case SVM_EXIT_READ_CR3:
5513 case SVM_EXIT_READ_CR4:
5514 return hmR0SvmExitReadCRx(pVCpu, pCtx, pSvmTransient);
5515
5516 case SVM_EXIT_CR0_SEL_WRITE:
5517 case SVM_EXIT_WRITE_CR0:
5518 case SVM_EXIT_WRITE_CR3:
5519 case SVM_EXIT_WRITE_CR4:
5520 case SVM_EXIT_WRITE_CR8:
5521 {
5522 uint8_t const uCr = uExitCode == SVM_EXIT_CR0_SEL_WRITE ? 0 : uExitCode - SVM_EXIT_WRITE_CR0;
5523 Log4(("hmR0SvmHandleExit: Write CR%u\n", uCr)); NOREF(uCr);
5524 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
5525 }
5526
5527 case SVM_EXIT_PAUSE:
5528 return hmR0SvmExitPause(pVCpu, pCtx, pSvmTransient);
5529
5530 case SVM_EXIT_VMMCALL:
5531 return hmR0SvmExitVmmCall(pVCpu, pCtx, pSvmTransient);
5532
5533 case SVM_EXIT_VINTR:
5534 return hmR0SvmExitVIntr(pVCpu, pCtx, pSvmTransient);
5535
5536 case SVM_EXIT_FERR_FREEZE:
5537 return hmR0SvmExitFerrFreeze(pVCpu, pCtx, pSvmTransient);
5538
5539 case SVM_EXIT_INTR:
5540 case SVM_EXIT_NMI:
5541 case SVM_EXIT_XCPT_NMI: /* Shouldn't ever happen, SVM_EXIT_NMI is used instead. */
5542 return hmR0SvmExitIntr(pVCpu, pCtx, pSvmTransient);
5543
5544 case SVM_EXIT_MSR:
5545 return hmR0SvmExitMsr(pVCpu, pCtx, pSvmTransient);
5546
5547 case SVM_EXIT_INVLPG:
5548 return hmR0SvmExitInvlpg(pVCpu, pCtx, pSvmTransient);
5549
5550 case SVM_EXIT_WBINVD:
5551 return hmR0SvmExitWbinvd(pVCpu, pCtx, pSvmTransient);
5552
5553 case SVM_EXIT_INVD:
5554 return hmR0SvmExitInvd(pVCpu, pCtx, pSvmTransient);
5555
5556 case SVM_EXIT_RDPMC:
5557 return hmR0SvmExitRdpmc(pVCpu, pCtx, pSvmTransient);
5558
5559 default:
5560 {
5561 switch (pSvmTransient->u64ExitCode)
5562 {
5563 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
5564 case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7: case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9:
5565 case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11: case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13:
5566 case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
5567 return hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
5568
5569 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
5570 case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7: case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9:
5571 case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11: case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13:
5572 case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
5573 return hmR0SvmExitWriteDRx(pVCpu, pCtx, pSvmTransient);
5574
5575 case SVM_EXIT_XSETBV:
5576 return hmR0SvmExitXsetbv(pVCpu, pCtx, pSvmTransient);
5577
5578 case SVM_EXIT_TASK_SWITCH:
5579 return hmR0SvmExitTaskSwitch(pVCpu, pCtx, pSvmTransient);
5580
5581 case SVM_EXIT_IRET:
5582 return hmR0SvmExitIret(pVCpu, pCtx, pSvmTransient);
5583
5584 case SVM_EXIT_SHUTDOWN:
5585 return hmR0SvmExitShutdown(pVCpu, pCtx, pSvmTransient);
5586
5587 case SVM_EXIT_SMI:
5588 case SVM_EXIT_INIT:
5589 {
5590 /*
5591 * We don't intercept SMIs. As for INIT signals, it really shouldn't ever happen here.
5592 * If it ever does, we want to know about it so log the exit code and bail.
5593 */
5594 return hmR0SvmExitUnexpected(pVCpu, pCtx, pSvmTransient);
5595 }
5596
5597#ifdef VBOX_WITH_NESTED_HWVIRT
5598 case SVM_EXIT_CLGI: return hmR0SvmExitClgi(pVCpu, pCtx, pSvmTransient);
5599 case SVM_EXIT_STGI: return hmR0SvmExitStgi(pVCpu, pCtx, pSvmTransient);
5600 case SVM_EXIT_VMLOAD: return hmR0SvmExitVmload(pVCpu, pCtx, pSvmTransient);
5601 case SVM_EXIT_VMSAVE: return hmR0SvmExitVmsave(pVCpu, pCtx, pSvmTransient);
5602 case SVM_EXIT_INVLPGA: return hmR0SvmExitInvlpga(pVCpu, pCtx, pSvmTransient);
5603 case SVM_EXIT_VMRUN: return hmR0SvmExitVmrun(pVCpu, pCtx, pSvmTransient);
5604#else
5605 case SVM_EXIT_CLGI:
5606 case SVM_EXIT_STGI:
5607 case SVM_EXIT_VMLOAD:
5608 case SVM_EXIT_VMSAVE:
5609 case SVM_EXIT_INVLPGA:
5610 case SVM_EXIT_VMRUN:
5611#endif
5612 case SVM_EXIT_RSM:
5613 case SVM_EXIT_SKINIT:
5614 {
5615 hmR0SvmSetPendingXcptUD(pVCpu);
5616 return VINF_SUCCESS;
5617 }
5618
5619#ifdef HMSVM_ALWAYS_TRAP_ALL_XCPTS
5620 case SVM_EXIT_XCPT_0: /* #DE */
5621 /* SVM_EXIT_XCPT_1: */ /* #DB - Handled above. */
5622 /* SVM_EXIT_XCPT_2: */ /* #NMI - Handled above. */
5623 /* SVM_EXIT_XCPT_3: */ /* #BP - Handled above. */
5624 case SVM_EXIT_XCPT_4: /* #OF */
5625 case SVM_EXIT_XCPT_5: /* #BR */
5626 /* SVM_EXIT_XCPT_6: */ /* #UD - Handled above. */
5627 case SVM_EXIT_XCPT_7: /* #NM */
5628 case SVM_EXIT_XCPT_8: /* #DF */
5629 case SVM_EXIT_XCPT_9: /* #CO_SEG_OVERRUN */
5630 case SVM_EXIT_XCPT_10: /* #TS */
5631 case SVM_EXIT_XCPT_11: /* #NP */
5632 case SVM_EXIT_XCPT_12: /* #SS */
5633 case SVM_EXIT_XCPT_13: /* #GP */
5634 /* SVM_EXIT_XCPT_14: */ /* #PF - Handled above. */
5635 case SVM_EXIT_XCPT_15: /* Reserved. */
5636 /* SVM_EXIT_XCPT_16: */ /* #MF - Handled above. */
5637 /* SVM_EXIT_XCPT_17: */ /* #AC - Handled above. */
5638 case SVM_EXIT_XCPT_18: /* #MC */
5639 case SVM_EXIT_XCPT_19: /* #XF */
5640 case SVM_EXIT_XCPT_20: case SVM_EXIT_XCPT_21: case SVM_EXIT_XCPT_22: case SVM_EXIT_XCPT_23:
5641 case SVM_EXIT_XCPT_24: case SVM_EXIT_XCPT_25: case SVM_EXIT_XCPT_26: case SVM_EXIT_XCPT_27:
5642 case SVM_EXIT_XCPT_28: case SVM_EXIT_XCPT_29: case SVM_EXIT_XCPT_30: case SVM_EXIT_XCPT_31:
5643 return hmR0SvmExitXcptGeneric(pVCpu, pCtx, pSvmTransient);
5644#endif /* HMSVM_ALWAYS_TRAP_ALL_XCPTS */
5645
5646 default:
5647 {
5648 AssertMsgFailed(("hmR0SvmHandleExit: Unknown exit code %#RX64\n", uExitCode));
5649 pVCpu->hm.s.u32HMError = uExitCode;
5650 return VERR_SVM_UNKNOWN_EXIT;
5651 }
5652 }
5653 }
5654 }
5655 /* not reached */
5656}
5657
5658
5659#ifdef DEBUG
5660/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
5661# define HMSVM_ASSERT_PREEMPT_CPUID_VAR() \
5662 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
5663
5664# define HMSVM_ASSERT_PREEMPT_CPUID() \
5665 do \
5666 { \
5667 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
5668 AssertMsg(idAssertCpu == idAssertCpuNow, ("SVM %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
5669 } while (0)
5670
5671# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() \
5672 do { \
5673 AssertPtr(pVCpu); \
5674 AssertPtr(pCtx); \
5675 AssertPtr(pSvmTransient); \
5676 Assert(ASMIntAreEnabled()); \
5677 HMSVM_ASSERT_PREEMPT_SAFE(); \
5678 HMSVM_ASSERT_PREEMPT_CPUID_VAR(); \
5679 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)); \
5680 HMSVM_ASSERT_PREEMPT_SAFE(); \
5681 if (VMMR0IsLogFlushDisabled(pVCpu)) \
5682 HMSVM_ASSERT_PREEMPT_CPUID(); \
5683 } while (0)
5684#else /* Release builds */
5685# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() do { NOREF(pVCpu); NOREF(pCtx); NOREF(pSvmTransient); } while (0)
5686#endif
5687
5688
5689/**
5690 * Worker for hmR0SvmInterpretInvlpg().
5691 *
5692 * @return VBox status code.
5693 * @param pVCpu The cross context virtual CPU structure.
5694 * @param pCpu Pointer to the disassembler state.
5695 * @param pCtx The guest CPU context.
5696 */
5697static int hmR0SvmInterpretInvlPgEx(PVMCPU pVCpu, PDISCPUSTATE pCpu, PCPUMCTX pCtx)
5698{
5699 DISQPVPARAMVAL Param1;
5700 RTGCPTR GCPtrPage;
5701
5702 int rc = DISQueryParamVal(CPUMCTX2CORE(pCtx), pCpu, &pCpu->Param1, &Param1, DISQPVWHICH_SRC);
5703 if (RT_FAILURE(rc))
5704 return VERR_EM_INTERPRETER;
5705
5706 if ( Param1.type == DISQPV_TYPE_IMMEDIATE
5707 || Param1.type == DISQPV_TYPE_ADDRESS)
5708 {
5709 if (!(Param1.flags & (DISQPV_FLAG_32 | DISQPV_FLAG_64)))
5710 return VERR_EM_INTERPRETER;
5711
5712 GCPtrPage = Param1.val.val64;
5713 VBOXSTRICTRC rc2 = EMInterpretInvlpg(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx), GCPtrPage);
5714 rc = VBOXSTRICTRC_VAL(rc2);
5715 }
5716 else
5717 {
5718 Log4(("hmR0SvmInterpretInvlPgEx invalid parameter type %#x\n", Param1.type));
5719 rc = VERR_EM_INTERPRETER;
5720 }
5721
5722 return rc;
5723}
5724
5725
5726/**
5727 * Interprets INVLPG.
5728 *
5729 * @returns VBox status code.
5730 * @retval VINF_* Scheduling instructions.
5731 * @retval VERR_EM_INTERPRETER Something we can't cope with.
5732 * @retval VERR_* Fatal errors.
5733 *
5734 * @param pVM The cross context VM structure.
5735 * @param pVCpu The cross context virtual CPU structure.
5736 * @param pCtx The guest CPU context.
5737 *
5738 * @remarks Updates the RIP if the instruction was executed successfully.
5739 */
5740static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
5741{
5742 /* Only allow 32 & 64 bit code. */
5743 if (CPUMGetGuestCodeBits(pVCpu) != 16)
5744 {
5745 PDISSTATE pDis = &pVCpu->hm.s.DisState;
5746 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL /* pcbInstr */);
5747 if ( RT_SUCCESS(rc)
5748 && pDis->pCurInstr->uOpcode == OP_INVLPG)
5749 {
5750 rc = hmR0SvmInterpretInvlPgEx(pVCpu, pDis, pCtx);
5751 if (RT_SUCCESS(rc))
5752 pCtx->rip += pDis->cbInstr;
5753 return rc;
5754 }
5755 else
5756 Log4(("hmR0SvmInterpretInvlpg: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
5757 }
5758 return VERR_EM_INTERPRETER;
5759}
5760
5761
5762#ifdef HMSVM_USE_IEM_EVENT_REFLECTION
5763/**
5764 * Gets the IEM exception flags for the specified SVM event.
5765 *
5766 * @returns The IEM exception flags.
5767 * @param pEvent Pointer to the SVM event.
5768 *
5769 * @remarks This function currently only constructs flags required for
5770 * IEMEvaluateRecursiveXcpt and not the complete flags (e.g. error-code
5771 * and CR2 aspects of an exception are not included).
5772 */
5773static uint32_t hmR0SvmGetIemXcptFlags(PCSVMEVENT pEvent)
5774{
5775 uint8_t const uEventType = pEvent->n.u3Type;
5776 uint32_t fIemXcptFlags;
5777 switch (uEventType)
5778 {
5779 case SVM_EVENT_EXCEPTION:
5780 /*
5781 * Only INT3 and INTO instructions can raise #BP and #OF exceptions.
5782 * See AMD spec. Table 8-1. "Interrupt Vector Source and Cause".
5783 */
5784 if (pEvent->n.u8Vector == X86_XCPT_BP)
5785 {
5786 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT | IEM_XCPT_FLAGS_BP_INSTR;
5787 break;
5788 }
5789 if (pEvent->n.u8Vector == X86_XCPT_OF)
5790 {
5791 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT | IEM_XCPT_FLAGS_OF_INSTR;
5792 break;
5793 }
5794 /** @todo How do we distinguish ICEBP \#DB from the regular one? */
5795 RT_FALL_THRU();
5796 case SVM_EVENT_NMI:
5797 fIemXcptFlags = IEM_XCPT_FLAGS_T_CPU_XCPT;
5798 break;
5799
5800 case SVM_EVENT_EXTERNAL_IRQ:
5801 fIemXcptFlags = IEM_XCPT_FLAGS_T_EXT_INT;
5802 break;
5803
5804 case SVM_EVENT_SOFTWARE_INT:
5805 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT;
5806 break;
5807
5808 default:
5809 fIemXcptFlags = 0;
5810 AssertMsgFailed(("Unexpected event type! uEventType=%#x uVector=%#x", uEventType, pEvent->n.u8Vector));
5811 break;
5812 }
5813 return fIemXcptFlags;
5814}
5815
5816#else
5817/**
5818 * Determines if an exception is a contributory exception.
5819 *
5820 * Contributory exceptions are ones which can cause double-faults unless the
5821 * original exception was a benign exception. Page-fault is intentionally not
5822 * included here as it's a conditional contributory exception.
5823 *
5824 * @returns @c true if the exception is contributory, @c false otherwise.
5825 * @param uVector The exception vector.
5826 */
5827DECLINLINE(bool) hmR0SvmIsContributoryXcpt(const uint32_t uVector)
5828{
5829 switch (uVector)
5830 {
5831 case X86_XCPT_GP:
5832 case X86_XCPT_SS:
5833 case X86_XCPT_NP:
5834 case X86_XCPT_TS:
5835 case X86_XCPT_DE:
5836 return true;
5837 default:
5838 break;
5839 }
5840 return false;
5841}
5842#endif /* HMSVM_USE_IEM_EVENT_REFLECTION */
5843
5844
5845/**
5846 * Handle a condition that occurred while delivering an event through the guest
5847 * IDT.
5848 *
5849 * @returns VBox status code (informational error codes included).
5850 * @retval VINF_SUCCESS if we should continue handling the \#VMEXIT.
5851 * @retval VINF_HM_DOUBLE_FAULT if a \#DF condition was detected and we ought to
5852 * continue execution of the guest which will delivery the \#DF.
5853 * @retval VINF_EM_RESET if we detected a triple-fault condition.
5854 * @retval VERR_EM_GUEST_CPU_HANG if we detected a guest CPU hang.
5855 *
5856 * @param pVCpu The cross context virtual CPU structure.
5857 * @param pCtx Pointer to the guest-CPU context.
5858 * @param pSvmTransient Pointer to the SVM transient structure.
5859 *
5860 * @remarks No-long-jump zone!!!
5861 */
5862static int hmR0SvmCheckExitDueToEventDelivery(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5863{
5864 int rc = VINF_SUCCESS;
5865 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
5866
5867 Log4(("EXITINTINFO: Pending vectoring event %#RX64 Valid=%RTbool ErrValid=%RTbool Err=%#RX32 Type=%u Vector=%u\n",
5868 pVmcb->ctrl.ExitIntInfo.u, !!pVmcb->ctrl.ExitIntInfo.n.u1Valid, !!pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid,
5869 pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode, pVmcb->ctrl.ExitIntInfo.n.u3Type, pVmcb->ctrl.ExitIntInfo.n.u8Vector));
5870
5871 /* See AMD spec. 15.7.3 "EXITINFO Pseudo-Code". The EXITINTINFO (if valid) contains the prior exception (IDT vector)
5872 * that was trying to be delivered to the guest which caused a #VMEXIT which was intercepted (Exit vector). */
5873 if (pVmcb->ctrl.ExitIntInfo.n.u1Valid)
5874 {
5875#ifdef HMSVM_USE_IEM_EVENT_REFLECTION
5876 IEMXCPTRAISE enmRaise;
5877 IEMXCPTRAISEINFO fRaiseInfo;
5878 bool const fExitIsHwXcpt = pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0 <= SVM_EXIT_XCPT_31;
5879 uint8_t const uIdtVector = pVmcb->ctrl.ExitIntInfo.n.u8Vector;
5880 if (fExitIsHwXcpt)
5881 {
5882 uint8_t const uExitVector = pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0;
5883 uint32_t const fIdtVectorFlags = hmR0SvmGetIemXcptFlags(&pVmcb->ctrl.ExitIntInfo);
5884 uint32_t const fExitVectorFlags = IEM_XCPT_FLAGS_T_CPU_XCPT;
5885 enmRaise = IEMEvaluateRecursiveXcpt(pVCpu, fIdtVectorFlags, uIdtVector, fExitVectorFlags, uExitVector, &fRaiseInfo);
5886 }
5887 else
5888 {
5889 /*
5890 * If delivery of an event caused a #VMEXIT that is not an exception (e.g. #NPF) then we
5891 * end up here.
5892 *
5893 * If the event was:
5894 * - a software interrupt, we can re-execute the instruction which will regenerate
5895 * the event.
5896 * - an NMI, we need to clear NMI blocking and re-inject the NMI.
5897 * - a hardware exception or external interrupt, we re-inject it.
5898 */
5899 fRaiseInfo = IEMXCPTRAISEINFO_NONE;
5900 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_SOFTWARE_INT)
5901 enmRaise = IEMXCPTRAISE_REEXEC_INSTR;
5902 else
5903 enmRaise = IEMXCPTRAISE_PREV_EVENT;
5904 }
5905
5906 switch (enmRaise)
5907 {
5908 case IEMXCPTRAISE_CURRENT_XCPT:
5909 case IEMXCPTRAISE_PREV_EVENT:
5910 {
5911 /* For software interrupts, we shall re-execute the instruction. */
5912 if (!(fRaiseInfo & IEMXCPTRAISEINFO_SOFT_INT_XCPT))
5913 {
5914 RTGCUINTPTR GCPtrFaultAddress = 0;
5915
5916 /* If we are re-injecting an NMI, clear NMI blocking. */
5917 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_NMI)
5918 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
5919
5920 /* Determine a vectoring #PF condition, see comment in hmR0SvmExitXcptPF(). */
5921 if (fRaiseInfo & (IEMXCPTRAISEINFO_EXT_INT_PF | IEMXCPTRAISEINFO_NMI_PF))
5922 pSvmTransient->fVectoringPF = true;
5923 else if ( pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXCEPTION
5924 && uIdtVector == X86_XCPT_PF)
5925 {
5926 /*
5927 * If the previous exception was a #PF, we need to recover the CR2 value.
5928 * This can't happen with shadow paging.
5929 */
5930 GCPtrFaultAddress = pCtx->cr2;
5931 }
5932
5933 /*
5934 * Without nested paging, when uExitVector is #PF, CR2 value will be updated from the VMCB's
5935 * exit info. fields, if it's a guest #PF, see hmR0SvmExitXcptPF().
5936 */
5937 Assert(pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT);
5938 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
5939 hmR0SvmSetPendingEvent(pVCpu, &pVmcb->ctrl.ExitIntInfo, GCPtrFaultAddress);
5940
5941 Log4(("IDT: Pending vectoring event %#RX64 ErrValid=%RTbool Err=%#RX32 GCPtrFaultAddress=%#RX64\n",
5942 pVmcb->ctrl.ExitIntInfo.u, RT_BOOL(pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid),
5943 pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode, GCPtrFaultAddress));
5944 }
5945 break;
5946 }
5947
5948 case IEMXCPTRAISE_REEXEC_INSTR:
5949 {
5950 Assert(rc == VINF_SUCCESS);
5951 break;
5952 }
5953
5954 case IEMXCPTRAISE_DOUBLE_FAULT:
5955 {
5956 /*
5957 * Determing a vectoring double #PF condition. Used later, when PGM evaluates the
5958 * second #PF as a guest #PF (and not a shadow #PF) and needs to be converted into a #DF.
5959 */
5960 if (fRaiseInfo & IEMXCPTRAISEINFO_PF_PF)
5961 {
5962 pSvmTransient->fVectoringDoublePF = true;
5963 Assert(rc == VINF_SUCCESS);
5964 }
5965 else
5966 {
5967 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
5968 hmR0SvmSetPendingXcptDF(pVCpu);
5969 rc = VINF_HM_DOUBLE_FAULT;
5970 }
5971 break;
5972 }
5973
5974 case IEMXCPTRAISE_TRIPLE_FAULT:
5975 {
5976 rc = VINF_EM_RESET;
5977 break;
5978 }
5979
5980 case IEMXCPTRAISE_CPU_HANG:
5981 {
5982 rc = VERR_EM_GUEST_CPU_HANG;
5983 break;
5984 }
5985
5986 default:
5987 {
5988 AssertMsgFailed(("hmR0SvmExitCpuid: EMInterpretCpuId failed with %Rrc\n", rc));
5989 rc = VERR_SVM_IPE_2;
5990 break;
5991 }
5992 }
5993#else
5994 uint8_t uIdtVector = pVmcb->ctrl.ExitIntInfo.n.u8Vector;
5995
5996 typedef enum
5997 {
5998 SVMREFLECTXCPT_XCPT, /* Reflect the exception to the guest or for further evaluation by VMM. */
5999 SVMREFLECTXCPT_DF, /* Reflect the exception as a double-fault to the guest. */
6000 SVMREFLECTXCPT_TF, /* Indicate a triple faulted state to the VMM. */
6001 SVMREFLECTXCPT_HANG, /* Indicate bad VM trying to deadlock the CPU. */
6002 SVMREFLECTXCPT_NONE /* Nothing to reflect. */
6003 } SVMREFLECTXCPT;
6004
6005 SVMREFLECTXCPT enmReflect = SVMREFLECTXCPT_NONE;
6006 bool fReflectingNmi = false;
6007 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXCEPTION)
6008 {
6009 if (pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0 <= SVM_EXIT_XCPT_31)
6010 {
6011 uint8_t uExitVector = (uint8_t)(pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0);
6012
6013#ifdef VBOX_STRICT
6014 if ( hmR0SvmIsContributoryXcpt(uIdtVector)
6015 && uExitVector == X86_XCPT_PF)
6016 {
6017 Log4(("IDT: Contributory #PF idCpu=%u uCR2=%#RX64\n", pVCpu->idCpu, pCtx->cr2));
6018 }
6019#endif
6020
6021 if ( uIdtVector == X86_XCPT_BP
6022 || uIdtVector == X86_XCPT_OF)
6023 {
6024 /* Ignore INT3/INTO, just re-execute. See @bugref{8357}. */
6025 }
6026 else if ( uExitVector == X86_XCPT_PF
6027 && uIdtVector == X86_XCPT_PF)
6028 {
6029 pSvmTransient->fVectoringDoublePF = true;
6030 Log4(("IDT: Vectoring double #PF uCR2=%#RX64\n", pCtx->cr2));
6031 }
6032 else if ( uExitVector == X86_XCPT_AC
6033 && uIdtVector == X86_XCPT_AC)
6034 {
6035 enmReflect = SVMREFLECTXCPT_HANG;
6036 Log4(("IDT: Nested #AC - Bad guest\n"));
6037 }
6038 else if ( (pVmcb->ctrl.u32InterceptXcpt & HMSVM_CONTRIBUTORY_XCPT_MASK)
6039 && hmR0SvmIsContributoryXcpt(uExitVector)
6040 && ( hmR0SvmIsContributoryXcpt(uIdtVector)
6041 || uIdtVector == X86_XCPT_PF))
6042 {
6043 enmReflect = SVMREFLECTXCPT_DF;
6044 Log4(("IDT: Pending vectoring #DF %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->hm.s.Event.u64IntInfo,
6045 uIdtVector, uExitVector));
6046 }
6047 else if (uIdtVector == X86_XCPT_DF)
6048 {
6049 enmReflect = SVMREFLECTXCPT_TF;
6050 Log4(("IDT: Pending vectoring triple-fault %#RX64 uIdtVector=%#x uExitVector=%#x\n",
6051 pVCpu->hm.s.Event.u64IntInfo, uIdtVector, uExitVector));
6052 }
6053 else
6054 enmReflect = SVMREFLECTXCPT_XCPT;
6055 }
6056 else
6057 {
6058 /*
6059 * If event delivery caused an #VMEXIT that is not an exception (e.g. #NPF) then reflect the original
6060 * exception to the guest after handling the #VMEXIT.
6061 */
6062 enmReflect = SVMREFLECTXCPT_XCPT;
6063 }
6064 }
6065 else if ( pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXTERNAL_IRQ
6066 || pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_NMI)
6067 {
6068 enmReflect = SVMREFLECTXCPT_XCPT;
6069 fReflectingNmi = RT_BOOL(pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_NMI);
6070
6071 if (pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0 <= SVM_EXIT_XCPT_31)
6072 {
6073 uint8_t uExitVector = (uint8_t)(pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0);
6074 if (uExitVector == X86_XCPT_PF)
6075 {
6076 pSvmTransient->fVectoringPF = true;
6077 Log4(("IDT: Vectoring #PF due to Ext-Int/NMI. uCR2=%#RX64\n", pCtx->cr2));
6078 }
6079 }
6080 }
6081 /* else: Ignore software interrupts (INT n) as they reoccur when restarting the instruction. */
6082
6083 switch (enmReflect)
6084 {
6085 case SVMREFLECTXCPT_XCPT:
6086 {
6087 /* If we are re-injecting the NMI, clear NMI blocking. */
6088 if (fReflectingNmi)
6089 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
6090
6091 Assert(pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT);
6092 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
6093 hmR0SvmSetPendingEvent(pVCpu, &pVmcb->ctrl.ExitIntInfo, 0 /* GCPtrFaultAddress */);
6094
6095 /* If uExitVector is #PF, CR2 value will be updated from the VMCB if it's a guest #PF. See hmR0SvmExitXcptPF(). */
6096 Log4(("IDT: Pending vectoring event %#RX64 ErrValid=%RTbool Err=%#RX32\n", pVmcb->ctrl.ExitIntInfo.u,
6097 !!pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid, pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
6098 break;
6099 }
6100
6101 case SVMREFLECTXCPT_DF:
6102 {
6103 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
6104 hmR0SvmSetPendingXcptDF(pVCpu);
6105 rc = VINF_HM_DOUBLE_FAULT;
6106 break;
6107 }
6108
6109 case SVMREFLECTXCPT_TF:
6110 {
6111 rc = VINF_EM_RESET;
6112 break;
6113 }
6114
6115 case SVMREFLECTXCPT_HANG:
6116 {
6117 rc = VERR_EM_GUEST_CPU_HANG;
6118 break;
6119 }
6120
6121 default:
6122 Assert(rc == VINF_SUCCESS);
6123 break;
6124 }
6125#endif /* HMSVM_USE_IEM_EVENT_REFLECTION */
6126 }
6127 Assert(rc == VINF_SUCCESS || rc == VINF_HM_DOUBLE_FAULT || rc == VINF_EM_RESET || rc == VERR_EM_GUEST_CPU_HANG);
6128 NOREF(pCtx);
6129 return rc;
6130}
6131
6132
6133/**
6134 * Advances the guest RIP making use of the CPU's NRIP_SAVE feature if
6135 * supported, otherwise advances the RIP by the number of bytes specified in
6136 * @a cb.
6137 *
6138 * @param pVCpu The cross context virtual CPU structure.
6139 * @param pCtx Pointer to the guest-CPU context.
6140 * @param cb RIP increment value in bytes.
6141 *
6142 * @remarks Use this function only from \#VMEXIT's where the NRIP value is valid
6143 * when NRIP_SAVE is supported by the CPU, otherwise use
6144 * hmR0SvmAdvanceRipDumb!
6145 */
6146DECLINLINE(void) hmR0SvmAdvanceRipHwAssist(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t cb)
6147{
6148 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6149 if (fSupportsNextRipSave)
6150 {
6151 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6152 Assert(pVmcb->ctrl.u64NextRIP);
6153 AssertRelease(pVmcb->ctrl.u64NextRIP - pCtx->rip == cb); /* temporary, remove later */
6154 pCtx->rip = pVmcb->ctrl.u64NextRIP;
6155 }
6156 else
6157 pCtx->rip += cb;
6158
6159 HMSVM_UPDATE_INTR_SHADOW(pVCpu, pCtx);
6160}
6161
6162
6163#ifdef VBOX_WITH_NESTED_HWVIRT
6164/**
6165 * Gets the length of the current instruction if the CPU supports the NRIP_SAVE
6166 * feature. Otherwise, returns the value in @a cbLikely.
6167 *
6168 * @param pVCpu The cross context virtual CPU structure.
6169 * @param pCtx Pointer to the guest-CPU context.
6170 * @param cbLikely The likely instruction length.
6171 */
6172DECLINLINE(uint8_t) hmR0SvmGetInstrLengthHwAssist(PVMCPU pVCpu, PCPUMCTX pCtx, uint8_t cbLikely)
6173{
6174 Assert(cbLikely <= 15); /* See Intel spec. 2.3.11 "AVX Instruction Length" */
6175 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6176 if (fSupportsNextRipSave)
6177 {
6178 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6179 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6180 Assert(cbInstr == cbLikely);
6181 return cbInstr;
6182 }
6183 return cbLikely;
6184}
6185#endif
6186
6187
6188/**
6189 * Advances the guest RIP by the number of bytes specified in @a cb. This does
6190 * not make use of any hardware features to determine the instruction length.
6191 *
6192 * @param pVCpu The cross context virtual CPU structure.
6193 * @param pCtx Pointer to the guest-CPU context.
6194 * @param cb RIP increment value in bytes.
6195 */
6196DECLINLINE(void) hmR0SvmAdvanceRipDumb(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t cb)
6197{
6198 pCtx->rip += cb;
6199 HMSVM_UPDATE_INTR_SHADOW(pVCpu, pCtx);
6200}
6201#undef HMSVM_UPDATE_INTR_SHADOW
6202
6203
6204/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
6205/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #VMEXIT handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
6206/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
6207
6208/** @name \#VMEXIT handlers.
6209 * @{
6210 */
6211
6212/**
6213 * \#VMEXIT handler for external interrupts, NMIs, FPU assertion freeze and INIT
6214 * signals (SVM_EXIT_INTR, SVM_EXIT_NMI, SVM_EXIT_FERR_FREEZE, SVM_EXIT_INIT).
6215 */
6216HMSVM_EXIT_DECL hmR0SvmExitIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6217{
6218 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6219
6220 if (pSvmTransient->u64ExitCode == SVM_EXIT_NMI)
6221 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGC);
6222 else if (pSvmTransient->u64ExitCode == SVM_EXIT_INTR)
6223 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
6224
6225 /*
6226 * AMD-V has no preemption timer and the generic periodic preemption timer has no way to signal -before- the timer
6227 * fires if the current interrupt is our own timer or a some other host interrupt. We also cannot examine what
6228 * interrupt it is until the host actually take the interrupt.
6229 *
6230 * Going back to executing guest code here unconditionally causes random scheduling problems (observed on an
6231 * AMD Phenom 9850 Quad-Core on Windows 64-bit host).
6232 */
6233 return VINF_EM_RAW_INTERRUPT;
6234}
6235
6236
6237/**
6238 * \#VMEXIT handler for WBINVD (SVM_EXIT_WBINVD). Conditional \#VMEXIT.
6239 */
6240HMSVM_EXIT_DECL hmR0SvmExitWbinvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6241{
6242 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6243
6244 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6245 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWbinvd);
6246 int rc = VINF_SUCCESS;
6247 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6248 return rc;
6249}
6250
6251
6252/**
6253 * \#VMEXIT handler for INVD (SVM_EXIT_INVD). Unconditional \#VMEXIT.
6254 */
6255HMSVM_EXIT_DECL hmR0SvmExitInvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6256{
6257 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6258
6259 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6260 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvd);
6261 int rc = VINF_SUCCESS;
6262 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6263 return rc;
6264}
6265
6266
6267/**
6268 * \#VMEXIT handler for INVD (SVM_EXIT_CPUID). Conditional \#VMEXIT.
6269 */
6270HMSVM_EXIT_DECL hmR0SvmExitCpuid(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6271{
6272 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6273 PVM pVM = pVCpu->CTX_SUFF(pVM);
6274 int rc = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
6275 if (RT_LIKELY(rc == VINF_SUCCESS))
6276 {
6277 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6278 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6279 }
6280 else
6281 {
6282 AssertMsgFailed(("hmR0SvmExitCpuid: EMInterpretCpuId failed with %Rrc\n", rc));
6283 rc = VERR_EM_INTERPRETER;
6284 }
6285 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCpuid);
6286 return rc;
6287}
6288
6289
6290/**
6291 * \#VMEXIT handler for RDTSC (SVM_EXIT_RDTSC). Conditional \#VMEXIT.
6292 */
6293HMSVM_EXIT_DECL hmR0SvmExitRdtsc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6294{
6295 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6296 PVM pVM = pVCpu->CTX_SUFF(pVM);
6297 int rc = EMInterpretRdtsc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
6298 if (RT_LIKELY(rc == VINF_SUCCESS))
6299 {
6300 pSvmTransient->fUpdateTscOffsetting = true;
6301 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6302 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6303 }
6304 else
6305 {
6306 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtsc failed with %Rrc\n", rc));
6307 rc = VERR_EM_INTERPRETER;
6308 }
6309 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtsc);
6310 return rc;
6311}
6312
6313
6314/**
6315 * \#VMEXIT handler for RDTSCP (SVM_EXIT_RDTSCP). Conditional \#VMEXIT.
6316 */
6317HMSVM_EXIT_DECL hmR0SvmExitRdtscp(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6318{
6319 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6320 int rc = EMInterpretRdtscp(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
6321 if (RT_LIKELY(rc == VINF_SUCCESS))
6322 {
6323 pSvmTransient->fUpdateTscOffsetting = true;
6324 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3);
6325 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6326 }
6327 else
6328 {
6329 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtscp failed with %Rrc\n", rc));
6330 rc = VERR_EM_INTERPRETER;
6331 }
6332 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtscp);
6333 return rc;
6334}
6335
6336
6337/**
6338 * \#VMEXIT handler for RDPMC (SVM_EXIT_RDPMC). Conditional \#VMEXIT.
6339 */
6340HMSVM_EXIT_DECL hmR0SvmExitRdpmc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6341{
6342 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6343 int rc = EMInterpretRdpmc(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
6344 if (RT_LIKELY(rc == VINF_SUCCESS))
6345 {
6346 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6347 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6348 }
6349 else
6350 {
6351 AssertMsgFailed(("hmR0SvmExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
6352 rc = VERR_EM_INTERPRETER;
6353 }
6354 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdpmc);
6355 return rc;
6356}
6357
6358
6359/**
6360 * \#VMEXIT handler for INVLPG (SVM_EXIT_INVLPG). Conditional \#VMEXIT.
6361 */
6362HMSVM_EXIT_DECL hmR0SvmExitInvlpg(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6363{
6364 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6365 PVM pVM = pVCpu->CTX_SUFF(pVM);
6366 Assert(!pVM->hm.s.fNestedPaging);
6367 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpg);
6368
6369 bool const fSupportsDecodeAssists = hmR0SvmSupportsDecodeAssists(pVCpu, pCtx);
6370 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6371 if ( fSupportsDecodeAssists
6372 && fSupportsNextRipSave)
6373 {
6374 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6375 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6376 RTGCPTR const GCPtrPage = pVmcb->ctrl.u64ExitInfo1;
6377 VBOXSTRICTRC rcStrict = IEMExecDecodedInvlpg(pVCpu, cbInstr, GCPtrPage);
6378 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6379 return VBOXSTRICTRC_VAL(rcStrict);
6380 }
6381
6382 int rc = hmR0SvmInterpretInvlpg(pVM, pVCpu, pCtx); /* Updates RIP if successful. */
6383 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
6384 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6385 return rc;
6386}
6387
6388
6389/**
6390 * \#VMEXIT handler for HLT (SVM_EXIT_HLT). Conditional \#VMEXIT.
6391 */
6392HMSVM_EXIT_DECL hmR0SvmExitHlt(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6393{
6394 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6395
6396 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 1);
6397 int rc = EMShouldContinueAfterHalt(pVCpu, pCtx) ? VINF_SUCCESS : VINF_EM_HALT;
6398 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6399 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
6400 if (rc != VINF_SUCCESS)
6401 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHltToR3);
6402 return rc;
6403}
6404
6405
6406/**
6407 * \#VMEXIT handler for MONITOR (SVM_EXIT_MONITOR). Conditional \#VMEXIT.
6408 */
6409HMSVM_EXIT_DECL hmR0SvmExitMonitor(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6410{
6411 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6412 int rc = EMInterpretMonitor(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
6413 if (RT_LIKELY(rc == VINF_SUCCESS))
6414 {
6415 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3);
6416 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6417 }
6418 else
6419 {
6420 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMonitor: EMInterpretMonitor failed with %Rrc\n", rc));
6421 rc = VERR_EM_INTERPRETER;
6422 }
6423 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMonitor);
6424 return rc;
6425}
6426
6427
6428/**
6429 * \#VMEXIT handler for MWAIT (SVM_EXIT_MWAIT). Conditional \#VMEXIT.
6430 */
6431HMSVM_EXIT_DECL hmR0SvmExitMwait(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6432{
6433 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6434 VBOXSTRICTRC rc2 = EMInterpretMWait(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
6435 int rc = VBOXSTRICTRC_VAL(rc2);
6436 if ( rc == VINF_EM_HALT
6437 || rc == VINF_SUCCESS)
6438 {
6439 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3);
6440
6441 if ( rc == VINF_EM_HALT
6442 && EMMonitorWaitShouldContinue(pVCpu, pCtx))
6443 {
6444 rc = VINF_SUCCESS;
6445 }
6446 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6447 }
6448 else
6449 {
6450 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMwait: EMInterpretMWait failed with %Rrc\n", rc));
6451 rc = VERR_EM_INTERPRETER;
6452 }
6453 AssertMsg(rc == VINF_SUCCESS || rc == VINF_EM_HALT || rc == VERR_EM_INTERPRETER,
6454 ("hmR0SvmExitMwait: EMInterpretMWait failed rc=%Rrc\n", rc));
6455 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMwait);
6456 return rc;
6457}
6458
6459
6460/**
6461 * \#VMEXIT handler for shutdown (triple-fault) (SVM_EXIT_SHUTDOWN). Conditional
6462 * \#VMEXIT.
6463 */
6464HMSVM_EXIT_DECL hmR0SvmExitShutdown(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6465{
6466 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6467 return VINF_EM_RESET;
6468}
6469
6470
6471/**
6472 * \#VMEXIT handler for unexpected exits. Conditional \#VMEXIT.
6473 */
6474HMSVM_EXIT_DECL hmR0SvmExitUnexpected(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6475{
6476 RT_NOREF(pCtx);
6477 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6478 AssertMsgFailed(("hmR0SvmExitUnexpected: ExitCode=%#RX64 uExitInfo1=%#RX64 uExitInfo2=%#RX64\n", pSvmTransient->u64ExitCode,
6479 pVmcb->ctrl.u64ExitInfo1, pVmcb->ctrl.u64ExitInfo2));
6480 RT_NOREF(pVmcb);
6481 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
6482 return VERR_SVM_UNEXPECTED_EXIT;
6483}
6484
6485
6486/**
6487 * \#VMEXIT handler for CRx reads (SVM_EXIT_READ_CR*). Conditional \#VMEXIT.
6488 */
6489HMSVM_EXIT_DECL hmR0SvmExitReadCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6490{
6491 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6492
6493 Log4(("hmR0SvmExitReadCRx: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
6494 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxRead[pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0]);
6495
6496 bool const fSupportsDecodeAssists = hmR0SvmSupportsDecodeAssists(pVCpu, pCtx);
6497 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6498 if ( fSupportsDecodeAssists
6499 && fSupportsNextRipSave)
6500 {
6501 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6502 bool const fMovCRx = RT_BOOL(pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_MASK);
6503 if (fMovCRx)
6504 {
6505 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6506 uint8_t const iCrReg = pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0;
6507 uint8_t const iGReg = pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_GPR_NUMBER;
6508 VBOXSTRICTRC rcStrict = IEMExecDecodedMovCRxRead(pVCpu, cbInstr, iGReg, iCrReg);
6509 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6510 return VBOXSTRICTRC_VAL(rcStrict);
6511 }
6512 /* else: SMSW instruction, fall back below to IEM for this. */
6513 }
6514
6515 VBOXSTRICTRC rc2 = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
6516 int rc = VBOXSTRICTRC_VAL(rc2);
6517 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3,
6518 ("hmR0SvmExitReadCRx: EMInterpretInstruction failed rc=%Rrc\n", rc));
6519 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0) <= 15);
6520 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6521 return rc;
6522}
6523
6524
6525/**
6526 * \#VMEXIT handler for CRx writes (SVM_EXIT_WRITE_CR*). Conditional \#VMEXIT.
6527 */
6528HMSVM_EXIT_DECL hmR0SvmExitWriteCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6529{
6530 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6531
6532 uint64_t const uExitCode = pSvmTransient->u64ExitCode;
6533 uint8_t const iCrReg = uExitCode == SVM_EXIT_CR0_SEL_WRITE ? 0 : (pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0);
6534 Assert(iCrReg <= 15);
6535
6536 VBOXSTRICTRC rcStrict = VERR_SVM_IPE_5;
6537 bool fDecodedInstr = false;
6538 bool const fSupportsDecodeAssists = hmR0SvmSupportsDecodeAssists(pVCpu, pCtx);
6539 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6540 if ( fSupportsDecodeAssists
6541 && fSupportsNextRipSave)
6542 {
6543 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6544 bool const fMovCRx = RT_BOOL(pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_MASK);
6545 if (fMovCRx)
6546 {
6547 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6548 uint8_t const iGReg = pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_GPR_NUMBER;
6549 Log4(("hmR0SvmExitWriteCRx: Mov CR%u w/ iGReg=%#x\n", iCrReg, iGReg));
6550 rcStrict = IEMExecDecodedMovCRxWrite(pVCpu, cbInstr, iCrReg, iGReg);
6551 fDecodedInstr = true;
6552 }
6553 /* else: LMSW or CLTS instruction, fall back below to IEM for this. */
6554 }
6555
6556 if (!fDecodedInstr)
6557 {
6558 Log4(("hmR0SvmExitWriteCRx: iCrReg=%#x\n", iCrReg));
6559 rcStrict = IEMExecOneBypassEx(pVCpu, CPUMCTX2CORE(pCtx), NULL);
6560 if (RT_UNLIKELY( rcStrict == VERR_IEM_ASPECT_NOT_IMPLEMENTED
6561 || rcStrict == VERR_IEM_INSTR_NOT_IMPLEMENTED))
6562 rcStrict = VERR_EM_INTERPRETER;
6563 }
6564
6565 if (rcStrict == VINF_SUCCESS)
6566 {
6567 switch (iCrReg)
6568 {
6569 case 0: /* CR0. */
6570 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
6571 break;
6572
6573 case 3: /* CR3. */
6574 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR3);
6575 break;
6576
6577 case 4: /* CR4. */
6578 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR4);
6579 break;
6580
6581 case 8: /* CR8 (TPR). */
6582 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
6583 break;
6584
6585 default:
6586 AssertMsgFailed(("hmR0SvmExitWriteCRx: Invalid/Unexpected Write-CRx exit. u64ExitCode=%#RX64 %#x\n",
6587 pSvmTransient->u64ExitCode, iCrReg));
6588 break;
6589 }
6590 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6591 }
6592 else
6593 Assert(rcStrict == VERR_EM_INTERPRETER || rcStrict == VINF_PGM_CHANGE_MODE || rcStrict == VINF_PGM_SYNC_CR3);
6594 return VBOXSTRICTRC_TODO(rcStrict);
6595}
6596
6597
6598/**
6599 * \#VMEXIT handler for MSR read and writes (SVM_EXIT_MSR). Conditional
6600 * \#VMEXIT.
6601 */
6602HMSVM_EXIT_DECL hmR0SvmExitMsr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6603{
6604 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6605 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6606 PVM pVM = pVCpu->CTX_SUFF(pVM);
6607
6608 int rc;
6609 if (pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_WRITE)
6610 {
6611 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
6612 Log4(("MSR Write: idMsr=%#RX32\n", pCtx->ecx));
6613
6614 /* Handle TPR patching; intercepted LSTAR write. */
6615 if ( pVM->hm.s.fTPRPatchingActive
6616 && pCtx->ecx == MSR_K8_LSTAR)
6617 {
6618 if ((pCtx->eax & 0xff) != pSvmTransient->u8GuestTpr)
6619 {
6620 /* Our patch code uses LSTAR for TPR caching for 32-bit guests. */
6621 int rc2 = APICSetTpr(pVCpu, pCtx->eax & 0xff);
6622 AssertRC(rc2);
6623 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
6624 }
6625 rc = VINF_SUCCESS;
6626 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6627 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6628 return rc;
6629 }
6630
6631 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6632 if (fSupportsNextRipSave)
6633 {
6634 rc = EMInterpretWrmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
6635 if (RT_LIKELY(rc == VINF_SUCCESS))
6636 {
6637 pCtx->rip = pVmcb->ctrl.u64NextRIP;
6638 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6639 }
6640 else
6641 AssertMsg( rc == VERR_EM_INTERPRETER
6642 || rc == VINF_CPUM_R3_MSR_WRITE, ("hmR0SvmExitMsr: EMInterpretWrmsr failed rc=%Rrc\n", rc));
6643 }
6644 else
6645 {
6646 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */));
6647 if (RT_LIKELY(rc == VINF_SUCCESS))
6648 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc); /* RIP updated by EMInterpretInstruction(). */
6649 else
6650 AssertMsg( rc == VERR_EM_INTERPRETER
6651 || rc == VINF_CPUM_R3_MSR_WRITE, ("hmR0SvmExitMsr: WrMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
6652 }
6653
6654 if (rc == VINF_SUCCESS)
6655 {
6656 /* If this is an X2APIC WRMSR access, update the APIC state as well. */
6657 if ( pCtx->ecx >= MSR_IA32_X2APIC_START
6658 && pCtx->ecx <= MSR_IA32_X2APIC_END)
6659 {
6660 /*
6661 * We've already saved the APIC related guest-state (TPR) in hmR0SvmPostRunGuest(). When full APIC register
6662 * virtualization is implemented we'll have to make sure APIC state is saved from the VMCB before
6663 * EMInterpretWrmsr() changes it.
6664 */
6665 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
6666 }
6667 else
6668 {
6669 switch (pCtx->ecx)
6670 {
6671 case MSR_K6_EFER: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_EFER_MSR); break;
6672 case MSR_IA32_TSC: pSvmTransient->fUpdateTscOffsetting = true; break;
6673 case MSR_K8_FS_BASE:
6674 case MSR_K8_GS_BASE: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS); break;
6675 case MSR_IA32_SYSENTER_CS: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_CS_MSR); break;
6676 case MSR_IA32_SYSENTER_EIP: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_EIP_MSR); break;
6677 case MSR_IA32_SYSENTER_ESP: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_ESP_MSR); break;
6678 }
6679 }
6680 }
6681 }
6682 else
6683 {
6684 /* MSR Read access. */
6685 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
6686 Assert(pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_READ);
6687 Log4(("MSR Read: idMsr=%#RX32\n", pCtx->ecx));
6688
6689 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6690 if (fSupportsNextRipSave)
6691 {
6692 rc = EMInterpretRdmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
6693 if (RT_LIKELY(rc == VINF_SUCCESS))
6694 {
6695 pCtx->rip = pVmcb->ctrl.u64NextRIP;
6696 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6697 }
6698 else
6699 AssertMsg( rc == VERR_EM_INTERPRETER
6700 || rc == VINF_CPUM_R3_MSR_READ, ("hmR0SvmExitMsr: EMInterpretRdmsr failed rc=%Rrc\n", rc));
6701 }
6702 else
6703 {
6704 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0));
6705 if (RT_UNLIKELY(rc != VINF_SUCCESS))
6706 {
6707 AssertMsg( rc == VERR_EM_INTERPRETER
6708 || rc == VINF_CPUM_R3_MSR_READ, ("hmR0SvmExitMsr: RdMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
6709 }
6710 /* RIP updated by EMInterpretInstruction(). */
6711 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6712 }
6713 }
6714
6715 /* RIP has been updated by EMInterpret[Rd|Wr]msr() or EMInterpretInstruction(). */
6716 return rc;
6717}
6718
6719
6720/**
6721 * \#VMEXIT handler for DRx read (SVM_EXIT_READ_DRx). Conditional \#VMEXIT.
6722 */
6723HMSVM_EXIT_DECL hmR0SvmExitReadDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6724{
6725 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6726 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
6727
6728 /** @todo Stepping with nested-guest. */
6729 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
6730 {
6731 /* We should -not- get this #VMEXIT if the guest's debug registers were active. */
6732 if (pSvmTransient->fWasGuestDebugStateActive)
6733 {
6734 AssertMsgFailed(("hmR0SvmExitReadDRx: Unexpected exit %#RX32\n", (uint32_t)pSvmTransient->u64ExitCode));
6735 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
6736 return VERR_SVM_UNEXPECTED_EXIT;
6737 }
6738
6739 /*
6740 * Lazy DR0-3 loading.
6741 */
6742 if (!pSvmTransient->fWasHyperDebugStateActive)
6743 {
6744 Assert(!DBGFIsStepping(pVCpu)); Assert(!pVCpu->hm.s.fSingleInstruction);
6745 Log5(("hmR0SvmExitReadDRx: Lazy loading guest debug registers\n"));
6746
6747 /* Don't intercept DRx read and writes. */
6748 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
6749 pVmcb->ctrl.u16InterceptRdDRx = 0;
6750 pVmcb->ctrl.u16InterceptWrDRx = 0;
6751 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
6752
6753 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
6754 VMMRZCallRing3Disable(pVCpu);
6755 HM_DISABLE_PREEMPT();
6756
6757 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
6758 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
6759 Assert(CPUMIsGuestDebugStateActive(pVCpu) || HC_ARCH_BITS == 32);
6760
6761 HM_RESTORE_PREEMPT();
6762 VMMRZCallRing3Enable(pVCpu);
6763
6764 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
6765 return VINF_SUCCESS;
6766 }
6767 }
6768
6769 /*
6770 * Interpret the read/writing of DRx.
6771 */
6772 /** @todo Decode assist. */
6773 VBOXSTRICTRC rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
6774 Log5(("hmR0SvmExitReadDRx: Emulated DRx access: rc=%Rrc\n", VBOXSTRICTRC_VAL(rc)));
6775 if (RT_LIKELY(rc == VINF_SUCCESS))
6776 {
6777 /* Not necessary for read accesses but whatever doesn't hurt for now, will be fixed with decode assist. */
6778 /** @todo CPUM should set this flag! */
6779 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);
6780 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6781 }
6782 else
6783 Assert(rc == VERR_EM_INTERPRETER);
6784 return VBOXSTRICTRC_TODO(rc);
6785}
6786
6787
6788/**
6789 * \#VMEXIT handler for DRx write (SVM_EXIT_WRITE_DRx). Conditional \#VMEXIT.
6790 */
6791HMSVM_EXIT_DECL hmR0SvmExitWriteDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6792{
6793 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6794 /* For now it's the same since we interpret the instruction anyway. Will change when using of Decode Assist is implemented. */
6795 int rc = hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
6796 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
6797 STAM_COUNTER_DEC(&pVCpu->hm.s.StatExitDRxRead);
6798 return rc;
6799}
6800
6801
6802/**
6803 * \#VMEXIT handler for XCRx write (SVM_EXIT_XSETBV). Conditional \#VMEXIT.
6804 */
6805HMSVM_EXIT_DECL hmR0SvmExitXsetbv(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6806{
6807 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6808
6809 /** @todo decode assists... */
6810 VBOXSTRICTRC rcStrict = IEMExecOne(pVCpu);
6811 if (rcStrict == VINF_IEM_RAISED_XCPT)
6812 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
6813
6814 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pCtx->cr4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
6815 Log4(("hmR0SvmExitXsetbv: New XCR0=%#RX64 fLoadSaveGuestXcr0=%d (cr4=%RX64) rcStrict=%Rrc\n",
6816 pCtx->aXcr[0], pVCpu->hm.s.fLoadSaveGuestXcr0, pCtx->cr4, VBOXSTRICTRC_VAL(rcStrict)));
6817
6818 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6819 return VBOXSTRICTRC_TODO(rcStrict);
6820}
6821
6822
6823/**
6824 * \#VMEXIT handler for I/O instructions (SVM_EXIT_IOIO). Conditional \#VMEXIT.
6825 */
6826HMSVM_EXIT_DECL hmR0SvmExitIOInstr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6827{
6828 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6829
6830 /* I/O operation lookup arrays. */
6831 static uint32_t const s_aIOSize[8] = { 0, 1, 2, 0, 4, 0, 0, 0 }; /* Size of the I/O accesses in bytes. */
6832 static uint32_t const s_aIOOpAnd[8] = { 0, 0xff, 0xffff, 0, 0xffffffff, 0, 0, 0 }; /* AND masks for saving
6833 the result (in AL/AX/EAX). */
6834 Log4(("hmR0SvmExitIOInstr: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
6835
6836 PVM pVM = pVCpu->CTX_SUFF(pVM);
6837 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6838
6839 /* Refer AMD spec. 15.10.2 "IN and OUT Behaviour" and Figure 15-2. "EXITINFO1 for IOIO Intercept" for the format. */
6840 SVMIOIOEXITINFO IoExitInfo;
6841 IoExitInfo.u = (uint32_t)pVmcb->ctrl.u64ExitInfo1;
6842 uint32_t uIOWidth = (IoExitInfo.u >> 4) & 0x7;
6843 uint32_t cbValue = s_aIOSize[uIOWidth];
6844 uint32_t uAndVal = s_aIOOpAnd[uIOWidth];
6845
6846 if (RT_UNLIKELY(!cbValue))
6847 {
6848 AssertMsgFailed(("hmR0SvmExitIOInstr: Invalid IO operation. uIOWidth=%u\n", uIOWidth));
6849 return VERR_EM_INTERPRETER;
6850 }
6851
6852 VBOXSTRICTRC rcStrict;
6853 bool fUpdateRipAlready = false;
6854 if (IoExitInfo.n.u1Str)
6855 {
6856#ifdef VBOX_WITH_2ND_IEM_STEP
6857 /* INS/OUTS - I/O String instruction. */
6858 /** @todo Huh? why can't we use the segment prefix information given by AMD-V
6859 * in EXITINFO1? Investigate once this thing is up and running. */
6860 Log4(("CS:RIP=%04x:%08RX64 %#06x/%u %c str\n", pCtx->cs.Sel, pCtx->rip, IoExitInfo.n.u16Port, cbValue,
6861 IoExitInfo.n.u1Type == SVM_IOIO_WRITE ? 'w' : 'r'));
6862 AssertReturn(pCtx->dx == IoExitInfo.n.u16Port, VERR_SVM_IPE_2);
6863 static IEMMODE const s_aenmAddrMode[8] =
6864 {
6865 (IEMMODE)-1, IEMMODE_16BIT, IEMMODE_32BIT, (IEMMODE)-1, IEMMODE_64BIT, (IEMMODE)-1, (IEMMODE)-1, (IEMMODE)-1
6866 };
6867 IEMMODE enmAddrMode = s_aenmAddrMode[(IoExitInfo.u >> 7) & 0x7];
6868 if (enmAddrMode != (IEMMODE)-1)
6869 {
6870 uint64_t cbInstr = pVmcb->ctrl.u64ExitInfo2 - pCtx->rip;
6871 if (cbInstr <= 15 && cbInstr >= 1)
6872 {
6873 Assert(cbInstr >= 1U + IoExitInfo.n.u1Rep);
6874 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
6875 {
6876 /* Don't know exactly how to detect whether u3Seg is valid, currently
6877 only enabling it for Bulldozer and later with NRIP. OS/2 broke on
6878 2384 Opterons when only checking NRIP. */
6879 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6880 if ( fSupportsNextRipSave
6881 && pVM->cpum.ro.GuestFeatures.enmMicroarch >= kCpumMicroarch_AMD_15h_First)
6882 {
6883 AssertMsg(IoExitInfo.n.u3Seg == X86_SREG_DS || cbInstr > 1U + IoExitInfo.n.u1Rep,
6884 ("u32Seg=%d cbInstr=%d u1REP=%d", IoExitInfo.n.u3Seg, cbInstr, IoExitInfo.n.u1Rep));
6885 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1Rep, (uint8_t)cbInstr,
6886 IoExitInfo.n.u3Seg, true /*fIoChecked*/);
6887 }
6888 else if (cbInstr == 1U + IoExitInfo.n.u1Rep)
6889 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1Rep, (uint8_t)cbInstr,
6890 X86_SREG_DS, true /*fIoChecked*/);
6891 else
6892 rcStrict = IEMExecOne(pVCpu);
6893 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
6894 }
6895 else
6896 {
6897 AssertMsg(IoExitInfo.n.u3Seg == X86_SREG_ES /*=0*/, ("%#x\n", IoExitInfo.n.u3Seg));
6898 rcStrict = IEMExecStringIoRead(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1Rep, (uint8_t)cbInstr,
6899 true /*fIoChecked*/);
6900 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
6901 }
6902 }
6903 else
6904 {
6905 AssertMsgFailed(("rip=%RX64 nrip=%#RX64 cbInstr=%#RX64\n", pCtx->rip, pVmcb->ctrl.u64ExitInfo2, cbInstr));
6906 rcStrict = IEMExecOne(pVCpu);
6907 }
6908 }
6909 else
6910 {
6911 AssertMsgFailed(("IoExitInfo=%RX64\n", IoExitInfo.u));
6912 rcStrict = IEMExecOne(pVCpu);
6913 }
6914 fUpdateRipAlready = true;
6915
6916#else
6917 /* INS/OUTS - I/O String instruction. */
6918 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
6919
6920 /** @todo Huh? why can't we use the segment prefix information given by AMD-V
6921 * in EXITINFO1? Investigate once this thing is up and running. */
6922
6923 rcStrict = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL);
6924 if (rcStrict == VINF_SUCCESS)
6925 {
6926 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
6927 {
6928 rcStrict = IOMInterpretOUTSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
6929 (DISCPUMODE)pDis->uAddrMode, cbValue);
6930 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
6931 }
6932 else
6933 {
6934 rcStrict = IOMInterpretINSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
6935 (DISCPUMODE)pDis->uAddrMode, cbValue);
6936 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
6937 }
6938 }
6939 else
6940 rcStrict = VINF_EM_RAW_EMULATE_INSTR;
6941#endif
6942 }
6943 else
6944 {
6945 /* IN/OUT - I/O instruction. */
6946 Assert(!IoExitInfo.n.u1Rep);
6947
6948 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
6949 {
6950 rcStrict = IOMIOPortWrite(pVM, pVCpu, IoExitInfo.n.u16Port, pCtx->eax & uAndVal, cbValue);
6951 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
6952 }
6953 else
6954 {
6955 uint32_t u32Val = 0;
6956 rcStrict = IOMIOPortRead(pVM, pVCpu, IoExitInfo.n.u16Port, &u32Val, cbValue);
6957 if (IOM_SUCCESS(rcStrict))
6958 {
6959 /* Save result of I/O IN instr. in AL/AX/EAX. */
6960 /** @todo r=bird: 32-bit op size should clear high bits of rax! */
6961 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
6962 }
6963 else if (rcStrict == VINF_IOM_R3_IOPORT_READ)
6964 HMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, cbValue);
6965
6966 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
6967 }
6968 }
6969
6970 if (IOM_SUCCESS(rcStrict))
6971 {
6972 /* AMD-V saves the RIP of the instruction following the IO instruction in EXITINFO2. */
6973 if (!fUpdateRipAlready)
6974 pCtx->rip = pVmcb->ctrl.u64ExitInfo2;
6975
6976 /*
6977 * If any I/O breakpoints are armed, we need to check if one triggered
6978 * and take appropriate action.
6979 * Note that the I/O breakpoint type is undefined if CR4.DE is 0.
6980 */
6981 /** @todo Optimize away the DBGFBpIsHwIoArmed call by having DBGF tell the
6982 * execution engines about whether hyper BPs and such are pending. */
6983 uint32_t const uDr7 = pCtx->dr[7];
6984 if (RT_UNLIKELY( ( (uDr7 & X86_DR7_ENABLED_MASK)
6985 && X86_DR7_ANY_RW_IO(uDr7)
6986 && (pCtx->cr4 & X86_CR4_DE))
6987 || DBGFBpIsHwIoArmed(pVM)))
6988 {
6989 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
6990 VMMRZCallRing3Disable(pVCpu);
6991 HM_DISABLE_PREEMPT();
6992
6993 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
6994 CPUMR0DebugStateMaybeSaveGuest(pVCpu, false /*fDr6*/);
6995
6996 VBOXSTRICTRC rcStrict2 = DBGFBpCheckIo(pVM, pVCpu, pCtx, IoExitInfo.n.u16Port, cbValue);
6997 if (rcStrict2 == VINF_EM_RAW_GUEST_TRAP)
6998 {
6999 /* Raise #DB. */
7000 pVmcb->guest.u64DR6 = pCtx->dr[6];
7001 pVmcb->guest.u64DR7 = pCtx->dr[7];
7002 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
7003 hmR0SvmSetPendingXcptDB(pVCpu);
7004 }
7005 /* rcStrict is VINF_SUCCESS, VINF_IOM_R3_IOPORT_COMMIT_WRITE, or in [VINF_EM_FIRST..VINF_EM_LAST],
7006 however we can ditch VINF_IOM_R3_IOPORT_COMMIT_WRITE as it has VMCPU_FF_IOM as backup. */
7007 else if ( rcStrict2 != VINF_SUCCESS
7008 && (rcStrict == VINF_SUCCESS || rcStrict2 < rcStrict))
7009 rcStrict = rcStrict2;
7010 AssertCompile(VINF_EM_LAST < VINF_IOM_R3_IOPORT_COMMIT_WRITE);
7011
7012 HM_RESTORE_PREEMPT();
7013 VMMRZCallRing3Enable(pVCpu);
7014 }
7015
7016 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
7017 }
7018
7019#ifdef VBOX_STRICT
7020 if (rcStrict == VINF_IOM_R3_IOPORT_READ)
7021 Assert(IoExitInfo.n.u1Type == SVM_IOIO_READ);
7022 else if (rcStrict == VINF_IOM_R3_IOPORT_WRITE || rcStrict == VINF_IOM_R3_IOPORT_COMMIT_WRITE)
7023 Assert(IoExitInfo.n.u1Type == SVM_IOIO_WRITE);
7024 else
7025 {
7026 /** @todo r=bird: This is missing a bunch of VINF_EM_FIRST..VINF_EM_LAST
7027 * statuses, that the VMM device and some others may return. See
7028 * IOM_SUCCESS() for guidance. */
7029 AssertMsg( RT_FAILURE(rcStrict)
7030 || rcStrict == VINF_SUCCESS
7031 || rcStrict == VINF_EM_RAW_EMULATE_INSTR
7032 || rcStrict == VINF_EM_DBG_BREAKPOINT
7033 || rcStrict == VINF_EM_RAW_GUEST_TRAP
7034 || rcStrict == VINF_EM_RAW_TO_R3
7035 || rcStrict == VINF_TRPM_XCPT_DISPATCHED
7036 || rcStrict == VINF_EM_TRIPLE_FAULT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
7037 }
7038#endif
7039 return VBOXSTRICTRC_TODO(rcStrict);
7040}
7041
7042
7043/**
7044 * \#VMEXIT handler for Nested Page-faults (SVM_EXIT_NPF). Conditional \#VMEXIT.
7045 */
7046HMSVM_EXIT_DECL hmR0SvmExitNestedPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7047{
7048 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7049 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
7050
7051 PVM pVM = pVCpu->CTX_SUFF(pVM);
7052 Assert(pVM->hm.s.fNestedPaging);
7053
7054 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7055
7056 /* See AMD spec. 15.25.6 "Nested versus Guest Page Faults, Fault Ordering" for VMCB details for #NPF. */
7057 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
7058 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1; /** @todo Make it more explicit that high bits can be non-zero. */
7059 RTGCPHYS GCPhysFaultAddr = pVmcb->ctrl.u64ExitInfo2;
7060
7061 Log4(("#NPF at CS:RIP=%04x:%#RX64 faultaddr=%RGp errcode=%#x \n", pCtx->cs.Sel, pCtx->rip, GCPhysFaultAddr, u32ErrCode));
7062
7063#ifdef VBOX_HM_WITH_GUEST_PATCHING
7064 /* TPR patching for 32-bit guests, using the reserved bit in the page tables for MMIO regions. */
7065 if ( pVM->hm.s.fTprPatchingAllowed
7066 && (GCPhysFaultAddr & PAGE_OFFSET_MASK) == XAPIC_OFF_TPR
7067 && ( !(u32ErrCode & X86_TRAP_PF_P) /* Not present */
7068 || (u32ErrCode & (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) == (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) /* MMIO page. */
7069 && !CPUMIsGuestInLongModeEx(pCtx)
7070 && !CPUMGetGuestCPL(pVCpu)
7071 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
7072 {
7073 RTGCPHYS GCPhysApicBase = APICGetBaseMsrNoCheck(pVCpu);
7074 GCPhysApicBase &= PAGE_BASE_GC_MASK;
7075
7076 if (GCPhysFaultAddr == GCPhysApicBase + XAPIC_OFF_TPR)
7077 {
7078 /* Only attempt to patch the instruction once. */
7079 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
7080 if (!pPatch)
7081 return VINF_EM_HM_PATCH_TPR_INSTR;
7082 }
7083 }
7084#endif
7085
7086 /*
7087 * Determine the nested paging mode.
7088 */
7089 PGMMODE enmNestedPagingMode;
7090#if HC_ARCH_BITS == 32
7091 if (CPUMIsGuestInLongModeEx(pCtx))
7092 enmNestedPagingMode = PGMMODE_AMD64_NX;
7093 else
7094#endif
7095 enmNestedPagingMode = PGMGetHostMode(pVM);
7096
7097 /*
7098 * MMIO optimization using the reserved (RSVD) bit in the guest page tables for MMIO pages.
7099 */
7100 int rc;
7101 Assert((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) != X86_TRAP_PF_RSVD);
7102 if ((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) == (X86_TRAP_PF_RSVD | X86_TRAP_PF_P))
7103 {
7104 /* If event delivery causes an MMIO #NPF, go back to instruction emulation as
7105 otherwise injecting the original pending event would most likely cause the same MMIO #NPF. */
7106 if (pVCpu->hm.s.Event.fPending)
7107 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7108
7109 VBOXSTRICTRC rc2 = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, enmNestedPagingMode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr,
7110 u32ErrCode);
7111 rc = VBOXSTRICTRC_VAL(rc2);
7112
7113 /*
7114 * If we succeed, resume guest execution.
7115 * If we fail in interpreting the instruction because we couldn't get the guest physical address
7116 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
7117 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
7118 * weird case. See @bugref{6043}.
7119 */
7120 if ( rc == VINF_SUCCESS
7121 || rc == VERR_PAGE_TABLE_NOT_PRESENT
7122 || rc == VERR_PAGE_NOT_PRESENT)
7123 {
7124 /* Successfully handled MMIO operation. */
7125 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
7126 rc = VINF_SUCCESS;
7127 }
7128 return rc;
7129 }
7130
7131 TRPMAssertXcptPF(pVCpu, GCPhysFaultAddr, u32ErrCode);
7132 rc = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, enmNestedPagingMode, u32ErrCode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr);
7133 TRPMResetTrap(pVCpu);
7134
7135 Log4(("#NPF: PGMR0Trap0eHandlerNestedPaging returned %Rrc CS:RIP=%04x:%#RX64\n", rc, pCtx->cs.Sel, pCtx->rip));
7136
7137 /*
7138 * Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}.
7139 */
7140 if ( rc == VINF_SUCCESS
7141 || rc == VERR_PAGE_TABLE_NOT_PRESENT
7142 || rc == VERR_PAGE_NOT_PRESENT)
7143 {
7144 /* We've successfully synced our shadow page tables. */
7145 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
7146 rc = VINF_SUCCESS;
7147 }
7148
7149 return rc;
7150}
7151
7152
7153/**
7154 * \#VMEXIT handler for virtual interrupt (SVM_EXIT_VINTR). Conditional
7155 * \#VMEXIT.
7156 */
7157HMSVM_EXIT_DECL hmR0SvmExitVIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7158{
7159 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7160 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
7161
7162 /* Indicate that we no longer need to #VMEXIT when the guest is ready to receive NMIs, it is now ready. */
7163 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7164 hmR0SvmClearVirtIntrIntercept(pVmcb);
7165
7166 /* Deliver the pending interrupt via hmR0SvmEvaluatePendingEvent() and resume guest execution. */
7167 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
7168 return VINF_SUCCESS;
7169}
7170
7171
7172/**
7173 * \#VMEXIT handler for task switches (SVM_EXIT_TASK_SWITCH). Conditional
7174 * \#VMEXIT.
7175 */
7176HMSVM_EXIT_DECL hmR0SvmExitTaskSwitch(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7177{
7178 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7179
7180 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7181
7182#ifndef HMSVM_ALWAYS_TRAP_TASK_SWITCH
7183 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
7184#endif
7185
7186 /* Check if this task-switch occurred while delivering an event through the guest IDT. */
7187 if (pVCpu->hm.s.Event.fPending) /* Can happen with exceptions/NMI. See @bugref{8411}. */
7188 {
7189 /*
7190 * AMD-V provides us with the exception which caused the TS; we collect
7191 * the information in the call to hmR0SvmCheckExitDueToEventDelivery.
7192 */
7193 Log4(("hmR0SvmExitTaskSwitch: TS occurred during event delivery.\n"));
7194 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
7195 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7196 }
7197
7198 /** @todo Emulate task switch someday, currently just going back to ring-3 for
7199 * emulation. */
7200 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
7201 return VERR_EM_INTERPRETER;
7202}
7203
7204
7205/**
7206 * \#VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional \#VMEXIT.
7207 */
7208HMSVM_EXIT_DECL hmR0SvmExitVmmCall(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7209{
7210 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7211 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitVmcall);
7212
7213 bool fRipUpdated;
7214 VBOXSTRICTRC rcStrict = HMSvmVmmcall(pVCpu, pCtx, &fRipUpdated);
7215 if (RT_SUCCESS(rcStrict))
7216 {
7217 /* Only update the RIP if we're continuing guest execution and not
7218 in the case of say VINF_GIM_R3_HYPERCALL. */
7219 if ( rcStrict == VINF_SUCCESS
7220 && !fRipUpdated)
7221 {
7222 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3 /* cbInstr */);
7223 }
7224
7225 /* If the hypercall or TPR patching changes anything other than guest's general-purpose registers,
7226 we would need to reload the guest changed bits here before VM-entry. */
7227 return VBOXSTRICTRC_VAL(rcStrict);
7228 }
7229
7230 hmR0SvmSetPendingXcptUD(pVCpu);
7231 return VINF_SUCCESS;
7232}
7233
7234
7235/**
7236 * \#VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional \#VMEXIT.
7237 */
7238HMSVM_EXIT_DECL hmR0SvmExitPause(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7239{
7240 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7241 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitPause);
7242 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
7243 /** @todo The guest has likely hit a contended spinlock. We might want to
7244 * poke a schedule different guest VCPU. */
7245 return VINF_EM_RAW_INTERRUPT;
7246}
7247
7248
7249/**
7250 * \#VMEXIT handler for FERR intercept (SVM_EXIT_FERR_FREEZE). Conditional
7251 * \#VMEXIT.
7252 */
7253HMSVM_EXIT_DECL hmR0SvmExitFerrFreeze(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7254{
7255 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7256 Assert(!(pCtx->cr0 & X86_CR0_NE));
7257
7258 Log4(("hmR0SvmExitFerrFreeze: Raising IRQ 13 in response to #FERR\n"));
7259 return PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13 /* u8Irq */, 1 /* u8Level */, 0 /* uTagSrc */);
7260}
7261
7262
7263/**
7264 * \#VMEXIT handler for IRET (SVM_EXIT_IRET). Conditional \#VMEXIT.
7265 */
7266HMSVM_EXIT_DECL hmR0SvmExitIret(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7267{
7268 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7269
7270 /* Clear NMI blocking. */
7271 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
7272
7273 /* Indicate that we no longer need to #VMEXIT when the guest is ready to receive NMIs, it is now ready. */
7274 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7275 hmR0SvmClearIretIntercept(pVmcb);
7276
7277 /* Deliver the pending NMI via hmR0SvmEvaluatePendingEvent() and resume guest execution. */
7278 return VINF_SUCCESS;
7279}
7280
7281
7282/**
7283 * \#VMEXIT handler for page-fault exceptions (SVM_EXIT_XCPT_14).
7284 * Conditional \#VMEXIT.
7285 */
7286HMSVM_EXIT_DECL hmR0SvmExitXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7287{
7288 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7289 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
7290
7291 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7292
7293 /* See AMD spec. 15.12.15 "#PF (Page Fault)". */
7294 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
7295 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1;
7296 RTGCUINTPTR uFaultAddress = pVmcb->ctrl.u64ExitInfo2;
7297 PVM pVM = pVCpu->CTX_SUFF(pVM);
7298
7299#if defined(HMSVM_ALWAYS_TRAP_ALL_XCPTS) || defined(HMSVM_ALWAYS_TRAP_PF)
7300 if (pVM->hm.s.fNestedPaging)
7301 {
7302 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
7303 if (!pSvmTransient->fVectoringDoublePF)
7304 {
7305 /* A genuine guest #PF, reflect it to the guest. */
7306 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
7307 Log4(("#PF: Guest page fault at %04X:%RGv FaultAddr=%RGv ErrCode=%#x\n", pCtx->cs.Sel, (RTGCPTR)pCtx->rip,
7308 uFaultAddress, u32ErrCode));
7309 }
7310 else
7311 {
7312 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
7313 hmR0SvmSetPendingXcptDF(pVCpu);
7314 Log4(("Pending #DF due to vectoring #PF. NP\n"));
7315 }
7316 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
7317 return VINF_SUCCESS;
7318 }
7319#endif
7320
7321 Assert(!pVM->hm.s.fNestedPaging);
7322
7323#ifdef VBOX_HM_WITH_GUEST_PATCHING
7324 /* Shortcut for APIC TPR reads and writes; only applicable to 32-bit guests. */
7325 if ( pVM->hm.s.fTprPatchingAllowed
7326 && (uFaultAddress & 0xfff) == XAPIC_OFF_TPR
7327 && !(u32ErrCode & X86_TRAP_PF_P) /* Not present. */
7328 && !CPUMIsGuestInLongModeEx(pCtx)
7329 && !CPUMGetGuestCPL(pVCpu)
7330 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
7331 {
7332 RTGCPHYS GCPhysApicBase;
7333 GCPhysApicBase = APICGetBaseMsrNoCheck(pVCpu);
7334 GCPhysApicBase &= PAGE_BASE_GC_MASK;
7335
7336 /* Check if the page at the fault-address is the APIC base. */
7337 RTGCPHYS GCPhysPage;
7338 int rc2 = PGMGstGetPage(pVCpu, (RTGCPTR)uFaultAddress, NULL /* pfFlags */, &GCPhysPage);
7339 if ( rc2 == VINF_SUCCESS
7340 && GCPhysPage == GCPhysApicBase)
7341 {
7342 /* Only attempt to patch the instruction once. */
7343 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
7344 if (!pPatch)
7345 return VINF_EM_HM_PATCH_TPR_INSTR;
7346 }
7347 }
7348#endif
7349
7350 Log4(("#PF: uFaultAddress=%#RX64 CS:RIP=%#04x:%#RX64 u32ErrCode %#RX32 cr3=%#RX64\n", uFaultAddress, pCtx->cs.Sel,
7351 pCtx->rip, u32ErrCode, pCtx->cr3));
7352
7353 /* If it's a vectoring #PF, emulate injecting the original event injection as PGMTrap0eHandler() is incapable
7354 of differentiating between instruction emulation and event injection that caused a #PF. See @bugref{6607}. */
7355 if (pSvmTransient->fVectoringPF)
7356 {
7357 Assert(pVCpu->hm.s.Event.fPending);
7358 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7359 }
7360
7361 TRPMAssertXcptPF(pVCpu, uFaultAddress, u32ErrCode);
7362 int rc = PGMTrap0eHandler(pVCpu, u32ErrCode, CPUMCTX2CORE(pCtx), (RTGCPTR)uFaultAddress);
7363
7364 Log4(("#PF rc=%Rrc\n", rc));
7365
7366 if (rc == VINF_SUCCESS)
7367 {
7368 /* Successfully synced shadow pages tables or emulated an MMIO instruction. */
7369 TRPMResetTrap(pVCpu);
7370 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
7371 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
7372 return rc;
7373 }
7374 else if (rc == VINF_EM_RAW_GUEST_TRAP)
7375 {
7376 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
7377
7378 if (!pSvmTransient->fVectoringDoublePF)
7379 {
7380 /* It's a guest page fault and needs to be reflected to the guest. */
7381 u32ErrCode = TRPMGetErrorCode(pVCpu); /* The error code might have been changed. */
7382 TRPMResetTrap(pVCpu);
7383 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
7384 }
7385 else
7386 {
7387 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
7388 TRPMResetTrap(pVCpu);
7389 hmR0SvmSetPendingXcptDF(pVCpu);
7390 Log4(("#PF: Pending #DF due to vectoring #PF\n"));
7391 }
7392
7393 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
7394 return VINF_SUCCESS;
7395 }
7396
7397 TRPMResetTrap(pVCpu);
7398 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
7399 return rc;
7400}
7401
7402
7403/**
7404 * \#VMEXIT handler for undefined opcode (SVM_EXIT_XCPT_6).
7405 * Conditional \#VMEXIT.
7406 */
7407HMSVM_EXIT_DECL hmR0SvmExitXcptUD(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7408{
7409 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7410 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
7411
7412 /* Paranoia; Ensure we cannot be called as a result of event delivery. */
7413 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
7414 Assert(!pVmcb->ctrl.ExitIntInfo.n.u1Valid); NOREF(pVmcb);
7415
7416 int rc = VERR_SVM_UNEXPECTED_XCPT_EXIT;
7417 if (pVCpu->hm.s.fGIMTrapXcptUD)
7418 {
7419 uint8_t cbInstr = 0;
7420 VBOXSTRICTRC rcStrict = GIMXcptUD(pVCpu, pCtx, NULL /* pDis */, &cbInstr);
7421 if (rcStrict == VINF_SUCCESS)
7422 {
7423 /* #UD #VMEXIT does not have valid NRIP information, manually advance RIP. See @bugref{7270#c170}. */
7424 hmR0SvmAdvanceRipDumb(pVCpu, pCtx, cbInstr);
7425 rc = VINF_SUCCESS;
7426 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
7427 }
7428 else if (rcStrict == VINF_GIM_HYPERCALL_CONTINUING)
7429 rc = VINF_SUCCESS;
7430 else if (rcStrict == VINF_GIM_R3_HYPERCALL)
7431 rc = VINF_GIM_R3_HYPERCALL;
7432 else
7433 Assert(RT_FAILURE(VBOXSTRICTRC_VAL(rcStrict)));
7434 }
7435
7436 /* If the GIM #UD exception handler didn't succeed for some reason or wasn't needed, raise #UD. */
7437 if (RT_FAILURE(rc))
7438 {
7439 hmR0SvmSetPendingXcptUD(pVCpu);
7440 rc = VINF_SUCCESS;
7441 }
7442
7443 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD);
7444 return rc;
7445}
7446
7447
7448/**
7449 * \#VMEXIT handler for math-fault exceptions (SVM_EXIT_XCPT_16).
7450 * Conditional \#VMEXIT.
7451 */
7452HMSVM_EXIT_DECL hmR0SvmExitXcptMF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7453{
7454 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7455
7456 /* Paranoia; Ensure we cannot be called as a result of event delivery. */
7457 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7458 Assert(!pVmcb->ctrl.ExitIntInfo.n.u1Valid); NOREF(pVmcb);
7459
7460 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
7461
7462 if (!(pCtx->cr0 & X86_CR0_NE))
7463 {
7464 PVM pVM = pVCpu->CTX_SUFF(pVM);
7465 PDISSTATE pDis = &pVCpu->hm.s.DisState;
7466 unsigned cbOp;
7467 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
7468 if (RT_SUCCESS(rc))
7469 {
7470 /* Convert a #MF into a FERR -> IRQ 13. See @bugref{6117}. */
7471 rc = PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13 /* u8Irq */, 1 /* u8Level */, 0 /* uTagSrc */);
7472 if (RT_SUCCESS(rc))
7473 pCtx->rip += cbOp;
7474 }
7475 else
7476 Log4(("hmR0SvmExitXcptMF: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
7477 return rc;
7478 }
7479
7480 hmR0SvmSetPendingXcptMF(pVCpu);
7481 return VINF_SUCCESS;
7482}
7483
7484
7485/**
7486 * \#VMEXIT handler for debug exceptions (SVM_EXIT_XCPT_1). Conditional
7487 * \#VMEXIT.
7488 */
7489HMSVM_EXIT_DECL hmR0SvmExitXcptDB(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7490{
7491 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7492
7493 /* If this #DB is the result of delivering an event, go back to the interpreter. */
7494 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7495 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
7496 {
7497 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingInterpret);
7498 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7499 }
7500
7501 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
7502
7503 /* This can be a fault-type #DB (instruction breakpoint) or a trap-type #DB (data breakpoint). However, for both cases
7504 DR6 and DR7 are updated to what the exception handler expects. See AMD spec. 15.12.2 "#DB (Debug)". */
7505 PVM pVM = pVCpu->CTX_SUFF(pVM);
7506 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
7507 int rc = DBGFRZTrap01Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx), pVmcb->guest.u64DR6, pVCpu->hm.s.fSingleInstruction);
7508 if (rc == VINF_EM_RAW_GUEST_TRAP)
7509 {
7510 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> guest trap\n", pVmcb->guest.u64DR6));
7511 if (CPUMIsHyperDebugStateActive(pVCpu))
7512 CPUMSetGuestDR6(pVCpu, CPUMGetGuestDR6(pVCpu) | pVmcb->guest.u64DR6);
7513
7514 /* Reflect the exception back to the guest. */
7515 hmR0SvmSetPendingXcptDB(pVCpu);
7516 rc = VINF_SUCCESS;
7517 }
7518
7519 /*
7520 * Update DR6.
7521 */
7522 if (CPUMIsHyperDebugStateActive(pVCpu))
7523 {
7524 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> %Rrc\n", pVmcb->guest.u64DR6, rc));
7525 pVmcb->guest.u64DR6 = X86_DR6_INIT_VAL;
7526 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
7527 }
7528 else
7529 {
7530 AssertMsg(rc == VINF_SUCCESS, ("rc=%Rrc\n", rc));
7531 Assert(!pVCpu->hm.s.fSingleInstruction && !DBGFIsStepping(pVCpu));
7532 }
7533
7534 return rc;
7535}
7536
7537
7538/**
7539 * \#VMEXIT handler for alignment check exceptions (SVM_EXIT_XCPT_17).
7540 * Conditional \#VMEXIT.
7541 */
7542HMSVM_EXIT_DECL hmR0SvmExitXcptAC(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7543{
7544 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7545
7546 /** @todo if triple-fault is returned in nested-guest scenario convert to a
7547 * shutdown VMEXIT. */
7548 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7549
7550 SVMEVENT Event;
7551 Event.u = 0;
7552 Event.n.u1Valid = 1;
7553 Event.n.u3Type = SVM_EVENT_EXCEPTION;
7554 Event.n.u8Vector = X86_XCPT_AC;
7555 Event.n.u1ErrorCodeValid = 1;
7556 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
7557 return VINF_SUCCESS;
7558}
7559
7560
7561/**
7562 * \#VMEXIT handler for breakpoint exceptions (SVM_EXIT_XCPT_3).
7563 * Conditional \#VMEXIT.
7564 */
7565HMSVM_EXIT_DECL hmR0SvmExitXcptBP(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7566{
7567 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7568
7569 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7570
7571 int rc = DBGFRZTrap03Handler(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
7572 if (rc == VINF_EM_RAW_GUEST_TRAP)
7573 {
7574 SVMEVENT Event;
7575 Event.u = 0;
7576 Event.n.u1Valid = 1;
7577 Event.n.u3Type = SVM_EVENT_EXCEPTION;
7578 Event.n.u8Vector = X86_XCPT_BP;
7579 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
7580 }
7581
7582 Assert(rc == VINF_SUCCESS || rc == VINF_EM_RAW_GUEST_TRAP || rc == VINF_EM_DBG_BREAKPOINT);
7583 return rc;
7584}
7585
7586
7587#if defined(HMSVM_ALWAYS_TRAP_ALL_XCPTS) || defined(VBOX_WITH_NESTED_HWVIRT)
7588/**
7589 * \#VMEXIT handler for generic exceptions. Conditional \#VMEXIT.
7590 */
7591HMSVM_EXIT_DECL hmR0SvmExitXcptGeneric(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7592{
7593 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7594
7595 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7596
7597 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7598 uint8_t const uVector = pVmcb->ctrl.u64ExitCode - SVM_EXIT_XCPT_0;
7599 uint32_t const uErrCode = pVmcb->ctrl.u64ExitInfo1;
7600 Assert(pSvmTransient->u64ExitCode == pVmcb->ctrl.u64ExitCode);
7601 Assert(uVector <= X86_XCPT_LAST);
7602 Log4(("hmR0SvmExitXcptGeneric: uVector=%#x uErrCode=%u\n", uVector, uErrCode));
7603
7604 SVMEVENT Event;
7605 Event.u = 0;
7606 Event.n.u1Valid = 1;
7607 Event.n.u3Type = SVM_EVENT_EXCEPTION;
7608 Event.n.u8Vector = uVector;
7609 switch (uVector)
7610 {
7611 /* Shouldn't be here for reflecting #PFs (among other things, the fault address isn't passed along). */
7612 case X86_XCPT_PF: AssertMsgFailed(("hmR0SvmExitXcptGeneric: Unexpected exception")); return VERR_SVM_IPE_5;
7613 case X86_XCPT_DF:
7614 case X86_XCPT_TS:
7615 case X86_XCPT_NP:
7616 case X86_XCPT_SS:
7617 case X86_XCPT_GP:
7618 case X86_XCPT_AC:
7619 {
7620 Event.n.u1ErrorCodeValid = 1;
7621 Event.n.u32ErrorCode = uErrCode;
7622 break;
7623 }
7624 }
7625
7626 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
7627 return VINF_SUCCESS;
7628}
7629#endif
7630
7631#ifdef VBOX_WITH_NESTED_HWVIRT
7632/**
7633 * \#VMEXIT handler for #PF occuring while in nested-guest execution
7634 * (SVM_EXIT_XCPT_14). Conditional \#VMEXIT.
7635 */
7636HMSVM_EXIT_DECL hmR0SvmExitXcptPFNested(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7637{
7638 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7639
7640 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7641
7642 /* See AMD spec. 15.12.15 "#PF (Page Fault)". */
7643 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7644 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1;
7645 uint64_t const uFaultAddress = pVmcb->ctrl.u64ExitInfo2;
7646
7647 Log4(("#PFNested: uFaultAddress=%#RX64 CS:RIP=%#04x:%#RX64 u32ErrCode=%#RX32 CR3=%#RX64\n", uFaultAddress, pCtx->cs.Sel,
7648 pCtx->rip, u32ErrCode, pCtx->cr3));
7649
7650 /* If it's a vectoring #PF, emulate injecting the original event injection as PGMTrap0eHandler() is incapable
7651 of differentiating between instruction emulation and event injection that caused a #PF. See @bugref{6607}. */
7652 if (pSvmTransient->fVectoringPF)
7653 {
7654 Assert(pVCpu->hm.s.Event.fPending);
7655 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7656 }
7657
7658 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
7659
7660 TRPMAssertXcptPF(pVCpu, uFaultAddress, u32ErrCode);
7661 int rc = PGMTrap0eHandler(pVCpu, u32ErrCode, CPUMCTX2CORE(pCtx), (RTGCPTR)uFaultAddress);
7662
7663 Log4(("#PFNested: rc=%Rrc\n", rc));
7664
7665 if (rc == VINF_SUCCESS)
7666 {
7667 /* Successfully synced shadow pages tables or emulated an MMIO instruction. */
7668 TRPMResetTrap(pVCpu);
7669 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
7670 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
7671 return rc;
7672 }
7673
7674 if (rc == VINF_EM_RAW_GUEST_TRAP)
7675 {
7676 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
7677
7678 if (!pSvmTransient->fVectoringDoublePF)
7679 {
7680 /* It's a nested-guest page fault and needs to be reflected to the nested-guest. */
7681 u32ErrCode = TRPMGetErrorCode(pVCpu); /* The error code might have been changed. */
7682 TRPMResetTrap(pVCpu);
7683 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
7684 }
7685 else
7686 {
7687 /* A nested-guest page-fault occurred during delivery of a page-fault. Inject #DF. */
7688 TRPMResetTrap(pVCpu);
7689 hmR0SvmSetPendingXcptDF(pVCpu);
7690 Log4(("#PF: Pending #DF due to vectoring #PF\n"));
7691 }
7692
7693 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
7694 return VINF_SUCCESS;
7695 }
7696
7697 TRPMResetTrap(pVCpu);
7698 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
7699 return rc;
7700}
7701
7702
7703/**
7704 * \#VMEXIT handler for CLGI (SVM_EXIT_CLGI). Conditional \#VMEXIT.
7705 */
7706HMSVM_EXIT_DECL hmR0SvmExitClgi(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7707{
7708 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7709
7710#ifdef VBOX_STRICT
7711 PCSVMVMCB pVmcbTmp = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7712 Assert(pVmcbTmp);
7713 Assert(!pVmcbTmp->ctrl.IntCtrl.n.u1VGifEnable);
7714 RT_NOREF(pVmcbTmp);
7715#endif
7716
7717 /** @todo Stat. */
7718 /* STAM_COUNTER_INC(&pVCpu->hm.s.StatExitClgi); */
7719 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7720 VBOXSTRICTRC rcStrict = IEMExecDecodedClgi(pVCpu, cbInstr);
7721 return VBOXSTRICTRC_VAL(rcStrict);
7722}
7723
7724
7725/**
7726 * \#VMEXIT handler for STGI (SVM_EXIT_STGI). Conditional \#VMEXIT.
7727 */
7728HMSVM_EXIT_DECL hmR0SvmExitStgi(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7729{
7730 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7731
7732#ifdef VBOX_STRICT
7733 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7734 Assert(pVmcb);
7735 Assert(!pVmcb->ctrl.IntCtrl.n.u1VGifEnable);
7736 RT_NOREF(pVmcb);
7737#endif
7738
7739 /** @todo Stat. */
7740 /* STAM_COUNTER_INC(&pVCpu->hm.s.StatExitStgi); */
7741 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7742 VBOXSTRICTRC rcStrict = IEMExecDecodedStgi(pVCpu, cbInstr);
7743 return VBOXSTRICTRC_VAL(rcStrict);
7744}
7745
7746
7747/**
7748 * \#VMEXIT handler for VMLOAD (SVM_EXIT_VMLOAD). Conditional \#VMEXIT.
7749 */
7750HMSVM_EXIT_DECL hmR0SvmExitVmload(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7751{
7752 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7753
7754#ifdef VBOX_STRICT
7755 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7756 Assert(pVmcb);
7757 Assert(!pVmcb->ctrl.LbrVirt.n.u1VirtVmsaveVmload);
7758 RT_NOREF(pVmcb);
7759#endif
7760
7761 /** @todo Stat. */
7762 /* STAM_COUNTER_INC(&pVCpu->hm.s.StatExitVmload); */
7763 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7764 VBOXSTRICTRC rcStrict = IEMExecDecodedVmload(pVCpu, cbInstr);
7765 if (rcStrict == VINF_SUCCESS)
7766 {
7767 /* We skip flagging changes made to LSTAR, STAR, SFMASK and other MSRs as they are always re-loaded. */
7768 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS
7769 | HM_CHANGED_GUEST_TR
7770 | HM_CHANGED_GUEST_LDTR);
7771 }
7772 return VBOXSTRICTRC_VAL(rcStrict);
7773}
7774
7775
7776/**
7777 * \#VMEXIT handler for VMSAVE (SVM_EXIT_VMSAVE). Conditional \#VMEXIT.
7778 */
7779HMSVM_EXIT_DECL hmR0SvmExitVmsave(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7780{
7781 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7782
7783#ifdef VBOX_STRICT
7784 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7785 Assert(pVmcb);
7786 Assert(!pVmcb->ctrl.LbrVirt.n.u1VirtVmsaveVmload);
7787 RT_NOREF(pVmcb);
7788#endif
7789
7790 /** @todo Stat. */
7791 /* STAM_COUNTER_INC(&pVCpu->hm.s.StatExitVmsave); */
7792 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7793 VBOXSTRICTRC rcStrict = IEMExecDecodedVmsave(pVCpu, cbInstr);
7794 return VBOXSTRICTRC_VAL(rcStrict);
7795}
7796
7797
7798/**
7799 * \#VMEXIT handler for INVLPGA (SVM_EXIT_INVLPGA). Conditional \#VMEXIT.
7800 */
7801HMSVM_EXIT_DECL hmR0SvmExitInvlpga(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7802{
7803 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7804 /** @todo Stat. */
7805 /* STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpga); */
7806 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7807 VBOXSTRICTRC rcStrict = IEMExecDecodedInvlpga(pVCpu, cbInstr);
7808 return VBOXSTRICTRC_VAL(rcStrict);
7809}
7810
7811
7812/**
7813 * \#VMEXIT handler for STGI (SVM_EXIT_VMRUN). Conditional \#VMEXIT.
7814 */
7815HMSVM_EXIT_DECL hmR0SvmExitVmrun(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7816{
7817 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7818 /** @todo Stat. */
7819 /* STAM_COUNTER_INC(&pVCpu->hm.s.StatExitVmrun); */
7820#if 0
7821 VBOXSTRICTRC rcStrict;
7822 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7823 rcStrict = IEMExecDecodedVmrun(pVCpu, cbInstr);
7824 Log4(("IEMExecDecodedVmrun: returned %d\n", VBOXSTRICTRC_VAL(rcStrict)));
7825 if (rcStrict == VINF_SUCCESS)
7826 {
7827 rcStrict = VINF_SVM_VMRUN;
7828 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
7829 }
7830 return VBOXSTRICTRC_VAL(rcStrict);
7831#endif
7832 return VERR_EM_INTERPRETER;
7833}
7834
7835
7836/**
7837 * Nested-guest \#VMEXIT handler for debug exceptions (SVM_EXIT_XCPT_1).
7838 * Unconditional \#VMEXIT.
7839 */
7840HMSVM_EXIT_DECL hmR0SvmNestedExitXcptDB(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7841{
7842 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7843
7844 /* If this #DB is the result of delivering an event, go back to the interpreter. */
7845 /** @todo if triple-fault is returned in nested-guest scenario convert to a
7846 * shutdown VMEXIT. */
7847 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7848 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
7849 {
7850 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingInterpret);
7851 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7852 }
7853
7854 hmR0SvmSetPendingXcptDB(pVCpu);
7855 return VINF_SUCCESS;
7856}
7857
7858
7859/**
7860 * Nested-guest \#VMEXIT handler for breakpoint exceptions (SVM_EXIT_XCPT_3).
7861 * Conditional \#VMEXIT.
7862 */
7863HMSVM_EXIT_DECL hmR0SvmNestedExitXcptBP(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7864{
7865 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7866
7867 /** @todo if triple-fault is returned in nested-guest scenario convert to a
7868 * shutdown VMEXIT. */
7869 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7870
7871 SVMEVENT Event;
7872 Event.u = 0;
7873 Event.n.u1Valid = 1;
7874 Event.n.u3Type = SVM_EVENT_EXCEPTION;
7875 Event.n.u8Vector = X86_XCPT_BP;
7876 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
7877 return VINF_SUCCESS;
7878}
7879
7880#endif /* VBOX_WITH_NESTED_HWVIRT */
7881
7882
7883/** @} */
7884
Note: See TracBrowser for help on using the repository browser.

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