VirtualBox

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

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

VMM/HMSVMR0: space.

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