VirtualBox

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

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

VMM/HMSVMR0: Nested Hw.virt: Fixes

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

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