VirtualBox

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

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

HMSVMR0.cpp: rdtscp fix (thought I fixed this already). bugref:9044

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

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